File size: 12,578 Bytes
5804513 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | from __future__ import annotations
import time
from collections import defaultdict
from dataclasses import dataclass
import pandas as pd
from src.domain import (
COVER_WEIGHT,
FAIRNESS_WEIGHT,
OVERTIME_WEIGHT,
PREFERENCE_WEIGHT,
UNDESIRABLE_WEIGHT,
ConstraintConfig,
SolveStatus,
)
from src.validation import leave_set, lock_rows, skill_set
@dataclass
class SolverOutcome:
status: SolveStatus
assignments: pd.DataFrame
uncovered: pd.DataFrame
objective: float | None
seconds: float
message: str
solver_name: str
def empty_assignments() -> pd.DataFrame:
return pd.DataFrame(
columns=[
"employee_id",
"name",
"date",
"weekday",
"shift_id",
"skill",
"hours",
"locked",
"undesirable",
"preference_ok",
]
)
def empty_uncovered() -> pd.DataFrame:
return pd.DataFrame(columns=["date", "weekday", "shift_id", "skill", "required", "filled", "uncovered", "reason"])
def _eligible(
emp,
day: str,
shift_id: str,
weekend: dict[str, int],
off: set[tuple[str, str]],
) -> bool:
if (str(emp.employee_id), day) in off:
return False
if shift_id == "night" and int(emp.night_ok) == 0:
return False
if int(weekend.get(day, 0)) == 1 and int(emp.weekend_ok) == 0:
return False
return True
def plan_from_choices(
employees: pd.DataFrame,
calendar: pd.DataFrame,
shifts: pd.DataFrame,
demand: pd.DataFrame,
leave: pd.DataFrame,
locks: pd.DataFrame,
chosen: list[tuple[str, str, str, str]],
) -> tuple[pd.DataFrame, pd.DataFrame]:
names = dict(zip(employees["employee_id"].astype(str), employees["name"].astype(str)))
prefer = dict(zip(employees["employee_id"].astype(str), employees["prefer_shift"].astype(str)))
weekday = dict(zip(calendar["date"].astype(str), calendar["weekday"].astype(str)))
weekend = dict(zip(calendar["date"].astype(str), calendar["is_weekend"].astype(int)))
hours = dict(zip(shifts["shift_id"].astype(str), shifts["hours"].astype(float)))
night_flag = dict(zip(shifts["shift_id"].astype(str), shifts["undesirable"].astype(int)))
locked = set(lock_rows(locks))
rows = []
cover: dict[tuple[str, str, str], int] = defaultdict(int)
for employee_id, day, shift_id, skill in chosen:
und = int(night_flag.get(shift_id, 0) == 1 or weekend.get(day, 0) == 1)
pref = prefer.get(employee_id, "any")
rows.append(
{
"employee_id": employee_id,
"name": names.get(employee_id, employee_id),
"date": day,
"weekday": weekday.get(day, ""),
"shift_id": shift_id,
"skill": skill,
"hours": float(hours.get(shift_id, 8.0)),
"locked": int((employee_id, day, shift_id) in locked),
"undesirable": und,
"preference_ok": int(pref in {"any", shift_id}),
}
)
cover[(day, shift_id, skill)] += 1
assignments = pd.DataFrame(rows)
if len(assignments):
assignments = assignments.sort_values(["date", "shift_id", "employee_id"]).reset_index(drop=True)
else:
assignments = empty_assignments()
uncovered_rows = []
for row in demand.itertuples(index=False):
key = (str(row.date), str(row.shift_id), str(row.skill))
filled = cover.get(key, 0)
need = int(row.required)
slack = max(0, need - filled)
if slack:
uncovered_rows.append(
{
"date": key[0],
"weekday": weekday.get(key[0], ""),
"shift_id": key[1],
"skill": key[2],
"required": need,
"filled": filled,
"uncovered": slack,
"reason": "Hard constraints left this slot open: hours, rest after night, leave, night_ok/weekend_ok, or a lock.",
}
)
uncovered = pd.DataFrame(uncovered_rows) if uncovered_rows else empty_uncovered()
_ = leave
return assignments, uncovered
def optimize_roster(
employees: pd.DataFrame,
calendar: pd.DataFrame,
shifts: pd.DataFrame,
demand: pd.DataFrame,
leave: pd.DataFrame,
locks: pd.DataFrame,
config: ConstraintConfig,
) -> SolverOutcome:
started = time.perf_counter()
try:
from ortools.sat.python import cp_model
except Exception as exc:
return SolverOutcome(SolveStatus.ERROR, empty_assignments(), empty_uncovered(), None, 0.0, f"OR-Tools missing: {exc}", "none")
dates = calendar.sort_values("date")["date"].astype(str).tolist()
weekend = dict(zip(calendar["date"].astype(str), calendar["is_weekend"].astype(int)))
week_of = dict(zip(calendar["date"].astype(str), calendar["week_index"].astype(int)))
shift_ids = shifts["shift_id"].astype(str).tolist()
hours_of = dict(zip(shifts["shift_id"].astype(str), shifts["hours"].astype(int)))
night_block = set(shifts.loc[shifts["blocks_next_morning"].astype(int) == 1, "shift_id"].astype(str))
off = leave_set(leave)
locked = set(lock_rows(locks))
demand_map = {(str(r.date), str(r.shift_id), str(r.skill)): int(r.required) for r in demand.itertuples(index=False)}
skills_needed = sorted({str(r.skill) for r in demand.itertuples(index=False)})
model = cp_model.CpModel()
x: dict[tuple[str, str, str], cp_model.IntVar] = {}
y: dict[tuple[str, str, str, str], cp_model.IntVar] = {}
for emp in employees.itertuples(index=False):
employee_id = str(emp.employee_id)
skills = skill_set(emp.skills)
for day in dates:
for shift_id in shift_ids:
allowed = _eligible(emp, day, shift_id, weekend, off)
var = model.NewBoolVar(f"x-{employee_id}-{day}-{shift_id}")
x[(employee_id, day, shift_id)] = var
if not allowed:
model.Add(var == 0)
for skill in skills_needed:
role = model.NewBoolVar(f"y-{employee_id}-{day}-{shift_id}-{skill}")
y[(employee_id, day, shift_id, skill)] = role
if skill not in skills or not allowed:
model.Add(role == 0)
else:
model.Add(role <= var)
model.Add(sum(y[(employee_id, day, shift_id, skill)] for skill in skills_needed) == var)
for emp in employees.itertuples(index=False):
employee_id = str(emp.employee_id)
for day in dates:
model.Add(sum(x[(employee_id, day, shift_id)] for shift_id in shift_ids) <= 1)
for idx, day in enumerate(dates[:-1]):
nxt = dates[idx + 1]
for shift_id in night_block:
if "morning" in shift_ids:
model.Add(x[(employee_id, day, shift_id)] + x[(employee_id, nxt, "morning")] <= 1)
period_hours = sum(hours_of[shift_id] * x[(employee_id, day, shift_id)] for day in dates for shift_id in shift_ids)
model.Add(period_hours <= int(round(float(emp.max_hours))))
for week in sorted(set(week_of.values())):
week_hours = sum(
hours_of[shift_id] * x[(employee_id, day, shift_id)]
for day in dates
if week_of[day] == week
for shift_id in shift_ids
)
weekly_cap = int(round(float(getattr(emp, "weekly_max_hours", config.weekly_max_hours))))
model.Add(week_hours <= weekly_cap)
for employee_id, day, shift_id in locked:
if (employee_id, day, shift_id) in x:
model.Add(x[(employee_id, day, shift_id)] == 1)
else:
return SolverOutcome(
SolveStatus.INFEASIBLE,
empty_assignments(),
empty_uncovered(),
None,
time.perf_counter() - started,
f"Lock {employee_id} {day} {shift_id} is not a valid assignment key.",
"ortools-cpsat",
)
slacks = []
for (day, shift_id, skill), need in demand_map.items():
filled = [y[(str(emp.employee_id), day, shift_id, skill)] for emp in employees.itertuples(index=False)]
slack = model.NewIntVar(0, max(need, 0), f"slack-{day}-{shift_id}-{skill}")
model.Add(sum(filled) + slack == need)
slacks.append(slack)
if config.require_full_cover:
model.Add(slack == 0)
overtime = []
undesirable = []
preference = []
for emp in employees.itertuples(index=False):
employee_id = str(emp.employee_id)
worked = sum(hours_of[shift_id] * x[(employee_id, day, shift_id)] for day in dates for shift_id in shift_ids)
ot = model.NewIntVar(0, 200, f"ot-{employee_id}")
model.Add(ot >= worked - int(round(float(emp.preferred_hours))))
overtime.append(ot)
und = []
pref_pen = []
for day in dates:
for shift_id in shift_ids:
is_und = int(shift_id == "night" or weekend.get(day, 0) == 1)
if is_und:
und.append(x[(employee_id, day, shift_id)])
if str(emp.prefer_shift) not in {"any", shift_id}:
pref_pen.append(x[(employee_id, day, shift_id)])
count = model.NewIntVar(0, len(dates) * len(shift_ids), f"und-{employee_id}")
model.Add(count == (sum(und) if und else 0))
undesirable.append(count)
preference.append(sum(pref_pen) if pref_pen else 0)
und_max = model.NewIntVar(0, len(dates) * len(shift_ids), "und-max")
und_min = model.NewIntVar(0, len(dates) * len(shift_ids), "und-min")
model.AddMaxEquality(und_max, undesirable)
model.AddMinEquality(und_min, undesirable)
spread = model.NewIntVar(0, len(dates) * len(shift_ids), "und-spread")
model.Add(spread == und_max - und_min)
model.Minimize(
COVER_WEIGHT * sum(slacks)
+ OVERTIME_WEIGHT * sum(overtime)
+ FAIRNESS_WEIGHT * spread
+ UNDESIRABLE_WEIGHT * sum(undesirable)
+ PREFERENCE_WEIGHT * sum(preference)
)
solver = cp_model.CpSolver()
solver.parameters.max_time_in_seconds = float(config.solver_seconds)
solver.parameters.num_search_workers = int(config.threads)
solver.parameters.log_search_progress = False
status_code = solver.Solve(model)
elapsed = time.perf_counter() - started
if status_code not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
status = SolveStatus.TIMEOUT if status_code == cp_model.UNKNOWN else SolveStatus.INFEASIBLE
message = (
"No roster found before the time limit — this is not a proof of infeasibility."
if status == SolveStatus.TIMEOUT
else f"CP-SAT status={solver.StatusName(status_code)}"
)
return SolverOutcome(status, empty_assignments(), empty_uncovered(), None, elapsed, message, "ortools-cpsat")
chosen: list[tuple[str, str, str, str]] = []
for emp in employees.itertuples(index=False):
employee_id = str(emp.employee_id)
for day in dates:
for shift_id in shift_ids:
if solver.Value(x[(employee_id, day, shift_id)]) != 1:
continue
skill = next((sk for sk in skills_needed if solver.Value(y[(employee_id, day, shift_id, sk)]) == 1), str(emp.skills).split("|")[0])
chosen.append((employee_id, day, shift_id, skill))
assignments, uncovered = plan_from_choices(employees, calendar, shifts, demand, leave, locks, chosen)
status = SolveStatus.OPTIMAL if status_code == cp_model.OPTIMAL else SolveStatus.FEASIBLE
message = (
"Proven optimal within the model. Hard rules and local labour parameters are user-confirmed inputs, not a legal certification."
if status == SolveStatus.OPTIMAL
else "Feasible incumbent in the time limit — not proven optimal. Timeout is not infeasibility."
)
return SolverOutcome(status, assignments, uncovered, float(solver.ObjectiveValue()), elapsed, message, "ortools-cpsat")
|