Download demo/src/validation.py from AriaAICompany/or-bench-problems: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/datasets/AriaAICompany/or-bench-problems/resolve/main/demo/src/validation.py
- Command line
-
hf download hf://datasets/AriaAICompany/or-bench-problems/demo/src/validation.py
-
curl -L -o validation.py https://huggingface.co/datasets/AriaAICompany/or-bench-problems/resolve/main/demo/src/validation.py
11.6 kB
| from __future__ import annotations | |
| from collections import defaultdict | |
| from src.domain import ( | |
| AssignmentInstance, | |
| Family, | |
| InventoryInstance, | |
| ScheduleInstance, | |
| Solution, | |
| ValidationIssue, | |
| ValidationReport, | |
| parse_instance, | |
| ) | |
| def _issue(code: str, message: str, entity_id: str | None = None, passed: bool = False) -> ValidationIssue: | |
| return ValidationIssue(code=code, message=message, entity_id=entity_id, passed=passed) | |
| def validate_schema(family: Family | str, payload: dict) -> ValidationReport: | |
| issues: list[ValidationIssue] = [] | |
| checked = ["schema", "ids", "values"] | |
| try: | |
| instance = parse_instance(family, payload) | |
| except Exception as exc: | |
| return ValidationReport(ok=False, issues=[_issue("schema", f"schema rejected: {exc}")], checked=checked) | |
| if isinstance(instance, InventoryInstance): | |
| ids = [sku.sku_id for sku in instance.skus] | |
| if len(ids) != len(set(ids)): | |
| issues.append(_issue("ids", "duplicate SKU ids")) | |
| if not instance.skus: | |
| issues.append(_issue("schema", "inventory needs at least one SKU")) | |
| for sku in instance.skus: | |
| if len(sku.demand) != instance.periods: | |
| issues.append(_issue("values", f"{sku.sku_id} demand length must equal periods", sku.sku_id)) | |
| if any(value < 0 for value in sku.demand): | |
| issues.append(_issue("values", f"{sku.sku_id} demand must be non-negative", sku.sku_id)) | |
| elif isinstance(instance, AssignmentInstance): | |
| if not instance.tasks or not instance.agents: | |
| issues.append(_issue("schema", "assignment needs tasks and agents")) | |
| task_ids = [task.task_id for task in instance.tasks] | |
| agent_ids = [agent.agent_id for agent in instance.agents] | |
| if len(task_ids) != len(set(task_ids)) or len(agent_ids) != len(set(agent_ids)): | |
| issues.append(_issue("ids", "duplicate task or agent ids")) | |
| known = {(task.task_id, agent.agent_id) for task in instance.tasks for agent in instance.agents} | |
| for row in instance.costs: | |
| if (row.task_id, row.agent_id) not in known: | |
| issues.append(_issue("references", f"cost for unknown pair {row.task_id}/{row.agent_id}")) | |
| else: | |
| job_ids = [job.job_id for job in instance.jobs] | |
| if len(job_ids) != len(set(job_ids)): | |
| issues.append(_issue("ids", "duplicate job ids")) | |
| if not instance.machines or not instance.jobs: | |
| issues.append(_issue("schema", "scheduling needs jobs and machines")) | |
| seen = set() | |
| for edge in instance.precedences: | |
| if edge.before not in job_ids or edge.after not in job_ids: | |
| issues.append(_issue("references", f"precedence {edge.before}->{edge.after} is unknown")) | |
| if edge.before == edge.after: | |
| issues.append(_issue("values", f"self precedence on {edge.before}", edge.before)) | |
| pair = (edge.before, edge.after) | |
| if pair in seen: | |
| continue | |
| seen.add(pair) | |
| if _has_cycle(instance.precedences): | |
| issues.append(_issue("values", "precedence graph has a cycle")) | |
| return ValidationReport(ok=not issues, issues=issues, checked=checked) | |
| def _has_cycle(edges) -> bool: | |
| graph: dict[str, list[str]] = defaultdict(list) | |
| nodes: set[str] = set() | |
| for edge in edges: | |
| graph[edge.before].append(edge.after) | |
| nodes.add(edge.before) | |
| nodes.add(edge.after) | |
| state: dict[str, int] = {} | |
| def visit(node: str) -> bool: | |
| state[node] = 1 | |
| for nxt in graph.get(node, []): | |
| if state.get(nxt) == 1: | |
| return True | |
| if state.get(nxt, 0) == 0 and visit(nxt): | |
| return True | |
| state[node] = 2 | |
| return False | |
| return any(state.get(node, 0) == 0 and visit(node) for node in nodes) | |
| def validate_solution(family: Family | str, payload: dict, solution: Solution | dict) -> ValidationReport: | |
| family = Family(family) | |
| schema_report = validate_schema(family, payload) | |
| if not schema_report.ok: | |
| return schema_report | |
| instance = parse_instance(family, payload) | |
| if not isinstance(solution, Solution): | |
| solution = Solution.model_validate(solution) | |
| if family == Family.INVENTORY: | |
| return _validate_inventory(instance, solution) | |
| if family == Family.ASSIGNMENT: | |
| return _validate_assignment(instance, solution) | |
| return _validate_schedule(instance, solution) | |
| def _validate_inventory(instance: InventoryInstance, solution: Solution) -> ValidationReport: | |
| issues: list[ValidationIssue] = [] | |
| checked = ["pack", "budget", "balance", "capacity", "cover", "objective"] | |
| qty = {(row.sku_id, int(row.period)): int(row.qty) for row in solution.orders} | |
| spend = 0 | |
| hold_cost = 0 | |
| short_cost = 0 | |
| stock = {sku.sku_id: sku.initial_stock for sku in instance.skus} | |
| for t in range(1, instance.periods + 1): | |
| ending = 0 | |
| for sku in instance.skus: | |
| order = int(qty.get((sku.sku_id, t), 0)) | |
| if order < 0: | |
| issues.append(_issue("values", f"negative order {sku.sku_id}@{t}", sku.sku_id)) | |
| if sku.pack_size and order % sku.pack_size != 0: | |
| issues.append(_issue("pack", f"{sku.sku_id}@{t} qty {order} is not a multiple of pack {sku.pack_size}", sku.sku_id)) | |
| spend += order * sku.unit_cost | |
| demand = int(sku.demand[t - 1]) | |
| available = stock[sku.sku_id] + order | |
| sold = min(available, demand) | |
| short = demand - sold | |
| stock[sku.sku_id] = available - sold | |
| if stock[sku.sku_id] < 0: | |
| issues.append(_issue("balance", f"negative inventory {sku.sku_id}@{t}", sku.sku_id)) | |
| if instance.cover_required and short: | |
| issues.append(_issue("cover", f"{sku.sku_id}@{t} shortage {short} while cover is required", sku.sku_id)) | |
| ending += stock[sku.sku_id] | |
| hold_cost += stock[sku.sku_id] * sku.holding_cost | |
| short_cost += short * sku.shortage_cost | |
| if ending > instance.warehouse_capacity: | |
| issues.append(_issue("capacity", f"period {t} inventory {ending} exceeds capacity {instance.warehouse_capacity}")) | |
| if spend > instance.budget: | |
| issues.append(_issue("budget", f"purchase {spend} exceeds budget {instance.budget}")) | |
| objective = float(spend + hold_cost + short_cost) | |
| return ValidationReport(ok=not issues, issues=issues, checked=checked, recomputed_objective=objective) | |
| def _validate_assignment(instance: AssignmentInstance, solution: Solution) -> ValidationReport: | |
| issues: list[ValidationIssue] = [] | |
| checked = ["unique", "eligible", "capacity", "required", "objective"] | |
| seen_tasks: set[str] = set() | |
| load: dict[str, int] = defaultdict(int) | |
| cost_map = instance.cost_map() | |
| agents = {agent.agent_id: agent for agent in instance.agents} | |
| tasks = {task.task_id: task for task in instance.tasks} | |
| spend = 0 | |
| for row in solution.assignments: | |
| if row.task_id in seen_tasks: | |
| issues.append(_issue("unique", f"task {row.task_id} assigned more than once", row.task_id)) | |
| seen_tasks.add(row.task_id) | |
| task = tasks.get(row.task_id) | |
| agent = agents.get(row.agent_id) | |
| if task is None or agent is None: | |
| issues.append(_issue("references", f"unknown pair {row.task_id}/{row.agent_id}", row.task_id)) | |
| continue | |
| if not instance.eligible(task, agent): | |
| issues.append(_issue("eligible", f"{row.task_id} is not eligible for {row.agent_id}", row.task_id)) | |
| if (row.task_id, row.agent_id) not in cost_map: | |
| issues.append(_issue("references", f"no cost for {row.task_id}/{row.agent_id}", row.task_id)) | |
| else: | |
| spend += cost_map[(row.task_id, row.agent_id)] | |
| load[row.agent_id] += task.size | |
| for agent in instance.agents: | |
| if load[agent.agent_id] > agent.capacity: | |
| issues.append(_issue("capacity", f"{agent.agent_id} load {load[agent.agent_id]} exceeds {agent.capacity}", agent.agent_id)) | |
| leftover = set(solution.unassigned) | |
| for task in instance.tasks: | |
| assigned = task.task_id in seen_tasks | |
| if task.required and not assigned: | |
| issues.append(_issue("required", f"required task {task.task_id} is unassigned", task.task_id)) | |
| if not assigned: | |
| leftover.add(task.task_id) | |
| spend += task.penalty | |
| if assigned and task.task_id in leftover: | |
| leftover.discard(task.task_id) | |
| return ValidationReport(ok=not issues, issues=issues, checked=checked, recomputed_objective=float(spend)) | |
| def _validate_schedule(instance: ScheduleInstance, solution: Solution) -> ValidationReport: | |
| issues: list[ValidationIssue] = [] | |
| checked = ["unique", "eligible", "release", "overlap", "precedence", "hard_due", "duration", "objective"] | |
| jobs = {job.job_id: job for job in instance.jobs} | |
| seen: set[str] = set() | |
| by_machine: dict[str, list[tuple[int, int, str]]] = defaultdict(list) | |
| ends: dict[str, int] = {} | |
| starts: dict[str, int] = {} | |
| tardy = 0 | |
| for row in solution.starts: | |
| if row.job_id in seen: | |
| issues.append(_issue("unique", f"job {row.job_id} starts more than once", row.job_id)) | |
| seen.add(row.job_id) | |
| job = jobs.get(row.job_id) | |
| if job is None: | |
| issues.append(_issue("references", f"unknown job {row.job_id}", row.job_id)) | |
| continue | |
| if row.machine_id not in instance.machines: | |
| issues.append(_issue("references", f"unknown machine {row.machine_id}", row.job_id)) | |
| if job.machine_eligible and row.machine_id not in set(job.machine_eligible): | |
| issues.append(_issue("eligible", f"{row.job_id} cannot use {row.machine_id}", row.job_id)) | |
| if row.start < job.release: | |
| issues.append(_issue("release", f"{row.job_id} starts at {row.start} before release {job.release}", row.job_id)) | |
| if row.end - row.start != job.duration: | |
| issues.append(_issue("duration", f"{row.job_id} duration {row.end - row.start} != {job.duration}", row.job_id)) | |
| if job.hard_due and row.end > job.due: | |
| issues.append(_issue("hard_due", f"{row.job_id} ends at {row.end} after hard due {job.due}", row.job_id)) | |
| by_machine[row.machine_id].append((row.start, row.end, row.job_id)) | |
| ends[row.job_id] = row.end | |
| starts[row.job_id] = row.start | |
| tardy += job.weight * max(0, row.end - job.due) | |
| for job in instance.jobs: | |
| if job.job_id not in seen: | |
| issues.append(_issue("cover", f"job {job.job_id} has no start", job.job_id)) | |
| for machine, blocks in by_machine.items(): | |
| ordered = sorted(blocks) | |
| for prev, cur in zip(ordered, ordered[1:]): | |
| if prev[1] > cur[0]: | |
| issues.append(_issue("overlap", f"{machine} overlap {prev[2]} and {cur[2]}", machine)) | |
| for edge in instance.precedences: | |
| if edge.before in ends and edge.after in starts and ends[edge.before] > starts[edge.after]: | |
| issues.append(_issue("precedence", f"{edge.before} must finish before {edge.after}", edge.after)) | |
| return ValidationReport(ok=not issues, issues=issues, checked=checked, recomputed_objective=float(tardy)) | |
| def format_input_error(report: ValidationReport) -> str: | |
| if report.ok: | |
| return "" | |
| return " | ".join(f"{item.code}: {item.message}" for item in report.issues[:8]) | |