shift-scenarios / space /src /validation.py
alirezaaminzadeh's picture
Add Shift Space source snapshot for org transfer
5804513 verified
Raw History Blame Contribute Delete
16 kB
from __future__ import annotations
from collections import defaultdict
import pandas as pd
from src.domain import MAX_DAYS, MAX_EMPLOYEES, MAX_UPLOAD_MB, ConstraintConfig, ValidationIssue, ValidationReport
EMPLOYEE_COLUMNS = ["employee_id", "name", "skills", "max_hours", "preferred_hours", "night_ok", "weekend_ok"]
DEMAND_COLUMNS = ["date", "shift_id", "skill", "required"]
SHIFT_COLUMNS = ["shift_id", "hours", "undesirable", "blocks_next_morning"]
CALENDAR_COLUMNS = ["date", "weekday", "week_index", "is_weekend"]
def _issue(
code: str,
message: str,
employee_id: str | None = None,
date: str | None = None,
shift_id: str | None = None,
skill: str | None = None,
passed: bool = False,
) -> ValidationIssue:
return ValidationIssue(code=code, message=message, employee_id=employee_id, date=date, shift_id=shift_id, skill=skill, passed=passed)
def skill_set(value: object) -> set[str]:
return {item.strip() for item in str(value).split("|") if item.strip()}
def leave_set(leave: pd.DataFrame) -> set[tuple[str, str]]:
if leave is None or leave.empty:
return set()
return set(zip(leave["employee_id"].astype(str), leave["date"].astype(str)))
def lock_rows(locks: pd.DataFrame) -> list[tuple[str, str, str]]:
if locks is None or locks.empty:
return []
frame = locks.copy()
if "locked" in frame.columns:
frame = frame.loc[frame["locked"].astype(int) != 0]
return list(zip(frame["employee_id"].astype(str), frame["date"].astype(str), frame["shift_id"].astype(str)))
def validate_input_tables(
employees: pd.DataFrame,
calendar: pd.DataFrame,
shifts: pd.DataFrame,
demand: pd.DataFrame,
leave: pd.DataFrame,
locks: pd.DataFrame,
config: ConstraintConfig,
) -> ValidationReport:
issues: list[ValidationIssue] = []
checked = ["schema", "counts", "ids", "values", "references", "locks", "hours"]
frames = {
"employees": (employees, EMPLOYEE_COLUMNS),
"calendar": (calendar, CALENDAR_COLUMNS),
"shifts": (shifts, SHIFT_COLUMNS),
"demand": (demand, DEMAND_COLUMNS),
}
for label, (frame, cols) in frames.items():
missing = [col for col in cols if col not in frame.columns]
if missing:
issues.append(_issue("schema", f"{label} missing columns: {missing}"))
if issues:
return ValidationReport(ok=False, issues=issues, checked=checked)
if employees.empty or calendar.empty or shifts.empty or demand.empty:
issues.append(_issue("schema", "employees, calendar, shifts and demand must be non-empty"))
if not 1 <= len(employees) <= MAX_EMPLOYEES:
issues.append(_issue("counts", f"employees must have 1 to {MAX_EMPLOYEES} rows, found {len(employees)}"))
if not 1 <= len(calendar) <= MAX_DAYS:
issues.append(_issue("counts", f"calendar must have 1 to {MAX_DAYS} days, found {len(calendar)}"))
if employees["employee_id"].astype(str).duplicated().any():
issues.append(_issue("ids", "duplicate employee_id"))
if calendar["date"].astype(str).duplicated().any():
issues.append(_issue("ids", "duplicate calendar date"))
if shifts["shift_id"].astype(str).duplicated().any():
issues.append(_issue("ids", "duplicate shift_id"))
if demand.duplicated(["date", "shift_id", "skill"]).any():
issues.append(_issue("ids", "duplicate demand date/shift/skill"))
if (employees["max_hours"].astype(float) <= 0).any():
issues.append(_issue("values", "max_hours must be > 0"))
if (employees["preferred_hours"].astype(float) < 0).any():
issues.append(_issue("values", "preferred_hours cannot be negative"))
required = pd.to_numeric(demand["required"], errors="coerce")
if required.isna().any() or (required < 0).any():
issues.append(_issue("values", "required demand cannot be negative"))
if (shifts["hours"].astype(float) <= 0).any():
issues.append(_issue("values", "shift hours must be > 0"))
emp_ids = set(employees["employee_id"].astype(str))
dates = set(calendar["date"].astype(str))
shift_ids = set(shifts["shift_id"].astype(str))
if leave is not None and len(leave):
unknown = sorted(set(leave["employee_id"].astype(str)) - emp_ids)
if unknown:
issues.append(_issue("references", f"leave references unknown employee_id: {unknown[:8]}", employee_id=unknown[0]))
unknown_d = sorted(set(leave["date"].astype(str)) - dates)
if unknown_d:
issues.append(_issue("references", f"leave references unknown date: {unknown_d[:8]}", date=unknown_d[0]))
for employee_id, day, shift_id in lock_rows(locks):
if employee_id not in emp_ids:
issues.append(_issue("locks", f"lock uses unknown employee {employee_id}", employee_id=employee_id, date=day, shift_id=shift_id))
if day not in dates:
issues.append(_issue("locks", f"lock uses unknown date {day}", employee_id=employee_id, date=day, shift_id=shift_id))
if shift_id not in shift_ids:
issues.append(_issue("locks", f"lock uses unknown shift {shift_id}", employee_id=employee_id, date=day, shift_id=shift_id))
unknown_demand_dates = sorted(set(demand["date"].astype(str)) - dates)
if unknown_demand_dates:
issues.append(_issue("references", f"demand references unknown date: {unknown_demand_dates[:8]}", date=unknown_demand_dates[0]))
unknown_demand_shifts = sorted(set(demand["shift_id"].astype(str)) - shift_ids)
if unknown_demand_shifts:
issues.append(_issue("references", f"demand references unknown shift: {unknown_demand_shifts[:8]}", shift_id=unknown_demand_shifts[0]))
if config.unavailable_employee_id and config.unavailable_employee_id not in emp_ids:
issues.append(_issue("references", f"unavailable employee {config.unavailable_employee_id} is not on the roster", employee_id=config.unavailable_employee_id))
if float(config.preferred_hours) > float(config.max_hours):
issues.append(_issue("hours", "preferred_hours cannot exceed max_hours"))
return ValidationReport(ok=not issues, issues=issues, checked=checked)
def diagnose_infeasibility(
employees: pd.DataFrame,
calendar: pd.DataFrame,
shifts: pd.DataFrame,
demand: pd.DataFrame,
leave: pd.DataFrame,
locks: pd.DataFrame,
) -> list[str]:
hints: list[str] = []
off = leave_set(leave)
dates = calendar["date"].astype(str).tolist()
weekend = dict(zip(calendar["date"].astype(str), calendar["is_weekend"].astype(int)))
shift_hours = dict(zip(shifts["shift_id"].astype(str), shifts["hours"].astype(float)))
for row in demand.itertuples(index=False):
if int(row.required) <= 0:
continue
eligible = 0
for emp in employees.itertuples(index=False):
if row.skill not in skill_set(emp.skills):
continue
if (str(emp.employee_id), str(row.date)) in off:
continue
if int(row.shift_id == "night") and int(emp.night_ok) == 0:
continue
if int(weekend.get(str(row.date), 0)) == 1 and int(emp.weekend_ok) == 0:
continue
eligible += 1
if eligible < int(row.required):
hints.append(
f"Heuristic: {row.date} {row.shift_id}/{row.skill} needs {int(row.required)} but only {eligible} eligible people remain."
)
locked = lock_rows(locks)
by_person_day: dict[tuple[str, str], list[str]] = defaultdict(list)
for employee_id, day, shift_id in locked:
by_person_day[(employee_id, day)].append(shift_id)
if (employee_id, day) in off:
hints.append(f"Heuristic: lock {employee_id} on {day} conflicts with leave.")
emp = employees.loc[employees["employee_id"].astype(str) == employee_id]
if not emp.empty and shift_id == "night" and int(emp.iloc[0]["night_ok"]) == 0:
hints.append(f"Heuristic: lock {employee_id} to night but night_ok=0.")
for (employee_id, day), items in by_person_day.items():
if len(set(items)) > 1:
hints.append(f"Heuristic: {employee_id} is locked to overlapping shifts on {day}: {sorted(set(items))}.")
hours_by_emp: dict[str, float] = defaultdict(float)
for employee_id, day, shift_id in locked:
hours_by_emp[employee_id] += float(shift_hours.get(shift_id, 8.0))
max_hours = dict(zip(employees["employee_id"].astype(str), employees["max_hours"].astype(float)))
for employee_id, hours in hours_by_emp.items():
if hours > max_hours.get(employee_id, 80.0) + 1e-6:
hints.append(f"Heuristic: locks already give {employee_id} {hours:.0f} h above the period cap.")
_ = dates
return hints[:8]
def validate_plan(
employees: pd.DataFrame,
calendar: pd.DataFrame,
shifts: pd.DataFrame,
demand: pd.DataFrame,
leave: pd.DataFrame,
locks: pd.DataFrame,
assignments: pd.DataFrame,
uncovered: pd.DataFrame,
config: ConstraintConfig,
require_full_cover: bool = False,
) -> ValidationReport:
issues: list[ValidationIssue] = []
checked = ["overlap", "rest", "hours", "skill", "leave", "availability", "locks", "demand_balance", "full_cover"]
emp_ids = set(employees["employee_id"].astype(str))
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_hours = dict(zip(shifts["shift_id"].astype(str), shifts["hours"].astype(float)))
night_block = set(shifts.loc[shifts["blocks_next_morning"].astype(int) == 1, "shift_id"].astype(str))
skills = {str(row.employee_id): skill_set(row.skills) for row in employees.itertuples(index=False)}
max_hours = dict(zip(employees["employee_id"].astype(str), employees["max_hours"].astype(float)))
weekly_max = dict(zip(employees["employee_id"].astype(str), employees.get("weekly_max_hours", pd.Series(config.weekly_max_hours, index=employees.index)).astype(float)))
night_ok = dict(zip(employees["employee_id"].astype(str), employees["night_ok"].astype(int)))
weekend_ok = dict(zip(employees["employee_id"].astype(str), employees["weekend_ok"].astype(int)))
off = leave_set(leave)
locked = set(lock_rows(locks))
assigned: dict[tuple[str, str], list[str]] = defaultdict(list)
hours: dict[str, float] = defaultdict(float)
weekly: dict[tuple[str, int], float] = defaultdict(float)
cover: dict[tuple[str, str, str], int] = defaultdict(int)
if assignments is not None and len(assignments):
for row in assignments.itertuples(index=False):
employee_id = str(row.employee_id)
day = str(row.date)
shift_id = str(row.shift_id)
skill = str(row.skill)
if employee_id not in emp_ids:
issues.append(_issue("availability", f"unknown employee {employee_id}", employee_id=employee_id, date=day, shift_id=shift_id))
continue
assigned[(employee_id, day)].append(shift_id)
hours[employee_id] += float(shift_hours.get(shift_id, 8.0))
weekly[(employee_id, int(week_of.get(day, 0)))] += float(shift_hours.get(shift_id, 8.0))
cover[(day, shift_id, skill)] += 1
if skill not in skills.get(employee_id, set()):
issues.append(_issue("skill", f"{employee_id} lacks skill {skill}", employee_id=employee_id, date=day, shift_id=shift_id, skill=skill))
if (employee_id, day) in off:
issues.append(_issue("leave", f"{employee_id} is on leave on {day}", employee_id=employee_id, date=day, shift_id=shift_id))
if shift_id == "night" and night_ok.get(employee_id, 1) == 0:
issues.append(_issue("availability", f"{employee_id} cannot work night", employee_id=employee_id, date=day, shift_id=shift_id))
if weekend.get(day, 0) == 1 and weekend_ok.get(employee_id, 1) == 0:
issues.append(_issue("availability", f"{employee_id} cannot work the weekend of {day}", employee_id=employee_id, date=day, shift_id=shift_id))
for (employee_id, day), items in assigned.items():
if len(items) > 1:
issues.append(_issue("overlap", f"{employee_id} has overlapping shifts on {day}: {items}", employee_id=employee_id, date=day))
date_pos = {day: idx for idx, day in enumerate(dates)}
for (employee_id, day), items in assigned.items():
if any(item in night_block for item in items):
nxt = date_pos.get(day)
if nxt is not None and nxt + 1 < len(dates):
nxt_day = dates[nxt + 1]
if "morning" in assigned.get((employee_id, nxt_day), []):
issues.append(_issue("rest", f"{employee_id} works night on {day} and morning on {nxt_day}", employee_id=employee_id, date=day, shift_id="night"))
for employee_id, total in hours.items():
cap = float(max_hours.get(employee_id, config.max_hours))
if total > cap + 1e-6:
issues.append(_issue("hours", f"{employee_id} works {total:.0f} h above cap {cap:.0f} h", employee_id=employee_id))
for (employee_id, week), total in weekly.items():
cap = float(weekly_max.get(employee_id, config.weekly_max_hours))
if total > cap + 1e-6:
issues.append(_issue("hours", f"{employee_id} works {total:.0f} h in week {week} above weekly cap {cap:.0f} h", employee_id=employee_id))
assigned_keys = {(str(r.employee_id), str(r.date), str(r.shift_id)) for r in assignments.itertuples(index=False)} if assignments is not None and len(assignments) else set()
for employee_id, day, shift_id in locked:
if (employee_id, day, shift_id) not in assigned_keys:
issues.append(_issue("locks", f"locked assignment {employee_id} {day} {shift_id} is missing", employee_id=employee_id, date=day, shift_id=shift_id))
leftover: dict[tuple[str, str, str], int] = defaultdict(int)
if uncovered is not None and len(uncovered):
for row in uncovered.itertuples(index=False):
leftover[(str(row.date), str(row.shift_id), str(row.skill))] += int(row.uncovered)
for row in demand.itertuples(index=False):
key = (str(row.date), str(row.shift_id), str(row.skill))
filled = cover.get(key, 0)
slack = leftover.get(key, 0)
need = int(row.required)
if filled + slack != need:
issues.append(
_issue(
"demand_balance",
f"{key[0]} {key[1]}/{key[2]}: filled {filled} + uncovered {slack} != required {need}",
date=key[0],
shift_id=key[1],
skill=key[2],
)
)
if (require_full_cover or config.require_full_cover) and slack > 0:
issues.append(_issue("full_cover", f"{key[0]} {key[1]}/{key[2]} left uncovered", date=key[0], shift_id=key[1], skill=key[2]))
return ValidationReport(ok=not issues, issues=issues, checked=checked)
def format_input_error(report: ValidationReport) -> str:
fails = [item for item in report.issues if not item.passed]
if not fails:
return ""
parts = []
for issue in fails[:8]:
loc = [item for item in (issue.employee_id, issue.date, issue.shift_id, issue.skill) if item]
prefix = f"[{', '.join(loc)}] " if loc else ""
parts.append(f"{prefix}{issue.message}")
return " | ".join(parts)
def file_too_large(size_bytes: int) -> bool:
return size_bytes > MAX_UPLOAD_MB * 1024 * 1024