Download demo/src/optimizer.py from AriaAICompany/or-bench-problems: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/datasets/AriaAICompany/or-bench-problems/resolve/main/demo/src/optimizer.py
- Command line
-
hf download hf://datasets/AriaAICompany/or-bench-problems/demo/src/optimizer.py
-
curl -L -o optimizer.py https://huggingface.co/datasets/AriaAICompany/or-bench-problems/resolve/main/demo/src/optimizer.py
11.7 kB
| from __future__ import annotations | |
| import time | |
| from dataclasses import dataclass | |
| from ortools.sat.python import cp_model | |
| from src.domain import ( | |
| AssignmentInstance, | |
| AssignmentRow, | |
| Family, | |
| InventoryInstance, | |
| InventoryOrder, | |
| ScheduleInstance, | |
| ScheduleStart, | |
| Solution, | |
| SolveStatus, | |
| parse_instance, | |
| ) | |
| class SolverOutcome: | |
| solution: Solution | |
| seconds: float | |
| solver_name: str | |
| message: str | |
| def _status(model_status: int) -> SolveStatus: | |
| if model_status == cp_model.OPTIMAL: | |
| return SolveStatus.OPTIMAL | |
| if model_status == cp_model.FEASIBLE: | |
| return SolveStatus.FEASIBLE | |
| if model_status == cp_model.INFEASIBLE: | |
| return SolveStatus.INFEASIBLE | |
| if model_status in {cp_model.UNKNOWN, cp_model.MODEL_INVALID}: | |
| return SolveStatus.TIMEOUT | |
| return SolveStatus.ERROR | |
| def _status_name(model_status: int) -> str: | |
| names = { | |
| cp_model.OPTIMAL: "OPTIMAL", | |
| cp_model.FEASIBLE: "FEASIBLE", | |
| cp_model.INFEASIBLE: "INFEASIBLE", | |
| cp_model.UNKNOWN: "UNKNOWN", | |
| cp_model.MODEL_INVALID: "MODEL_INVALID", | |
| } | |
| return names.get(model_status, str(model_status)) | |
| def solve_inventory(instance: InventoryInstance, seconds: float, threads: int = 1) -> SolverOutcome: | |
| started = time.perf_counter() | |
| model = cp_model.CpModel() | |
| periods = instance.periods | |
| skus = instance.skus | |
| order: dict[tuple[str, int], cp_model.IntVar] = {} | |
| inv: dict[tuple[str, int], cp_model.IntVar] = {} | |
| short: dict[tuple[str, int], cp_model.IntVar] = {} | |
| sold: dict[tuple[str, int], cp_model.IntVar] = {} | |
| max_demand = max((max(sku.demand) for sku in skus), default=1) | |
| max_pack = max((sku.pack_size for sku in skus), default=1) | |
| max_order = max(max_demand * periods + max_pack * 4, 1) | |
| for sku in skus: | |
| for t in range(1, periods + 1): | |
| packs = model.NewIntVar(0, max_order // sku.pack_size + 1, f"packs_{sku.sku_id}_{t}") | |
| qty = model.NewIntVar(0, max_order, f"ord_{sku.sku_id}_{t}") | |
| model.Add(qty == packs * sku.pack_size) | |
| order[(sku.sku_id, t)] = qty | |
| inv[(sku.sku_id, t)] = model.NewIntVar(0, instance.warehouse_capacity, f"inv_{sku.sku_id}_{t}") | |
| demand = int(sku.demand[t - 1]) | |
| short[(sku.sku_id, t)] = model.NewIntVar(0, demand, f"sh_{sku.sku_id}_{t}") | |
| sold[(sku.sku_id, t)] = model.NewIntVar(0, demand, f"sd_{sku.sku_id}_{t}") | |
| prev = sku.initial_stock if t == 1 else inv[(sku.sku_id, t - 1)] | |
| model.Add(inv[(sku.sku_id, t)] + sold[(sku.sku_id, t)] == prev + qty) | |
| model.Add(sold[(sku.sku_id, t)] + short[(sku.sku_id, t)] == demand) | |
| if instance.cover_required: | |
| model.Add(short[(sku.sku_id, t)] == 0) | |
| for t in range(1, periods + 1): | |
| model.Add(sum(inv[(sku.sku_id, t)] for sku in skus) <= instance.warehouse_capacity) | |
| model.Add( | |
| sum(sku.unit_cost * order[(sku.sku_id, t)] for sku in skus for t in range(1, periods + 1)) <= instance.budget | |
| ) | |
| objective = [] | |
| for sku in skus: | |
| for t in range(1, periods + 1): | |
| objective.append(sku.unit_cost * order[(sku.sku_id, t)]) | |
| objective.append(sku.holding_cost * inv[(sku.sku_id, t)]) | |
| objective.append(sku.shortage_cost * short[(sku.sku_id, t)]) | |
| model.Minimize(sum(objective)) | |
| solver = cp_model.CpSolver() | |
| solver.parameters.max_time_in_seconds = float(seconds) | |
| solver.parameters.num_search_workers = int(threads) | |
| raw = solver.Solve(model) | |
| status = _status(raw) | |
| elapsed = time.perf_counter() - started | |
| message = _status_name(raw) | |
| if status in {SolveStatus.OPTIMAL, SolveStatus.FEASIBLE}: | |
| orders = [ | |
| InventoryOrder(sku_id=sku.sku_id, period=t, qty=int(solver.Value(order[(sku.sku_id, t)]))) | |
| for sku in skus | |
| for t in range(1, periods + 1) | |
| ] | |
| obj = float(solver.ObjectiveValue()) | |
| bound = float(solver.BestObjectiveBound()) if status == SolveStatus.FEASIBLE else obj | |
| return SolverOutcome( | |
| Solution( | |
| family=Family.INVENTORY, | |
| status=status, | |
| objective=obj, | |
| bound=bound, | |
| orders=orders, | |
| message=message, | |
| ), | |
| elapsed, | |
| "ortools-cpsat", | |
| message, | |
| ) | |
| return SolverOutcome( | |
| Solution(family=Family.INVENTORY, status=status, message=message), | |
| elapsed, | |
| "ortools-cpsat", | |
| message, | |
| ) | |
| def solve_assignment(instance: AssignmentInstance, seconds: float, threads: int = 1) -> SolverOutcome: | |
| started = time.perf_counter() | |
| model = cp_model.CpModel() | |
| x: dict[tuple[str, str], cp_model.IntVar] = {} | |
| costs = instance.cost_map() | |
| for task in instance.tasks: | |
| for agent in instance.agents: | |
| if instance.eligible(task, agent) and (task.task_id, agent.agent_id) in costs: | |
| x[(task.task_id, agent.agent_id)] = model.NewBoolVar(f"x_{task.task_id}_{agent.agent_id}") | |
| unassigned: dict[str, cp_model.IntVar] = {} | |
| for task in instance.tasks: | |
| assigned = [x[(task.task_id, agent.agent_id)] for agent in instance.agents if (task.task_id, agent.agent_id) in x] | |
| miss = model.NewBoolVar(f"u_{task.task_id}") | |
| unassigned[task.task_id] = miss | |
| model.Add(sum(assigned) + miss == 1) | |
| if task.required: | |
| model.Add(miss == 0) | |
| for agent in instance.agents: | |
| load = [ | |
| task.size * x[(task.task_id, agent.agent_id)] | |
| for task in instance.tasks | |
| if (task.task_id, agent.agent_id) in x | |
| ] | |
| if load: | |
| model.Add(sum(load) <= agent.capacity) | |
| obj_terms = [] | |
| for (task_id, agent_id), var in x.items(): | |
| obj_terms.append(costs[(task_id, agent_id)] * var) | |
| for task in instance.tasks: | |
| obj_terms.append(task.penalty * unassigned[task.task_id]) | |
| model.Minimize(sum(obj_terms) if obj_terms else 0) | |
| solver = cp_model.CpSolver() | |
| solver.parameters.max_time_in_seconds = float(seconds) | |
| solver.parameters.num_search_workers = int(threads) | |
| raw = solver.Solve(model) | |
| status = _status(raw) | |
| elapsed = time.perf_counter() - started | |
| message = _status_name(raw) | |
| if status in {SolveStatus.OPTIMAL, SolveStatus.FEASIBLE}: | |
| rows = [ | |
| AssignmentRow(task_id=task_id, agent_id=agent_id) | |
| for (task_id, agent_id), var in x.items() | |
| if solver.Value(var) | |
| ] | |
| leftover = [task_id for task_id, var in unassigned.items() if solver.Value(var)] | |
| obj = float(solver.ObjectiveValue()) | |
| bound = float(solver.BestObjectiveBound()) if status == SolveStatus.FEASIBLE else obj | |
| return SolverOutcome( | |
| Solution( | |
| family=Family.ASSIGNMENT, | |
| status=status, | |
| objective=obj, | |
| bound=bound, | |
| assignments=rows, | |
| unassigned=leftover, | |
| message=message, | |
| ), | |
| elapsed, | |
| "ortools-cpsat", | |
| message, | |
| ) | |
| return SolverOutcome( | |
| Solution(family=Family.ASSIGNMENT, status=status, message=message), | |
| elapsed, | |
| "ortools-cpsat", | |
| message, | |
| ) | |
| def solve_scheduling(instance: ScheduleInstance, seconds: float, threads: int = 1) -> SolverOutcome: | |
| started = time.perf_counter() | |
| model = cp_model.CpModel() | |
| horizon = max(instance.horizon, sum(job.duration for job in instance.jobs) + max((job.release for job in instance.jobs), default=0) + 2) | |
| intervals_by_machine: dict[str, list] = {machine: [] for machine in instance.machines} | |
| start: dict[str, cp_model.IntVar] = {} | |
| end: dict[str, cp_model.IntVar] = {} | |
| tardy: dict[str, cp_model.IntVar] = {} | |
| assign: dict[tuple[str, str], cp_model.IntVar] = {} | |
| for job in instance.jobs: | |
| start[job.job_id] = model.NewIntVar(job.release, horizon, f"s_{job.job_id}") | |
| end[job.job_id] = model.NewIntVar(job.release + job.duration, horizon + job.duration, f"e_{job.job_id}") | |
| model.Add(end[job.job_id] == start[job.job_id] + job.duration) | |
| tardy[job.job_id] = model.NewIntVar(0, horizon + job.duration, f"tard_{job.job_id}") | |
| model.Add(tardy[job.job_id] >= end[job.job_id] - job.due) | |
| if job.hard_due: | |
| model.Add(end[job.job_id] <= job.due) | |
| eligible = [machine for machine in instance.machines if machine in set(job.machine_eligible)] | |
| if not eligible: | |
| eligible = list(instance.machines) | |
| machine_bools = [] | |
| for machine in eligible: | |
| flag = model.NewBoolVar(f"m_{job.job_id}_{machine}") | |
| assign[(job.job_id, machine)] = flag | |
| interval = model.NewOptionalIntervalVar(start[job.job_id], job.duration, end[job.job_id], flag, f"iv_{job.job_id}_{machine}") | |
| intervals_by_machine[machine].append(interval) | |
| machine_bools.append(flag) | |
| model.AddExactlyOne(machine_bools) | |
| for machine, intervals in intervals_by_machine.items(): | |
| if intervals: | |
| model.AddNoOverlap(intervals) | |
| job_ids = {job.job_id for job in instance.jobs} | |
| for edge in instance.precedences: | |
| if edge.before in job_ids and edge.after in job_ids: | |
| model.Add(end[edge.before] <= start[edge.after]) | |
| makespan = model.NewIntVar(0, horizon + 8, "makespan") | |
| for job in instance.jobs: | |
| model.Add(makespan >= end[job.job_id]) | |
| model.Minimize(sum(job.weight * tardy[job.job_id] for job in instance.jobs) * 100 + makespan) | |
| solver = cp_model.CpSolver() | |
| solver.parameters.max_time_in_seconds = float(seconds) | |
| solver.parameters.num_search_workers = int(threads) | |
| raw = solver.Solve(model) | |
| status = _status(raw) | |
| elapsed = time.perf_counter() - started | |
| message = _status_name(raw) | |
| if status in {SolveStatus.OPTIMAL, SolveStatus.FEASIBLE}: | |
| starts = [] | |
| for job in instance.jobs: | |
| machine_id = next(machine for machine in instance.machines if (job.job_id, machine) in assign and solver.Value(assign[(job.job_id, machine)])) | |
| starts.append( | |
| ScheduleStart( | |
| job_id=job.job_id, | |
| machine_id=machine_id, | |
| start=int(solver.Value(start[job.job_id])), | |
| end=int(solver.Value(end[job.job_id])), | |
| ) | |
| ) | |
| weighted = sum(job.weight * max(0, int(solver.Value(end[job.job_id])) - job.due) for job in instance.jobs) | |
| obj = float(weighted) | |
| return SolverOutcome( | |
| Solution( | |
| family=Family.SCHEDULING, | |
| status=status, | |
| objective=obj, | |
| bound=obj if status == SolveStatus.OPTIMAL else None, | |
| starts=starts, | |
| message=message, | |
| ), | |
| elapsed, | |
| "ortools-cpsat", | |
| message, | |
| ) | |
| return SolverOutcome( | |
| Solution(family=Family.SCHEDULING, status=status, message=message), | |
| elapsed, | |
| "ortools-cpsat", | |
| message, | |
| ) | |
| def solve_instance(family: Family | str, payload: dict, seconds: float, threads: int = 1) -> SolverOutcome: | |
| family = Family(family) | |
| instance = parse_instance(family, payload) | |
| if family == Family.INVENTORY: | |
| return solve_inventory(instance, seconds, threads) | |
| if family == Family.ASSIGNMENT: | |
| return solve_assignment(instance, seconds, threads) | |
| return solve_scheduling(instance, seconds, threads) | |