Prescriptive Analytics & Decision Intelligence
Overview / Module 4 / Day 32
Module 4 · Scheduling, Routing and Constraint Programming · Day 32 of 80

Staff Scheduling I: Coverage and Labour Rules

The Montreal DC's warehouse runs three shifts a day, seven days a week, with 34 people: forklift drivers (who can also pick) and pickers. Every week the supervisor builds the roster by hand. Today you build it with CP-SAT: enough people on every shift, every legal rule respected, at least pay. Then you check the supervisor's roster with the same rules.

▶
Video for Day 32 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:45
32.1 The data and the rules
0:45–1:45
32.2 Coverage only
1:45–2:00
Break
2:00–2:45
32.3 With the labour rules
2:45–3:45
32.4 The supervisor's roster; a planted bug
3:45–4:00
Break
4:00–4:45
Mini-project: the Christmas peak
4:45–5:00
Commit with Git + checklist

32.1 The data and the rules

Shifts: day 07:00–15:00, evening 15:00–23:00 ($1.50 an hour premium), night 23:00–07:00 ($2.75). Full-timers are guaranteed 40 hours (5 shifts) a week; part-timers work at most 3 shifts.

The general rules of Ontario's Employment Standards Act, 2000 (ESA) for hours of work, as the province's guides summarize them:

  • At most 8 hours a day (or the regular work day, if longer) and 48 hours a week, unless the employee agrees in writing to more.
  • 11 consecutive hours off in every 24-hour period, and at least 24 consecutive hours off each work week (or 48 in every two weeks).
  • Overtime pay at 1.5 times the regular rate for hours over 44 in a work week.

(These are general rules with exceptions and special rules for some industries and jobs. A real roster system needs them checked by someone qualified; this is a course model, not legal advice.)

With 8-hour shifts, the rules become simple constraints:

RuleIn the model
48 hours a weekat most 6 shifts; this also guarantees a day off, so 24 hours off in the week
11 hours off in every 24no evening shift followed by a day shift (8 hours off), no night followed by a day or an evening (0 or 8 hours)
Overtime after 44 hoursthe 6th shift has 4 overtime hours at time and a half

dc_rules stores these numbers, so a rule change is a data change. Create day32/roster.py:

"""Day 32: a legal weekly roster for the Montreal DC warehouse, with CP-SAT.

Import it:  from roster import load_roster_data, build_roster, solve_roster, check_roster, roster_cost
"""
import pandas as pd
from ortools.sat.python import cp_model

DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
SHIFTS = ["D", "E", "N"]
# Shift pairs on consecutive days that leave less than 11 hours off in some 24-hour period:
# evening (ends 23:00) then day (starts 07:00): 8 hours; night (ends 07:00) then day (07:00): none;
# night (ends 07:00) then evening (starts 15:00): 8 hours.
TOO_CLOSE = [("E", "D"), ("N", "D"), ("N", "E")]


def load_roster_data(con):
    staff = con.sql("SELECT * FROM dc_staff ORDER BY employee_id").df().set_index("employee_id")
    shifts = con.sql("SELECT * FROM dc_shifts").df().set_index("shift")
    coverage = {(r.day, r.shift, r.role): int(r.people) for r in con.sql("SELECT * FROM dc_coverage").df().itertuples()}
    rules = {r: v for r, v, _ in con.sql("SELECT * FROM dc_rules").fetchall()}
    last_sunday = dict(con.sql("SELECT * FROM dc_last_sunday").fetchall())
    return staff, shifts, coverage, rules, last_sunday


def can_do(staff, e, role):
    """Forklift drivers can also pick; pickers can't drive a forklift."""
    return role == "picker" or staff.role[e] == "forklift"


def build_roster(staff, shifts, coverage, rules, last_sunday, labour_rules=True, carry_over=True, agency_rate=None):
    """work[e, d, s, r] = 1 if employee e works shift s on day d in role r. Minimize the week's pay.
    CP-SAT works with whole numbers, so pay is counted in half-cents (time and a half adds half a wage)."""
    m = cp_model.CpModel()
    E = list(staff.index)
    roles = ["picker", "forklift"]
    work = {(e, d, s, r): m.new_bool_var(f"work_{e}_{d}_{s}_{r}")
            for e in E for d in DAYS for s in SHIFTS for r in roles if can_do(staff, e, r)}
    on = {(e, d, s): sum(work[e, d, s, r] for r in roles if (e, d, s, r) in work) for e in E for d in DAYS for s in SHIFTS}
    for e in E:
        for d in DAYS:
            m.add(sum(on[e, d, s] for s in SHIFTS) <= 1)                           # one shift a day
    agency = {}
    if agency_rate is not None:                                                      # agency pickers (not drivers)
        agency = {(d, s, r): m.new_int_var(0, 20, f"agency_{d}_{s}") for (d, s, r) in coverage if r == "picker"}
    for (d, s, r), people in coverage.items():
        m.add(sum(work[e, d, s, r] for e in E if (e, d, s, r) in work) + agency.get((d, s, r), 0) >= people)  # enough people
    hours = int(rules["hours_per_shift"])
    shifts_worked = {e: sum(on[e, d, s] for d in DAYS for s in SHIFTS) for e in E}
    if labour_rules:
        max_shifts = int(rules["max_hours_per_week"]) // hours                    # 48 hours: 6 shifts, so a day off
        for e in E:
            limit = int(rules["part_time_max_shifts"]) if staff.contract[e] == "part-time" else max_shifts
            m.add(shifts_worked[e] <= limit)
            for a, b in zip(DAYS, DAYS[1:]):
                for s1, s2 in TOO_CLOSE:
                    m.add(on[e, a, s1] + on[e, b, s2] <= 1)                          # 11 hours off in every 24
            if carry_over and last_sunday[e] in SHIFTS:
                for s1, s2 in TOO_CLOSE:
                    if s1 == last_sunday[e]:
                        m.add(on[e, "Mon", s2] == 0)                                 # last Sunday counts too
    # pay, in half-cents: full-timers are paid at least their guaranteed shifts; time and a half after 44 hours
    cost = []
    paid = {}
    for e in E:
        wage = int(round(200 * staff.hourly_wage[e]))                             # half-cents an hour
        if staff.contract[e] == "full-time":
            paid[e] = m.new_int_var(int(rules["full_time_min_shifts"]), 7, f"paid_{e}")
            m.add(paid[e] >= shifts_worked[e])
        else:
            paid[e] = shifts_worked[e]
        overtime = m.new_int_var(0, 7 * hours, f"overtime_{e}")
        m.add(overtime >= hours * shifts_worked[e] - int(rules["overtime_after_hours"]))
        cost.append(wage * hours * paid[e] + (wage // 2) * overtime)                 # the extra half for overtime hours
        cost += [int(round(200 * shifts.premium_per_hour[s])) * hours * on[e, d, s] for d in DAYS for s in SHIFTS]
    if agency:
        cost.append(int(round(200 * agency_rate)) * hours * sum(agency.values()))
    m.pay = sum(cost)                                                                # kept for Day 33
    m.minimize(m.pay)
    m.agency = agency
    return m, work


def dollars(half_cents):
    return round(half_cents / 200, 2)


def solve_roster(m, work, seconds=120):
    solver = cp_model.CpSolver()
    solver.parameters.max_time_in_seconds = seconds
    solver.parameters.num_workers = 8
    solver.parameters.interleave_search = True      # deterministic parallel search: the same roster on every run
    status = solver.solve(m)
    rows = [(e, d, s, r) for (e, d, s, r), v in work.items() if solver.value(v)] if status in (cp_model.OPTIMAL, cp_model.FEASIBLE) else []
    return solver, status, pd.DataFrame(rows, columns=["employee_id", "day", "shift", "role"])


def check_roster(roster, staff, coverage, rules, last_sunday):
    """An independent check of a roster against every rule. Returns a list of problems (empty if legal)."""
    problems = []
    for (d, s, r), people in coverage.items():
        n = ((roster["day"] == d) & (roster["shift"] == s) & (roster["role"] == r)).sum()
        if n < people:
            problems.append(f"{d} {s} {r}: {n} of {people}")
    for e, g in roster.groupby("employee_id"):
        if g["day"].duplicated().any():
            problems.append(f"{e}: two shifts on one day")
        if any(not can_do(staff, e, r) for r in g.role):
            problems.append(f"{e}: works a role they can't do")
        limit = int(rules["part_time_max_shifts"]) if staff.contract[e] == "part-time" else int(rules["max_hours_per_week"]) // 8
        if len(g) > limit:
            problems.append(f"{e}: {len(g)} shifts, over {limit}")
        day_shift = dict(zip(g["day"], g["shift"]))
        prev = [("Sun-1", last_sunday[e])] + [(d, day_shift.get(d)) for d in DAYS]
        for (a, s1), (b, s2) in zip(prev, prev[1:]):
            if (s1, s2) in TOO_CLOSE:
                problems.append(f"{e}: {s1} on {a} then {s2} on {b}: less than 11 hours off")
    return problems


def roster_cost(roster, staff, shifts, rules):
    total = 0.0
    for e in staff.index:
        g = roster[roster.employee_id == e]
        n, wage = len(g), staff.hourly_wage[e]
        paid = max(n, int(rules["full_time_min_shifts"])) if staff.contract[e] == "full-time" else n
        total += wage * 8 * paid + 0.5 * wage * max(0, 8 * n - rules["overtime_after_hours"])
        total += sum(8 * shifts.premium_per_hour[s] for s in g["shift"])
    return round(total, 2)

Four points about this model:

  • work[e, d, s, r] exists only for roles the employee can do (can_do): a picker has no forklift variables at all.
  • The pay is in half-cents so that time and a half stays a whole number (31.4).
  • check_roster is an independent checker, written separately from the model. Every roster, the model's or a person's, goes through it.
  • The rest rule needs last Sunday: someone who finished at 23:00 on Sunday can't start at 07:00 on Monday.

Then day32/run_roster.py:

# ---------- 32.1 The data ----------
print(staff.groupby(["role", "contract"]).size().rename("people").to_string())
cov = pd.Series(coverage).rename_axis(["day", "shift", "role"]).unstack("day")[DAYS]
print(cov.to_string())
print(f"{sum(coverage.values())} shifts to fill; full-timers are paid for at least {rules['full_time_min_shifts']:.0f} shifts")
role      contract
forklift  full-time    10
          part-time     2
picker    full-time    16
          part-time     6
day             Mon  Tue  Wed  Thu  Fri  Sat  Sun
shift role
D     forklift    3    3    3    3    3    2    2
      picker      7    7    7    7    7    5    5
E     forklift    2    2    2    2    2    2    2
      picker      6    6    6    6    6    4    4
N     forklift    1    1    1    1    1    1    1
      picker      3    3    3    3    3    2    2
142 shifts to fill; full-timers are paid for at least 5 shifts

32.2 Coverage only

# ---------- 32.2 Coverage only ----------
m, work = build_roster(staff, shifts, coverage, rules, last_sunday, labour_rules=False)
solver, status, roster = solve_roster(m, work)
problems = check_roster(roster, staff, coverage, rules, last_sunday)
print(f"coverage only: {solver.status_name(status)}, ${dollars(solver.objective_value):,.2f}; {len(problems)} rule breaks, e.g.")
for p in problems[:5]:
    print("   ", p)
coverage only: OPTIMAL, $28,836.40; 30 rule breaks, e.g.
    E01: N on Tue then D on Wed: less than 11 hours off
    E02: E on Sun-1 then D on Mon: less than 11 hours off
    E06: N on Thu then E on Fri: less than 11 hours off
    E07: N on Sun-1 then E on Mon: less than 11 hours off
    E07: E on Wed then D on Thu: less than 11 hours off

Cheapest possible, and illegal: 30 rule breaks, all of them too little rest. Without the rules, the model happily puts someone on a night shift and the next day's 07:00 shift.

32.3 With the labour rules

# ---------- 32.3 With the labour rules ----------
m, work = build_roster(staff, shifts, coverage, rules, last_sunday)
solver, status, roster = solve_roster(m, work)
problems = check_roster(roster, staff, coverage, rules, last_sunday)
print(f"with the rules: {solver.status_name(status)}, ${dollars(solver.objective_value):,.2f} "
      f"(checked again: ${roster_cost(roster, staff, shifts, rules):,.2f}); {len(problems)} rule breaks")
per = roster.groupby("employee_id").size().reindex(staff.index, fill_value=0)
print("shifts per person:", per.groupby(staff.contract).value_counts().sort_index().to_dict())
grid = roster.pivot(index="employee_id", columns="day", values="shift").reindex(columns=DAYS).fillna(".")
print(grid.head(12).to_string())
with the rules: OPTIMAL, $28,876.48 (checked again: $28,876.48); 0 rule breaks
shifts per person: {('full-time', 5): 26, ('part-time', 0): 4, ('part-time', 3): 4}
day         Mon Tue Wed Thu Fri Sat Sun
employee_id
E01           E   E   E   .   E   N   .
E02           .   E   E   E   E   .   D
E03           D   D   D   .   D   D   .
E04           E   .   D   D   D   .   N
E06           D   .   N   N   N   .   E
E07           N   .   D   E   E   E   .
E08           N   N   N   N   .   .   E
E09           D   D   N   N   .   D   .
E10           D   D   .   D   N   .   D
E12           E   .   .   D   D   E   E
E13           N   .   D   D   N   .   D
E14           N   .   D   D   D   .   D

$28,876.48: legality costs only $40.08 a week here. The checker agrees with the model on both the rules and the pay. Every full-timer works exactly their 5 guaranteed shifts, and only 4 part-timers are needed. Read the grid: no E followed by D, no N followed by D or E, at least one day off each.

32.4 The supervisor's roster

# ---------- 32.4 Against the supervisor's roster ----------
current = con.sql("SELECT * FROM dc_current_roster").df()
problems = check_roster(current, staff, coverage, rules, last_sunday)
print(f"the supervisor's roster: ${roster_cost(current, staff, shifts, rules):,.2f}; {len(problems)} rule breaks:")
for p in problems:
    print("   ", p)
cur = current.groupby("employee_id").size().reindex(staff.index, fill_value=0)
print("shifts per person:", cur.groupby(staff.contract).value_counts().sort_index().to_dict())
the supervisor's roster: $31,380.16; 5 rule breaks:
    E02: E on Sun-1 then D on Mon: less than 11 hours off
    E13: N on Sun-1 then D on Mon: less than 11 hours off
    E14: E on Sun-1 then D on Mon: less than 11 hours off
    E15: E on Sun-1 then D on Mon: less than 11 hours off
    E19: N on Sun-1 then D on Mon: less than 11 hours off
shifts per person: {('full-time', 4): 12, ('full-time', 5): 14, ('part-time', 3): 8}
  • The hand-made roster costs $31,380.16: $2,503.68 a week more (about $130,000 a year). Twelve full-timers work only 4 shifts but are paid for 5, while all 8 part-timers work 3 shifts.
  • It breaks the rest rule 5 times, all on Monday morning: the supervisor built the week without looking at who worked last Sunday evening or night.

Decision it supports: who works which shift, legally and at least cost.

Other decisions you can support the same way: nurse rosters · call-centre shifts · store staffing · airline crew days off.

The planted bug

day32/bug_carry_over.py builds the roster "only looking at next week". Run it.

con = duckdb.connect("northbound.duckdb", read_only=True)
staff, shifts, coverage, rules, last_sunday = load_roster_data(con)
m, work = build_roster(staff, shifts, coverage, rules, last_sunday, carry_over=False)
solver, status, roster = solve_roster(m, work)
print(f"{solver.status_name(status)}: ${dollars(solver.objective_value):,.2f}")
for p in check_roster(roster, staff, coverage, rules, last_sunday):
    print("   ", p)
What happens, and why
OPTIMAL: $28,876.48
    E08: N on Sun-1 then E on Mon: less than 11 hours off
    E14: E on Sun-1 then D on Mon: less than 11 hours off
    E15: E on Sun-1 then D on Mon: less than 11 hours off
    E24: E on Sun-1 then D on Mon: less than 11 hours off
    E27: E on Sun-1 then D on Mon: less than 11 hours off
    E34: N on Sun-1 then E on Mon: less than 11 hours off

Same cost, "optimal", and six breaks of the 11-hour rule on Monday, the same mistake as the supervisor's. A week is not independent of the week before: schedules have state at the boundary (last week's shifts, hours already worked, days off already taken). Rolling plans (Day 39) carry it forward every week. The independent checker caught what the model didn't know.

Mini-project: the Christmas peak

In December, the DC needs 10% more people on every shift (rounded up), and in the busiest week 20% more. Can the staff cover it legally? If not, the DC can book agency pickers at $36 an hour (agencies can't supply certified forklift drivers). What does each week cost, and how many agency shifts are needed?

Solution
"""Day 32 mini-project: Christmas peak weeks need 10% and 20% more people on every shift (rounded up).
Can the staff cover it legally? With agency pickers at $36 an hour, what does each week cost?

Run from the repository root (after day06/load_tables.py):  python day32/mini_project_peak.py
"""
import math
import sys

import duckdb
from ortools.sat.python import cp_model

sys.path.insert(0, "day32")
from roster import DAYS, build_roster, check_roster, dollars, load_roster_data, solve_roster

con = duckdb.connect("northbound.duckdb", read_only=True)
staff, shifts, coverage, rules, last_sunday = load_roster_data(con)
for extra in (0.0, 0.10, 0.20):
    week = {k: math.ceil(v * (1 + extra)) for k, v in coverage.items()}
    for agency in (None, 36.0):
        m, work = build_roster(staff, shifts, week, rules, last_sunday, agency_rate=agency)
        solver, status, roster = solve_roster(m, work)
        label = f"+{extra:.0%}, {sum(week.values())} shifts, {'with' if agency else 'no'} agency:"
        if status not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
            print(label, solver.status_name(status))
            continue
        n = roster.groupby("employee_id").size()
        temps = sum(solver.value(v) for v in m.agency.values())
        breaks = [p for p in check_roster(roster, staff, week, rules, last_sunday) if not p.startswith(tuple(DAYS))]
        legal = not breaks                                       # (coverage gaps filled by agency are not rule breaks)
        print(label, f"${dollars(solver.objective_value):,.2f}; agency shifts {temps}; staff on 6 shifts {(n == 6).sum()}; "
              f"legal: {legal}")
+0%, 142 shifts, no agency: $28,876.48; agency shifts 0; staff on 6 shifts 0; legal: True
+0%, 142 shifts, with agency: $28,876.48; agency shifts 0; staff on 6 shifts 0; legal: True
+10%, 184 shifts, no agency: INFEASIBLE
+10%, 184 shifts, with agency: $39,231.96; agency shifts 8; staff on 6 shifts 22; legal: True
+20%, 194 shifts, no agency: INFEASIBLE
+20%, 194 shifts, with agency: $41,951.96; agency shifts 18; staff on 6 shifts 22; legal: True
  • The staff alone can't cover either peak week: 184 shifts against at most 180 (26 full-timers × 6 + 8 part-timers × 3). The model says so in seconds ("infeasible"), not after a week of trying.
  • With agency pickers, the +10% week costs $39,231.96 with 8 agency shifts, and 22 full-timers work a 6th shift (with 4 hours of overtime each). Overtime is cheaper than agency, up to the 48-hour limit.
  • The +20% week needs 18 agency shifts: $41,951.96.

Note to the DC manager: "For peak weeks, book 8 agency picker shifts (+10%) or 18 (+20%) now, and plan 22 sixth shifts with overtime. No roster without agency staff is legal at these levels."

Commit

git add .
git commit -m "Day 32: legal weekly roster with CP-SAT"
git push

Day 32 checklist

  • I can turn hours-of-work rules into roster constraints (shift limits, forbidden shift pairs).
  • I keep rule values in data, not in code.
  • I check every roster with an independent checker, the model's included.
  • I carry last week's shifts into the new week.
  • I compared a hand-made roster with the model's on cost and legality.
  • I can tell when a requirement is impossible, and price the way out (agency staff).

Sources: Ontario: Your guide to the Employment Standards Act, hours of work · Ontario: Information about hours of work and overtime pay (2024) · Ontario: Industries and jobs with exemptions or special rules, terms and definitions