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

Mini-project: A 4-Week Warehouse Roster

December at the Montreal DC: four weeks, the last one a +10% peak. Days 32 and 33 built one week. Today's mini-project builds a month: rest rules that cross from one week into the next, Day 33's requests, fairness measured over the month, and a question from Day 33's memo: should two pickers be certified as forklift drivers so that everyone gets every other weekend off?

▶
Video for Day 35 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:30
35.1 The brief and the model
0:30–1:15
35.2 Four normal weeks in one model
1:15–1:45
35.3 December in one model
1:45–2:00
Break
2:00–2:45
35.4 December, one week at a time
2:45–3:45
35.5 Fairness policies
3:45–4:00
Break
4:00–4:45
35.6 The memo
4:45–5:00
Commit with Git + checklist

35.1 The brief and the model

  • Horizon: 4 weeks, 28 days; week 4 needs 10% more people on every shift (rounded up), with agency pickers at $36 an hour.
  • Rules: Day 32's, in every week; the 11-hour rest rule runs across week boundaries too.
  • Requests: Day 33's 47 requests for week 1, at $50 each.
  • Fairness over the month (full-timers): nights worked, and weekends worked (a weekend counts if any shift falls on Saturday or Sunday).
  • Options: two weekend teams that alternate (every other weekend off); certify E13 and E14 as forklift drivers (forklift_certification: $1,800 each for the course, $1.50 an hour more).

Create day35/four_weeks.py:

"""Day 35 mini-project: a 4-week roster for the Montreal DC warehouse (December: the 4th week is the peak).

Import it:  from four_weeks import build_four_weeks, solve_four_weeks
"""
import math

import pandas as pd
from ortools.sat.python import cp_model

from roster import DAYS, SHIFTS, TOO_CLOSE

ROLES = ["picker", "forklift"]


def calendar(weeks):
    return [(w, d) for w in range(1, weeks + 1) for d in DAYS]


def build_four_weeks(staff, shifts, coverage, rules, last_sunday, weeks=4, peak=None, requests=None, weight=50.0,
                     max_nights=None, max_weekends=None, agency_rate=36.0, new_drivers=(), weekend_teams=None,
                     first_week=1, nights_so_far=None, raise_per_hour=0.0):
    """work[e, (w, d), s, r]. peak: {week: extra share of people}. new_drivers: pickers certified for forklifts.
    Fairness over the whole horizon: at most max_nights nights and max_weekends weekends worked per full-timer.
    Pay is in half-cents (Day 32); a broken week-1 request costs `weight` dollars."""
    m = cp_model.CpModel()
    E, cal = list(staff.index), calendar(weeks)
    drives = {e: staff.role[e] == "forklift" or e in new_drivers for e in E}
    work = {(e, c, s, r): m.new_bool_var(f"w_{e}_{c[0]}{c[1]}_{s}_{r}")
            for e in E for c in cal for s in SHIFTS for r in ROLES if r == "picker" or drives[e]}
    on = {(e, c, s): sum(work[e, c, s, r] for r in ROLES if (e, c, s, r) in work) for e in E for c in cal for s in SHIFTS}
    need = {}
    for (w, d) in cal:
        extra = (peak or {}).get(w, 0.0)
        for s in SHIFTS:
            for r in ROLES:
                need[(w, d), s, r] = math.ceil(coverage[d, s, r] * (1 + extra))
    agency = {(c, s): m.new_int_var(0, 20, f"agency_{c[0]}{c[1]}_{s}") for c in cal for s in SHIFTS}
    for (c, s, r), people in need.items():
        m.add(sum(work[e, c, s, r] for e in E if (e, c, s, r) in work) + (agency[c, s] if r == "picker" else 0) >= people)
    hours = int(rules["hours_per_shift"])
    cost = []
    for e in E:
        wage = int(round(200 * (staff.hourly_wage[e] + (raise_per_hour if e in new_drivers else 0.0))))
        for c in cal:
            m.add(sum(on[e, c, s] for s in SHIFTS) <= 1)
        days = [None] + cal
        for a, b in zip(days, days[1:]):                         # 11 hours off, across weeks too
            for s1, s2 in TOO_CLOSE:
                if a is None:
                    if last_sunday[e] == s1:
                        m.add(on[e, b, s2] == 0)
                else:
                    m.add(on[e, a, s1] + on[e, b, s2] <= 1)
        for w in range(1, weeks + 1):
            n = sum(on[e, (w, d), s] for d in DAYS for s in SHIFTS)
            limit = int(rules["part_time_max_shifts"]) if staff.contract[e] == "part-time" else int(rules["max_hours_per_week"]) // hours
            m.add(n <= limit)
            paid = n
            if staff.contract[e] == "full-time":
                paid = m.new_int_var(int(rules["full_time_min_shifts"]), 7, f"paid_{e}_{w}")
                m.add(paid >= n)
            ot = m.new_int_var(0, 7 * hours, f"ot_{e}_{w}")
            m.add(ot >= hours * n - int(rules["overtime_after_hours"]))
            cost.append(wage * hours * paid + (wage // 2) * ot)
        cost += [int(round(200 * shifts.premium_per_hour[s])) * hours * on[e, c, s] for c in cal for s in SHIFTS]
    cost.append(int(round(200 * agency_rate)) * hours * sum(agency.values()))
    m.pay = sum(cost)
    # fairness over the horizon (full-timers)
    m.nights, m.weekends = {}, {}
    for e in staff.index[staff.contract == "full-time"]:
        m.nights[e] = m.new_int_var(0, 7 * weeks, f"nights_{e}")
        m.add(m.nights[e] == sum(on[e, c, "N"] for c in cal))
        worked = []
        for w in range(1, weeks + 1):
            ww = m.new_bool_var(f"weekend_{e}_{w}")
            for d in ("Sat", "Sun"):
                for s in SHIFTS:
                    m.add(ww >= on[e, (w, d), s])
            worked.append(ww)
        m.weekends[e] = m.new_int_var(0, weeks, f"weekends_{e}")
        m.add(m.weekends[e] == sum(worked))
        m.weekend_worked = getattr(m, "weekend_worked", {})
        for w, ww in enumerate(worked, start=1):
            m.weekend_worked[e, w] = ww
        if weekend_teams is not None:                            # team A works odd weekends, team B even ones
            for w, ww in enumerate(worked, start=first_week):
                if (w % 2 == 1) != (weekend_teams[e] == "A"):
                    m.add(ww == 0)
        if max_nights is not None:
            m.add(m.nights[e] + (nights_so_far or {}).get(e, 0) <= max_nights)
        if max_weekends is not None:
            m.add(m.weekends[e] <= max_weekends)
    # a redundant row that helps the search: each weekend day needs enough full-timers working that weekend
    full = list(staff.index[staff.contract == "full-time"])
    part = [e for e in E if e not in full]
    for w in range(1, weeks + 1):
        for d in ("Sat", "Sun"):
            people = sum(need[(w, d), s, r] for s in SHIFTS for r in ROLES)
            m.add(sum(m.weekend_worked[e, w] for e in full)
                  + sum(on[e, (w, d), s] for e in part for s in SHIFTS)
                  + sum(agency[(w, d), s] for s in SHIFTS) >= people)
    broken = []
    if requests is not None:                                     # Day 33's requests, for week 1
        for r in requests.itertuples():
            b = m.new_bool_var(f"broken_{r.Index}")
            if r.request == "day_off":
                xs = [on[r.employee_id, (1, r.day), s] for s in SHIFTS]
            elif r.request == "no_nights":
                xs = [on[r.employee_id, (1, d), "N"] for d in DAYS]
            else:
                xs = [on[r.employee_id, (1, d), s] for d in DAYS for s in SHIFTS if s != r.shift]
            for x in xs:
                m.add(b >= x)
            broken.append((int(r.priority), b))
    m.broken = broken
    m.minimize(m.pay + int(round(200 * weight)) * sum(p * b for p, b in broken))
    m.agency, m.work = agency, work
    return m


def teams(staff):
    """Every other weekend off: full-timers alternate, by employee number."""
    full = staff.index[staff.contract == "full-time"]
    return {e: "A" if k % 2 == 0 else "B" for k, e in enumerate(full)}


def rolling(staff, shifts, coverage, rules, last_sunday, weeks=4, peak=None, requests=None, max_nights=None,
            weekend_teams=None, work=10.0, **kw):
    """Plan one week at a time: carry last Sunday's shifts and the nights worked so far into the next week."""
    last, nights, total, rosters, info = dict(last_sunday), {}, {}, [], []
    for w in range(1, weeks + 1):
        m = build_four_weeks(staff, shifts, coverage, rules, last, weeks=1, peak={1: (peak or {}).get(w, 0.0)},
                             requests=requests if w == 1 else None, max_nights=max_nights,
                             weekend_teams=weekend_teams, first_week=w, nights_so_far=nights, **kw)
        out, r = solve_four_weeks(m, work)
        if "pay" not in out:
            return {"status": f"week {w}: {out['status']}"}, None
        r["week"] = w
        rosters.append(r)
        sunday = r[r.day == "Sun"].set_index("employee_id")["shift"].to_dict()
        last = {e: sunday.get(e, "off") for e in staff.index}
        for e, n in r[r["shift"] == "N"].groupby("employee_id").size().items():
            nights[e] = nights.get(e, 0) + n
        info.append(out)
    roster = pd.concat(rosters, ignore_index=True)
    full = staff.index[staff.contract == "full-time"]
    weekends = roster[roster.day.isin(["Sat", "Sun"]) & roster.employee_id.isin(full)].groupby("employee_id").week.nunique()
    night_counts = [nights.get(e, 0) for e in full]
    return {"status": "rolling, " + ", ".join(o["status"].lower() for o in info),
            "pay": round(sum(o["pay"] for o in info), 2), "bound": None,
            "agency_shifts": sum(o["agency_shifts"] for o in info), "broken": sum(o["broken"] for o in info),
            "most_nights": max(night_counts), "fewest_nights": min(night_counts),
            "most_weekends": int(weekends.reindex(full, fill_value=0).max()),
            "all_four_weekends": int((weekends == 4).sum())}, roster


def solve_four_weeks(m, work=40.0):
    s = cp_model.CpSolver()
    s.parameters.max_deterministic_time = work
    s.parameters.num_workers = 8
    s.parameters.interleave_search = True
    status = s.solve(m)
    ok = status in (cp_model.OPTIMAL, cp_model.FEASIBLE)
    roster = pd.DataFrame([(e, c[0], c[1], sh, r) for (e, c, sh, r), v in m.work.items() if ok and s.value(v)],
                          columns=["employee_id", "week", "day", "shift", "role"])
    out = {"status": s.status_name(status)}
    if ok:
        nights = [s.value(v) for v in m.nights.values()]
        weekends = [s.value(v) for v in m.weekends.values()]
        out.update(pay=round(s.value(m.pay) / 200, 2), bound=round(s.best_objective_bound / 200, 2),
                   agency_shifts=sum(s.value(v) for v in m.agency.values()),
                   broken=sum(s.value(b) for _, b in m.broken), most_nights=max(nights), fewest_nights=min(nights),
                   most_weekends=max(weekends), all_four_weekends=sum(x == 4 for x in weekends))
    return out, roster

Two parts are new. rolling plans one week at a time, carrying last Sunday's shifts and the nights worked so far into the next week. The redundant row ("each weekend day needs enough full-timers working that weekend") adds nothing a whole-number plan doesn't already satisfy, but it tightens the bound, as on Day 27.

35.2 Four normal weeks in one model

A known-answer check first: four normal weeks with no requests should cost four times Day 32's week.

# ---------- 35.2 Four normal weeks in one model ----------
out, roster = solve_four_weeks(build_four_weeks(staff, shifts, coverage, rules, last_sunday), work=40)
rows = [line("4 normal weeks, one model", out)]
print(f"4 x Day 32's week = ${4 * 28_876.48:,.2f}")
problems = []
prev = dict(last_sunday)
for w, g in roster.groupby("week"):
    problems += check_roster(g, staff, coverage, rules, prev)       # Day 32's checker, one week at a time
    sunday = g[g.day == "Sun"].set_index("employee_id")["shift"].to_dict()
    prev = {e: sunday.get(e, "off") for e in staff.index}
print(f"Day 32's checker, week by week: {len(problems)} rule breaks")
4 normal weeks, one model: OPTIMAL
4 x Day 32's week = $115,505.92
Day 32's checker, week by week: 0 rule breaks

$115,505.92, exactly 4 × $28,876.48, proven optimal, and Day 32's checker finds nothing wrong in any week.

35.3 December in one model, and 35.4 one week at a time

# ---------- 35.3 December in one model ----------
out, roster = solve_four_weeks(build_four_weeks(staff, shifts, coverage, rules, last_sunday, **DECEMBER), work=40)
rows.append(line("December, one model", out))

# ---------- 35.4 December, one week at a time ----------
out, roster = rolling(staff, shifts, coverage, rules, last_sunday, **DECEMBER)
rows.append(line("December, week by week", out))
print(pd.DataFrame(rows).to_string(index=False))
December, one model: FEASIBLE
December, week by week: rolling, optimal, optimal, optimal, optimal
                     plan       pay     bound  agency_shifts  broken  most_nights  fewest_nights  most_weekends  all_four_weekends
4 normal weeks, one model 115505.92 115505.92              0       0            9              0              4                 26
      December, one model 125861.40 125859.68              8       0           10              0              4                 26
   December, week by week 125861.40       NaN              8       0            9              0              4                 21
  • One model for the whole month finds $125,861.40 and proves no plan costs less than $125,859.68: within $2.
  • Week by week, each week solved to optimality, gives the same $125,861.40. Here the weeks hardly interact (only Sunday-to-Monday rest), so planning them one at a time loses nothing. When weeks interact more (monthly fairness, hours averaged over two weeks), week-by-week planning can lose money or even fail: see 35.5 and Day 39.
  • The month is unfair: some full-timers work 9 nights, others none; 21 of 26 work all four weekends.

35.5 Fairness policies

# ---------- 35.5 Fairness policies ----------
rows = []
team = teams(staff)
drivers = tuple(training.index)
for name, kw in [("today's rules", {}),
                 ("every other weekend", {"weekend_teams": team}),
                 ("every other weekend, 2 new drivers", {"weekend_teams": team, "new_drivers": drivers,
                                                         "raise_per_hour": float(training.raise_per_hour.iloc[0])}),
                 ("... and at most 6 nights", {"weekend_teams": team, "new_drivers": drivers, "max_nights": 6,
                                               "raise_per_hour": float(training.raise_per_hour.iloc[0])})]:
    out, roster = rolling(staff, shifts, coverage, rules, last_sunday, **DECEMBER, **kw)
    rows.append(line(name, out))
print(pd.DataFrame(rows).drop(columns="bound").to_string(index=False))
print(f"training {len(drivers)} drivers: ${training.course_cost.sum():,} once")
today's rules: rolling, optimal, optimal, optimal, optimal
every other weekend: week 4: INFEASIBLE
every other weekend, 2 new drivers: rolling, optimal, optimal, optimal, optimal
... and at most 6 nights: rolling, optimal, optimal, optimal, optimal
                              plan       pay  agency_shifts  broken  most_nights  fewest_nights  most_weekends  all_four_weekends
                     today's rules 125861.40            8.0     0.0          9.0            0.0            4.0               21.0
               every other weekend       NaN            NaN     NaN          NaN            NaN            NaN                NaN
every other weekend, 2 new drivers 126768.04           18.0     7.0         17.0            0.0            2.0                0.0
          ... and at most 6 nights 128075.88           20.0     7.0          6.0            0.0            2.0                0.0
training 2 drivers: $3,600 once
  • Every other weekend off, with today's drivers, is impossible in week 4: the peak weekend needs 16 forklift shifts, and with half the full-time drivers off each weekend the drivers can cover only 14 (Day 33 found the same limit). Agency staff can't drive forklifts.
  • With E13 and E14 certified, every-other-weekend works: $126,768.04 for the month, $906.64 more than today's rules (including the drivers' raise), plus $3,600 once for the courses. Nobody works more than 2 weekends; 7 week-1 requests are broken.
  • But nights become less fair (one person works 17 of 28): teams fix the weekends and push nights onto fewer people. Adding "at most 6 nights" costs another $1,307.84: $128,075.88.

35.6 The memo

A model memo

To: the DC manager. Re: December roster and the weekend policy.

"December can be covered legally for $125,861 over the four weeks, including 8 agency picker shifts in the peak week. All 47 week-1 requests can be granted.

Every other weekend off is not possible in the peak week with today's forklift drivers: the peak weekend needs 16 forklift shifts and alternating teams can cover 14. Certifying two pickers (E13, E14) as forklift drivers ($3,600 once, $1.50 an hour more for them) makes it possible, for about $900 more over December.

Fair weekends alone push night shifts onto a few people; adding a limit of 6 nights a month brings nights in line for another $1,300.

Recommendation: certify the two drivers in January; adopt every-other-weekend and the 6-night limit from January, when there is no peak; review the cost after three months. Total for December if adopted now: $128,076 against $125,861 (+1.8%)."

Commit

git add .
git commit -m "Day 35: 4-week roster mini-project"
git push

Day 35 checklist

  • I extended a weekly model to four weeks, with rest rules across week boundaries.
  • I checked the month against a known answer (4 × one week).
  • I compared one model for the month with planning week by week.
  • I measured fairness over the month (nights, weekends).
  • I found why a policy is infeasible, and priced the fix (two new drivers).
  • I wrote a recommendation with costs, one-time costs and side effects.