33.1 Requests as soft constraints
staff_requests holds next week's 47 requests: days off (mostly Fridays and weekends), "no nights", and preferred shifts, some with priority 2. A hard constraint must hold; a soft constraint may break, at a price in the objective. Each request gets a yes/no variable broken; the objective adds a cost for each broken request (times its priority). Create day33/preferences.py:
"""Day 33: requests and fairness on top of Day 32's roster model.
Import it: from preferences import on_shift, add_requests, nights_and_weekends
"""
from roster import DAYS, SHIFTS
def on_shift(work):
"""on[e, d, s]: 1 if e works shift s on day d (in any role)."""
on = {}
for (e, d, s, r), v in work.items():
on.setdefault((e, d, s), []).append(v)
return {k: sum(v) for k, v in on.items()}
def add_requests(m, work, requests):
"""One yes/no 'broken' variable per request: day off, no nights, or a preferred shift.
Returns [(employee, request, priority, broken)]."""
on = on_shift(work)
out = []
for r in requests.itertuples():
e = r.employee_id
broken = m.new_bool_var(f"broken_{e}_{r.request}_{r.Index}")
if r.request == "day_off":
shifts = [on[e, r.day, s] for s in SHIFTS]
elif r.request == "no_nights":
shifts = [on[e, d, "N"] for d in DAYS]
else: # prefer_shift: every other shift breaks it
shifts = [on[e, d, s] for d in DAYS for s in SHIFTS if s != r.shift]
for x in shifts:
m.add(broken >= x) # working any of them breaks the request
out.append((e, r.request, int(r.priority), broken))
return out
def nights_and_weekends(m, work, staff):
"""Integer variables: nights[e] and weekend_days[e] for each full-timer."""
on = on_shift(work)
nights, weekends = {}, {}
for e in staff.index[staff.contract == "full-time"]:
nights[e] = m.new_int_var(0, 7, f"nights_{e}")
m.add(nights[e] == sum(on[e, d, "N"] for d in DAYS))
weekends[e] = m.new_int_var(0, 2, f"weekend_{e}")
m.add(weekends[e] == sum(on[e, d, s] for d in ("Sat", "Sun") for s in SHIFTS))
return nights, weekends
def plan_week(staff, shifts, coverage, rules, last_sunday, requests, weight=50.0, max_nights=None,
max_weekend_days=None, agency_rate=None):
"""Day 32's roster with requests (each broken request costs `weight` dollars, times its priority)
and optional fairness caps. Returns a summary dict."""
from ortools.sat.python import cp_model
from roster import build_roster, dollars, solve_roster
m, work = build_roster(staff, shifts, coverage, rules, last_sunday, agency_rate=agency_rate)
broken = add_requests(m, work, requests)
nights, weekends = nights_and_weekends(m, work, staff)
if max_nights is not None:
for v in nights.values():
m.add(v <= max_nights)
if max_weekend_days is not None:
for v in weekends.values():
m.add(v <= max_weekend_days)
penalty = sum(p * b for _, _, p, b in broken)
m.minimize(m.pay + int(round(200 * weight)) * penalty) # half-cents, like the pay
solver, status, roster = solve_roster(m, work)
if status not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
return {"status": solver.status_name(status)}
night_counts = sorted((solver.value(v) for v in nights.values()), reverse=True)
return {"status": solver.status_name(status), "pay": dollars(solver.value(m.pay)),
"broken": sum(solver.value(b) for *_, b in broken),
"broken_list": [(e, r) for e, r, _, b in broken if solver.value(b)],
"most_nights": night_counts[0], "nights_top5": night_counts[:5],
"most_weekend_days": max(solver.value(v) for v in weekends.values()),
"both_weekend_days": sum(solver.value(v) == 2 for v in weekends.values()),
"agency": sum(solver.value(v) for v in m.agency.values()), "roster": roster}
plan_week returns pay, broken requests, and fairness measures. Then day33/run_preferences.py:
# ---------- 33.1 Requests as soft constraints ----------
print(requests.request.value_counts().to_string(), f"\n{len(requests)} requests, weighted {requests.priority.sum()}")
print("day-off requests by day:", requests[requests.request == "day_off"].day.value_counts().to_dict())
print("--- requests with no price, and at $50 each")
show([(f"each broken request costs ${w}", plan_week(*data, weight=w)) for w in (0, 50)])
request
day_off 28
no_nights 13
prefer_shift 6
47 requests, weighted 58
day-off requests by day: {'Sun': 10, 'Sat': 8, 'Fri': 5, 'Mon': 2, 'Thu': 2, 'Wed': 1}
--- requests with no price, and at $50 each
plan pay broken most_nights nights_top5 most_weekend_days both_weekend_days
each broken request costs $0 28876.48 47 4 [4, 3, 3, 2, 2] 2 6
each broken request costs $50 28876.48 0 5 [5, 5, 4, 3, 2] 2 8
Granting all 47 requests costs nothing: same pay, $28,876.48. With a weight of 0, the model broke all of them, not because it had to but because nothing told it otherwise. A solver is indifferent to everything that isn't in the model: anything people care about must be in the objective or the constraints.
33.2 Fairness
Look at nights_top5 above: with all requests granted, two people work 5 nights each. Fairness rules put caps on that: at most 2 nights (or 1), at most 1 weekend day.
# ---------- 33.2 Fairness caps ----------
print("--- fairness caps, requests at $50 each")
show([(name, plan_week(*data, **kw)) for name, kw in [
("requests only", {}), ("at most 2 nights", {"max_nights": 2}), ("at most 1 night", {"max_nights": 1}),
("at most 1 weekend day", {"max_weekend_days": 1}), ("2 nights, 1 weekend day", {"max_nights": 2, "max_weekend_days": 1})]])
r = plan_week(*data, max_nights=1)
print("requests broken with at most 1 night each:", r["broken_list"])
--- fairness caps, requests at $50 each
plan pay broken most_nights nights_top5 most_weekend_days both_weekend_days
requests only 28876.48 0 5 [5, 5, 4, 3, 2] 2 8
at most 2 nights 28896.88 1 2 [2, 2, 2, 2, 2] 2 5
at most 1 night 28876.48 6 1 [1, 1, 1, 1, 1] 2 7
at most 1 weekend day 28876.48 1 4 [4, 4, 4, 3, 3] 1 0
2 nights, 1 weekend day 28896.88 2 2 [2, 2, 2, 2, 2] 1 0
requests broken with at most 1 night each: [('E03', 'no_nights'), ('E06', 'no_nights'), ('E07', 'day_off'), ('E08', 'prefer_shift'), ('E09', 'no_nights'), ('E10', 'prefer_shift')]
- At most 2 nights each: $20.40 more a week and 1 broken request.
- At most 1 night each: no extra pay, but 6 broken requests, half of them "no nights" requests: if nobody may work more than one night, everyone must take a turn, including those who asked not to.
- At most 1 weekend day each: 1 broken request; together with 2 nights, 2 broken and $20.40.
Fairness and requests pull against each other. The model doesn't decide which matters more: it shows the price of each choice, and people decide. Other ways to write fairness: minimize the largest number of nights (min-max, as in 31.3), or the spread between most and fewest; or balance over several weeks (Day 35).
33.3 A peak week: when requests cost money
In the +10% week (Day 32's mini-project), staff are short and requests compete with coverage.
# ---------- 33.3 A peak week: when requests cost money ----------
peak = {k: math.ceil(v * 1.10) for k, v in coverage.items()}
peak_data = (staff, shifts, peak, rules, last_sunday, requests)
print("--- peak week (+10%), with agency pickers")
rows = []
for w in (0, 5, 10, 25, 50, 200):
r = plan_week(*peak_data, weight=w, agency_rate=36.0)
rows.append((w, r["pay"], r["broken"], r["agency"]))
t = pd.DataFrame(rows, columns=["dollars_per_request", "pay", "broken", "agency_shifts"])
print(t.to_string(index=False))
--- peak week (+10%), with agency pickers
dollars_per_request pay broken agency_shifts
0 39231.96 47 8
5 39236.56 6 9
10 39236.56 6 9
25 39289.76 3 10
50 39397.46 0 13
200 39397.46 0 13
- Each step of the weight is a point on a trade-off curve: $5 a request already grants 41 of 47 requests for $4.60 more; granting all 47 costs $165.50 more a week (5 more agency shifts).
- The weight is a price: "how many dollars is one broken request worth to us?" Managers can answer that. Sweep it and show the curve, rather than picking one number in the code.
Decision it supports: how much to spend to honour staff requests and share unpopular shifts fairly.
Other decisions you can support the same way: class timetables with teacher preferences · on-call rotas · holiday allocation.
The planted bug
day33/bug_units.py sets "a broken request costs $50" in the peak week. Run it.
m, work = build_roster(staff, shifts, peak, rules, last_sunday, agency_rate=36.0)
broken = add_requests(m, work, requests)
m.minimize(m.pay + 50 * sum(p * b for _, _, p, b in broken)) # $50 a broken request
solver, status, roster = solve_roster(m, work)
print(f"{solver.status_name(status)}: pay ${dollars(solver.value(m.pay)):,.2f}, "
f"requests broken {sum(solver.value(b) for *_, b in broken)} of {len(broken)}")
What happens, and why
OPTIMAL: pay $39,231.96, requests broken 7 of 47
The pay is the cheapest possible and 7 requests are broken, to save $165.50: about $24 a request, not $50. The pay is in half-cents (Day 32), so a penalty of 50 is 50 half-cents: $0.25 a request. To the model, a broken request was worth a quarter. Keep every term of an objective in the same unit, convert in one place (plan_week multiplies by 200), and test that a large weight really changes the answer.
Mini-project: the union's proposal
The union proposes: nobody works more than 2 nights a week, and no full-timer works both weekend days. What would it cost in a normal week and in a +10% peak week (with agency pickers allowed), in pay and in broken requests? Recommend.
Solution
"""Day 33 mini-project: the union proposes "nobody works more than 2 nights a week, and no full-timer works
both weekend days". What would it cost in a normal week and in a peak week, in pay and in broken requests?
Run from the repository root (after day06/load_tables.py): python day33/mini_project_union.py (about 1 minute)
"""
import math
import sys
import duckdb
import pandas as pd
for folder in ("day32", "day33"):
sys.path.insert(0, folder)
from preferences import plan_week
from roster import load_roster_data
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
staff, shifts, coverage, rules, last_sunday = load_roster_data(con)
requests = con.sql("SELECT * FROM staff_requests").df()
rows = []
for week, cov in [("normal", coverage), ("peak +10%", {k: math.ceil(v * 1.10) for k, v in coverage.items()})]:
for name, kw in [("today's rules", {}), ("union proposal", {"max_nights": 2, "max_weekend_days": 1})]:
r = plan_week(staff, shifts, cov, rules, last_sunday, requests, agency_rate=36.0, **kw)
rows.append((week, name, r["status"], r.get("pay"), r.get("broken"), r.get("agency"), r.get("most_nights"),
r.get("both_weekend_days")))
print(pd.DataFrame(rows, columns=["week", "rules", "status", "pay", "broken", "agency_shifts", "most_nights",
"both_weekend_days"]).to_string(index=False))
week rules status pay broken agency_shifts most_nights both_weekend_days
normal today's rules OPTIMAL 28876.48 0.0 0.0 5.0 6.0
normal union proposal OPTIMAL 28896.88 2.0 0.0 2.0 0.0
peak +10% today's rules OPTIMAL 39397.46 0.0 13.0 5.0 11.0
peak +10% union proposal INFEASIBLE NaN NaN NaN NaN NaN
- In a normal week the proposal costs $20.40 and 2 broken requests: almost free. Nobody works more than 2 nights (today up to 5) and no one works both weekend days (today 6 people do).
- In the peak week it is impossible, even with agency pickers. The weekend forklift shifts are the bottleneck: at +10% the weekend needs 16 forklift shifts, and with one weekend day each for 10 full-time drivers plus two part-timers' 2 days each, the drivers can cover at most 14. Agency staff can't drive forklifts.
Memo to the DC manager: "Accept the union's proposal for normal weeks: it costs about $20 a week. For peak weeks, either certify two more pickers as forklift drivers, or agree with the union that drivers may work both weekend days in December. Without one of the two, no legal peak roster meets the proposal."
Commit
git add .
git commit -m "Day 33: requests and fairness"
git push
Then run the tests: tests/test_scheduling.py checks Days 31–33 (CP-SAT against Day 15, the legal roster against the checker, the Monday carry-over, free requests). Add "day31", "day32", "day33" to the folders in conftest.py.
"""Module 4, Days 31-33: CP-SAT, legal rosters, requests and fairness."""
import pytest
from cp_assignment import build_cp_assignment, solve_and_price
from preferences import plan_week
from roster import build_roster, check_roster, dollars, load_roster_data, roster_cost, solve_roster
from transport import load_network
def test_cp_sat_assignment_matches_day15(con):
dcs, stores, lanes = load_network(con)
m, assign = build_cp_assignment(dcs, stores, lanes)
status, cents, real, _ = solve_and_price(m, assign, lanes, stores)
assert status == "OPTIMAL" and round(cents) == 4_149_276 and real == pytest.approx(41_492.76, abs=0.01)
@pytest.fixture(scope="module")
def roster_data(con):
return load_roster_data(con)
def test_legal_roster_passes_the_independent_check(roster_data):
staff, shifts, coverage, rules, last_sunday = roster_data
m, work = build_roster(*roster_data)
solver, status, roster = solve_roster(m, work)
assert check_roster(roster, staff, coverage, rules, last_sunday) == []
assert dollars(solver.objective_value) == pytest.approx(roster_cost(roster, staff, shifts, rules), abs=0.01)
assert dollars(solver.objective_value) == pytest.approx(28_876.48, abs=0.01)
def test_forgetting_last_sunday_breaks_the_rest_rule(roster_data):
staff, shifts, coverage, rules, last_sunday = roster_data
m, work = build_roster(*roster_data, carry_over=False)
_, _, roster = solve_roster(m, work)
problems = check_roster(roster, staff, coverage, rules, last_sunday)
assert problems and all("Sun-1" in p for p in problems)
def test_all_requests_granted_at_no_extra_pay(con, roster_data):
requests = con.sql("SELECT * FROM staff_requests").df()
r = plan_week(*roster_data, requests, weight=50)
assert r["broken"] == 0 and r["pay"] == pytest.approx(28_876.48, abs=0.01)
53 passed
Day 33 checklist
- I can write requests as soft constraints with a broken-request variable and a price.
- I check what is free before arguing about what costs money.
- I can add fairness caps and see how they trade against requests.
- I sweep a weight to draw a trade-off curve instead of guessing one number.
- I keep every term of an objective in the same unit.
- I can explain why a proposal is infeasible, and what would make it feasible.