Download demo/src/generator.py from AriaAICompany/or-bench-problems: direct link, hf CLI and curl.
- Browser
- Download file 19.9 kB
-
https://huggingface.co/datasets/AriaAICompany/or-bench-problems/resolve/main/demo/src/generator.py
- Command line
-
hf download hf://datasets/AriaAICompany/or-bench-problems/demo/src/generator.py
-
curl -L -o generator.py https://huggingface.co/datasets/AriaAICompany/or-bench-problems/resolve/main/demo/src/generator.py
19.9 kB
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import random | |
| from pathlib import Path | |
| from src.domain import ( | |
| DEFAULT_SEED, | |
| N_ASSIGNMENT, | |
| N_INVENTORY, | |
| N_PROBLEMS, | |
| N_SCHEDULING, | |
| AssignmentAgent, | |
| AssignmentCost, | |
| AssignmentInstance, | |
| AssignmentTask, | |
| Difficulty, | |
| Family, | |
| InventoryInstance, | |
| InventorySku, | |
| ProblemRecord, | |
| ScheduleInstance, | |
| ScheduleJob, | |
| SchedulePrecedence, | |
| Split, | |
| ) | |
| from src.optimizer import solve_instance | |
| DEV_TEMPLATES = ("D-A", "D-B", "D-C") | |
| TEST_TEMPLATES = ("T-A", "T-B") | |
| SKU_NAMES = ("bearing", "seal", "gasket", "filter", "hose", "valve") | |
| SKU_FA = ("بلبرینگ", "آببند", "واشر", "فیلتر", "شیلنگ", "شیر") | |
| TASK_SKILLS = ("weld", "inspect", "pack", "lift") | |
| INTERACTIVE_IDS = ( | |
| "INV-001", | |
| "INV-008", | |
| "INV-014", | |
| "INV-021", | |
| "INV-028", | |
| "INV-031", | |
| "INV-034", | |
| "ASN-001", | |
| "ASN-006", | |
| "ASN-012", | |
| "ASN-018", | |
| "ASN-024", | |
| "ASN-029", | |
| "ASN-033", | |
| "SCH-001", | |
| "SCH-007", | |
| "SCH-013", | |
| "SCH-019", | |
| "SCH-027", | |
| "SCH-033", | |
| ) | |
| def _split_for(index: int, n_items: int) -> Split: | |
| # First 20 of each family → 60 development / 40 test overall. | |
| _ = n_items | |
| return Split.DEVELOPMENT if index <= 20 else Split.TEST | |
| def _difficulty(index: int, n_items: int, infeasible_tail: int) -> Difficulty: | |
| if index > n_items - infeasible_tail: | |
| return Difficulty.INFEASIBLE | |
| if index % 7 == 0: | |
| return Difficulty.HARD | |
| if index % 3 == 0: | |
| return Difficulty.MEDIUM | |
| return Difficulty.EASY | |
| def _template(split: Split, index: int) -> str: | |
| pool = DEV_TEMPLATES if split == Split.DEVELOPMENT else TEST_TEMPLATES | |
| return pool[(index - 1) % len(pool)] | |
| def _key(*parts: object) -> str: | |
| raw = "|".join(str(item) for item in parts) | |
| return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16] | |
| def _wrap_schema(payload: dict, template_id: str) -> str: | |
| if template_id.startswith("D-"): | |
| return "SCHEMA_BEGIN\n" + json.dumps(payload, ensure_ascii=False) + "\nSCHEMA_END\n" | |
| return "" | |
| def _json_prompt(payload: dict) -> str: | |
| return json.dumps(payload, ensure_ascii=False, indent=2) | |
| def make_inventory(index: int, rng: random.Random) -> tuple[InventoryInstance, str]: | |
| difficulty = _difficulty(index, N_INVENTORY, 3) | |
| n_sku = 2 if difficulty == Difficulty.EASY else 3 if difficulty != Difficulty.HARD else 4 | |
| periods = 3 if difficulty != Difficulty.HARD else 4 | |
| cover = difficulty in {Difficulty.HARD, Difficulty.INFEASIBLE} or index % 5 == 0 | |
| skus = [] | |
| for k in range(n_sku): | |
| demand = [rng.randint(2, 8) for _ in range(periods)] | |
| pack = rng.choice([1, 2, 3]) | |
| skus.append( | |
| InventorySku( | |
| sku_id=f"S{k + 1}", | |
| name=SKU_NAMES[k], | |
| demand=demand, | |
| initial_stock=rng.randint(0, 3), | |
| unit_cost=rng.randint(3, 9), | |
| holding_cost=rng.randint(1, 3), | |
| shortage_cost=rng.randint(6, 14), | |
| pack_size=pack, | |
| lead_time=0, | |
| ) | |
| ) | |
| total_need = sum(max(0, sum(sku.demand) - sku.initial_stock) for sku in skus) | |
| min_buy = 0 | |
| for sku in skus: | |
| need = max(0, sum(sku.demand) - sku.initial_stock) | |
| packs = (need + sku.pack_size - 1) // sku.pack_size | |
| min_buy += packs * sku.pack_size * sku.unit_cost | |
| cap = max(8, int(total_need * 0.7) + rng.randint(2, 8)) | |
| if difficulty == Difficulty.INFEASIBLE: | |
| for sku in skus: | |
| sku.initial_stock = 0 | |
| sku.demand = [max(3, value) for value in sku.demand] | |
| total_need = sum(sum(sku.demand) for sku in skus) | |
| min_buy = 0 | |
| for sku in skus: | |
| packs = (sum(sku.demand) + sku.pack_size - 1) // sku.pack_size | |
| min_buy += packs * sku.pack_size * sku.unit_cost | |
| budget = max(1, min_buy // 5) | |
| cover = True | |
| cap = max(6, total_need) | |
| elif difficulty == Difficulty.HARD: | |
| budget = max(min_buy, int(min_buy * 1.05) + 2) | |
| else: | |
| budget = min_buy + rng.randint(8, 24) | |
| instance = InventoryInstance( | |
| periods=periods, | |
| budget=int(budget), | |
| warehouse_capacity=int(cap), | |
| cover_required=cover, | |
| lost_sales=True, | |
| skus=skus, | |
| ) | |
| return instance, difficulty.value | |
| def render_inventory(instance: InventoryInstance, template_id: str, language: str) -> tuple[str, str]: | |
| labeled = [] | |
| for sku in instance.skus: | |
| labeled.append( | |
| f"SKU {sku.sku_id} demand={','.join(str(v) for v in sku.demand)} pack={sku.pack_size} " | |
| f"cost={sku.unit_cost} hold={sku.holding_cost} short={sku.shortage_cost} stock={sku.initial_stock}" | |
| ) | |
| labels = ( | |
| f"PERIODS: {instance.periods}\nBUDGET: {instance.budget}\nCAPACITY: {instance.warehouse_capacity}\n" | |
| f"COVER_REQUIRED: {1 if instance.cover_required else 0}\n" + "\n".join(labeled) | |
| ) | |
| schema_block = _wrap_schema(instance.model_dump(), template_id) | |
| names = ", ".join(f"{sku.sku_id} ({sku.name})" for sku in instance.skus) | |
| names_fa = ", ".join(f"{sku.sku_id} ({SKU_FA[int(sku.sku_id[1:]) - 1]})" for sku in instance.skus) | |
| cover_en = "All demand must be covered; lost sales are forbidden." if instance.cover_required else "Lost sales are allowed and charged." | |
| cover_fa = "پوشش کامل تقاضا الزامی است." if instance.cover_required else "کمبود مجاز است و جریمه دارد." | |
| if template_id in {"D-A", "D-B", "D-C"}: | |
| en = ( | |
| f"A B2B warehouse plans {instance.periods} weeks for {len(instance.skus)} SKUs: {names}. " | |
| f"{cover_en} Orders are pack multiples. Lead time is 0. " | |
| f"Budget is {instance.budget} currency units. Storage holds at most {instance.warehouse_capacity} units in total. " | |
| "Minimize purchase + holding + shortage.\n" | |
| f"{labels}\n{schema_block}" | |
| ) | |
| fa = ( | |
| f"یک انبار B2B برای {instance.periods} هفته و {len(instance.skus)} کالا برنامه میخرد: {names_fa}. " | |
| f"{cover_fa} سفارش مضرب بسته است. زمان تأمین صفر است. " | |
| f"بودجه برابر {instance.budget} واحد پول و ظرفیت انبار {instance.warehouse_capacity} واحد است. " | |
| "هدف کمینهکردن خرید + نگهداری + کمبود است.\n" | |
| f"{labels}\n{schema_block}" | |
| ) | |
| else: | |
| demand_txt = "; ".join(f"{sku.sku_id} wants {sku.demand} at pack {sku.pack_size}" for sku in instance.skus) | |
| en = ( | |
| f"Replenish {names} over a {instance.periods}-week horizon. {cover_en} " | |
| f"The buyer cannot spend more than {instance.budget}. On-hand stock across SKUs cannot exceed {instance.warehouse_capacity}. " | |
| f"{demand_txt}. Costs and opening stock are in the JSON companion." | |
| ) | |
| fa = ( | |
| f"برای {names_fa} در افق {instance.periods} هفته خرید کنید. {cover_fa} " | |
| f"سقف هزینه {instance.budget} و سقف موجودی کل {instance.warehouse_capacity} است. " | |
| "جزئیات تقاضا و بسته در فایل JSON همراه است." | |
| ) | |
| return en, fa | |
| def make_assignment(index: int, rng: random.Random) -> tuple[AssignmentInstance, str]: | |
| difficulty = _difficulty(index, N_ASSIGNMENT, 2) | |
| n_tasks = 4 if difficulty == Difficulty.EASY else 6 if difficulty != Difficulty.HARD else 8 | |
| n_agents = 3 if difficulty != Difficulty.HARD else 4 | |
| tasks = [] | |
| for k in range(n_tasks): | |
| skills = [rng.choice(TASK_SKILLS)] | |
| if difficulty != Difficulty.EASY and rng.random() < 0.35: | |
| skills.append(rng.choice(TASK_SKILLS)) | |
| skills = sorted(set(skills)) | |
| tasks.append( | |
| AssignmentTask( | |
| task_id=f"T{k + 1}", | |
| name=f"job-{k + 1}", | |
| size=rng.randint(1, 3), | |
| required=True if difficulty == Difficulty.INFEASIBLE else (k < n_tasks - 1 or difficulty != Difficulty.EASY), | |
| skills=skills, | |
| penalty=rng.randint(20, 40), | |
| ) | |
| ) | |
| agents = [] | |
| for k in range(n_agents): | |
| skills = [TASK_SKILLS[k % len(TASK_SKILLS)]] | |
| if difficulty != Difficulty.EASY: | |
| skills.append(TASK_SKILLS[(k + 1) % len(TASK_SKILLS)]) | |
| agents.append( | |
| AssignmentAgent( | |
| agent_id=f"A{k + 1}", | |
| name=f"tech-{k + 1}", | |
| capacity=rng.randint(3, 6) if difficulty != Difficulty.INFEASIBLE else 1, | |
| skills=sorted(set(skills)), | |
| ) | |
| ) | |
| if difficulty == Difficulty.INFEASIBLE: | |
| for task in tasks: | |
| task.required = True | |
| task.size = 3 | |
| for agent in agents: | |
| agent.capacity = 1 | |
| else: | |
| for idx, task in enumerate(tasks): | |
| agent = agents[idx % len(agents)] | |
| if not (set(task.skills) & set(agent.skills)): | |
| task.skills = sorted(set(task.skills + agent.skills[:1])) | |
| required_load = sum(task.size for task in tasks if task.required) | |
| agents[-1].skills = sorted(set(TASK_SKILLS)) | |
| total_cap = sum(agent.capacity for agent in agents) | |
| if required_load > total_cap: | |
| agents[-1].capacity += required_load - total_cap + 2 | |
| else: | |
| agents[-1].capacity += 2 | |
| costs = [] | |
| for task in tasks: | |
| for agent in agents: | |
| if set(task.skills) & set(agent.skills) or not task.skills: | |
| costs.append(AssignmentCost(task_id=task.task_id, agent_id=agent.agent_id, cost=rng.randint(4, 18))) | |
| return AssignmentInstance(tasks=tasks, agents=agents, costs=costs), difficulty.value | |
| def render_assignment(instance: AssignmentInstance, template_id: str) -> tuple[str, str]: | |
| payload = instance.model_dump() | |
| schema_block = _wrap_schema(payload, template_id) | |
| task_txt = ", ".join(f"{task.task_id} size {task.size} skills {'/'.join(task.skills)}" for task in instance.tasks) | |
| agent_txt = ", ".join(f"{agent.agent_id} cap {agent.capacity} skills {'/'.join(agent.skills)}" for agent in instance.agents) | |
| if template_id.startswith("D-"): | |
| en = ( | |
| "Assign each required maintenance task to at most one eligible technician. " | |
| "Do not exceed agent capacity. Optional leftover tasks pay a penalty.\n" | |
| f"TASKS: {task_txt}\nAGENTS: {agent_txt}\n{schema_block}" | |
| ) | |
| fa = ( | |
| "هر کار الزامی را حداکثر به یک تکنسین واجد مهارت بدهید و از ظرفیت نفر تجاوز نکنید. " | |
| "کار اختیاریِ انجامنشده جریمه دارد.\n" | |
| f"TASKS: {task_txt}\nAGENTS: {agent_txt}\n{schema_block}" | |
| ) | |
| else: | |
| en = ( | |
| f"A service desk has technicians {agent_txt}. Work orders: {task_txt}. " | |
| "A task may use an agent only when they share a skill. Minimize assignment cost plus leftover penalties." | |
| ) | |
| fa = ( | |
| f"میز خدمت تکنسینهای {agent_txt} را دارد. سفارشها: {task_txt}. " | |
| "تخصیص فقط با مهارت مشترک مجاز است. هزینه تخصیص بهعلاوه جریمه کار باقیمانده کمینه شود." | |
| ) | |
| return en, fa | |
| def make_schedule(index: int, rng: random.Random) -> tuple[ScheduleInstance, str]: | |
| difficulty = _difficulty(index, N_SCHEDULING, 3) | |
| n_jobs = 4 if difficulty == Difficulty.EASY else 6 if difficulty != Difficulty.HARD else 8 | |
| machines = ["M1"] if difficulty == Difficulty.EASY else ["M1", "M2"] | |
| jobs = [] | |
| cursor = 0 | |
| for k in range(n_jobs): | |
| duration = rng.randint(2, 5) | |
| release = rng.choice([0, 0, 1, 2]) | |
| due = cursor + duration + rng.randint(1, 4) | |
| hard = difficulty == Difficulty.INFEASIBLE and k < 2 | |
| if difficulty == Difficulty.INFEASIBLE and k < 2: | |
| due = release + duration - 1 | |
| eligible = machines[:] if difficulty == Difficulty.EASY or rng.random() < 0.7 else [rng.choice(machines)] | |
| jobs.append( | |
| ScheduleJob( | |
| job_id=f"J{k + 1}", | |
| name=f"op-{k + 1}", | |
| duration=duration, | |
| release=release, | |
| due=max(due, release + duration), | |
| weight=rng.randint(1, 4), | |
| hard_due=hard, | |
| machine_eligible=eligible, | |
| ) | |
| ) | |
| cursor += duration | |
| if difficulty == Difficulty.INFEASIBLE and len(jobs) >= 2: | |
| jobs[0].hard_due = True | |
| jobs[0].due = jobs[0].release + jobs[0].duration - 1 | |
| jobs[1].hard_due = True | |
| jobs[1].due = jobs[1].release + jobs[1].duration - 1 | |
| if jobs[0].due < jobs[0].release + jobs[0].duration: | |
| pass | |
| precedences = [] | |
| if difficulty != Difficulty.EASY and n_jobs >= 3: | |
| precedences.append(SchedulePrecedence(before="J1", after="J3")) | |
| if difficulty == Difficulty.HARD and n_jobs >= 5: | |
| precedences.append(SchedulePrecedence(before="J2", after="J5")) | |
| horizon = sum(job.duration for job in jobs) + 8 | |
| return ScheduleInstance(machines=machines, jobs=jobs, precedences=precedences, horizon=horizon), difficulty.value | |
| def render_schedule(instance: ScheduleInstance, template_id: str) -> tuple[str, str]: | |
| payload = instance.model_dump() | |
| schema_block = _wrap_schema(payload, template_id) | |
| job_txt = ", ".join( | |
| f"{job.job_id} dur {job.duration} rel {job.release} due {job.due}{' hard' if job.hard_due else ''}" | |
| for job in instance.jobs | |
| ) | |
| pred = ", ".join(f"{edge.before}->{edge.after}" for edge in instance.precedences) or "none" | |
| if template_id.startswith("D-"): | |
| en = ( | |
| f"Schedule jobs on machines {', '.join(instance.machines)} without overlap. " | |
| f"Respect release times and precedences ({pred}). Hard due dates are deadlines.\n" | |
| f"JOBS: {job_txt}\n{schema_block}" | |
| ) | |
| fa = ( | |
| f"کارها را روی ماشینهای {', '.join(instance.machines)} بدون همپوشانی زمانبندی کنید. " | |
| f"زمان آزادسازی و تقدم ({pred}) رعایت شود. موعد سخت ضربالاجل است.\n" | |
| f"JOBS: {job_txt}\n{schema_block}" | |
| ) | |
| else: | |
| en = ( | |
| f"A shop has machines {', '.join(instance.machines)}. Jobs: {job_txt}. " | |
| f"Precedence: {pred}. Minimize weighted tardiness. Do not overlap a machine." | |
| ) | |
| fa = ( | |
| f"کارگاه ماشینهای {', '.join(instance.machines)} را دارد. کارها: {job_txt}. " | |
| f"تقدم: {pred}. تأخیر وزنی کمینه شود و ماشین همپوشانی نداشته باشد." | |
| ) | |
| return en, fa | |
| def _finalize( | |
| problem_id: str, | |
| family: Family, | |
| index: int, | |
| n_items: int, | |
| instance, | |
| difficulty: str, | |
| template_id: str, | |
| language: str, | |
| seed: int, | |
| prompt_en: str, | |
| prompt_fa: str, | |
| notes: str, | |
| ) -> ProblemRecord: | |
| split = _split_for(index, n_items) | |
| payload = instance.model_dump() | |
| gold = solve_instance(family, payload, seconds=6.0, threads=1) | |
| wanted = Difficulty(difficulty) | |
| if wanted == Difficulty.INFEASIBLE and gold.solution.status.value != "infeasible": | |
| notes = (notes + " requested infeasible; solver found a plan so the row is hard.").strip() | |
| wanted = Difficulty.HARD | |
| structural = _key( | |
| family.value, | |
| split.value, | |
| template_id, | |
| problem_id, | |
| json.dumps(payload, sort_keys=True, ensure_ascii=False), | |
| wanted.value, | |
| ) | |
| return ProblemRecord( | |
| problem_id=problem_id, | |
| family=family, | |
| split=split, | |
| interactive=problem_id in INTERACTIVE_IDS, | |
| difficulty=wanted, | |
| language=language, | |
| template_id=template_id, | |
| seed=seed, | |
| prompt_en=prompt_en, | |
| prompt_fa=prompt_fa, | |
| prompt_json=_json_prompt(payload), | |
| schema_payload=payload, | |
| gold_status=gold.solution.status.value, | |
| gold_objective=gold.solution.objective, | |
| gold_bound=gold.solution.bound, | |
| gold_solution=gold.solution.as_dict(), | |
| structural_key=structural, | |
| notes=notes, | |
| ) | |
| def generate_catalog(seed: int = DEFAULT_SEED) -> list[ProblemRecord]: | |
| problems: list[ProblemRecord] = [] | |
| for index in range(1, N_INVENTORY + 1): | |
| rng = random.Random(seed * 1000 + index) | |
| instance, difficulty = make_inventory(index, rng) | |
| split = _split_for(index, N_INVENTORY) | |
| template_id = _template(split, index) | |
| language = "en" if index % 2 else "fa" | |
| en, fa = render_inventory(instance, template_id, language) | |
| problems.append( | |
| _finalize( | |
| f"INV-{index:03d}", | |
| Family.INVENTORY, | |
| index, | |
| N_INVENTORY, | |
| instance, | |
| difficulty, | |
| template_id, | |
| language, | |
| seed * 1000 + index, | |
| en, | |
| fa, | |
| "lead time is 0; units are abstract currency and pieces", | |
| ) | |
| ) | |
| for index in range(1, N_ASSIGNMENT + 1): | |
| rng = random.Random(seed * 2000 + index) | |
| instance, difficulty = make_assignment(index, rng) | |
| split = _split_for(index, N_ASSIGNMENT) | |
| template_id = _template(split, index) | |
| language = "fa" if index % 2 else "en" | |
| en, fa = render_assignment(instance, template_id) | |
| problems.append( | |
| _finalize( | |
| f"ASN-{index:03d}", | |
| Family.ASSIGNMENT, | |
| index, | |
| N_ASSIGNMENT, | |
| instance, | |
| difficulty, | |
| template_id, | |
| language, | |
| seed * 2000 + index, | |
| en, | |
| fa, | |
| "skill intersection is the eligibility rule", | |
| ) | |
| ) | |
| for index in range(1, N_SCHEDULING + 1): | |
| rng = random.Random(seed * 3000 + index) | |
| instance, difficulty = make_schedule(index, rng) | |
| split = _split_for(index, N_SCHEDULING) | |
| template_id = _template(split, index) | |
| language = "en" if index % 3 else "fa" | |
| en, fa = render_schedule(instance, template_id) | |
| problems.append( | |
| _finalize( | |
| f"SCH-{index:03d}", | |
| Family.SCHEDULING, | |
| index, | |
| N_SCHEDULING, | |
| instance, | |
| difficulty, | |
| template_id, | |
| language, | |
| seed * 3000 + index, | |
| en, | |
| fa, | |
| "objective reported as weighted tardiness; makespan is a tie-break inside the solver only", | |
| ) | |
| ) | |
| if len(problems) != N_PROBLEMS: | |
| raise RuntimeError(f"expected {N_PROBLEMS} problems, got {len(problems)}") | |
| return problems | |
| def write_catalog(path: Path, seed: int = DEFAULT_SEED) -> list[ProblemRecord]: | |
| problems = generate_catalog(seed) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with path.open("w", encoding="utf-8") as handle: | |
| for row in problems: | |
| handle.write(row.model_dump_json() + "\n") | |
| return problems | |
| def load_catalog(path: Path | None = None) -> list[ProblemRecord]: | |
| if path and path.exists(): | |
| rows = [] | |
| for line in path.read_text(encoding="utf-8").splitlines(): | |
| if line.strip(): | |
| rows.append(ProblemRecord.model_validate_json(line)) | |
| return rows | |
| return generate_catalog() | |