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")