Publish ORBench 100-problem catalog and recorded results
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- README.md +54 -0
- data/leaderboard.csv +11 -0
- data/problems.jsonl +0 -0
- data/protocol.md +13 -0
- data/results.jsonl +0 -0
- data/sample_preview.json +17 -0
- data/splits.json +128 -0
- demo/.gitattributes +8 -0
- demo/.gitignore +6 -0
- demo/README.md +55 -0
- demo/app.py +8 -0
- demo/examples/leaderboard.csv +11 -0
- demo/examples/problems.jsonl +0 -0
- demo/examples/protocol.md +13 -0
- demo/examples/results.jsonl +0 -0
- demo/examples/sample_preview.json +17 -0
- demo/examples/splits.json +128 -0
- demo/requirements.txt +5 -0
- demo/src/__init__.py +1 -0
- demo/src/__pycache__/__init__.cpython-312.pyc +0 -0
- demo/src/__pycache__/baseline.cpython-312.pyc +0 -0
- demo/src/__pycache__/budget_guard.cpython-312.pyc +0 -0
- demo/src/__pycache__/domain.cpython-312.pyc +0 -0
- demo/src/__pycache__/explain.cpython-312.pyc +0 -0
- demo/src/__pycache__/extractor.cpython-312.pyc +0 -0
- demo/src/__pycache__/generator.cpython-312.pyc +0 -0
- demo/src/__pycache__/i18n.cpython-312.pyc +0 -0
- demo/src/__pycache__/metrics.cpython-312.pyc +0 -0
- demo/src/__pycache__/model_registry.cpython-312.pyc +0 -0
- demo/src/__pycache__/optimizer.cpython-312.pyc +0 -0
- demo/src/__pycache__/pipeline.cpython-312.pyc +0 -0
- demo/src/__pycache__/plots.cpython-312.pyc +0 -0
- demo/src/__pycache__/validation.cpython-312.pyc +0 -0
- demo/src/baseline.py +181 -0
- demo/src/budget_guard.py +22 -0
- demo/src/domain.py +297 -0
- demo/src/explain.py +81 -0
- demo/src/extractor.py +186 -0
- demo/src/generator.py +501 -0
- demo/src/i18n.py +112 -0
- demo/src/metrics.py +201 -0
- demo/src/model_registry.py +114 -0
- demo/src/optimizer.py +300 -0
- demo/src/pipeline.py +385 -0
- demo/src/plots.py +142 -0
- demo/src/ui.py +470 -0
- demo/src/validation.py +235 -0
- demo/tests/__pycache__/conftest.cpython-312-pytest-8.3.4.pyc +0 -0
- demo/tests/__pycache__/test_pipeline.cpython-312-pytest-8.3.4.pyc +0 -0
- demo/tests/conftest.py +6 -0
README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-4.0
|
| 3 |
+
pretty_name: ORBench Decision Problems
|
| 4 |
+
task_categories:
|
| 5 |
+
- other
|
| 6 |
+
- text-generation
|
| 7 |
+
- structured-data-extraction
|
| 8 |
+
tags:
|
| 9 |
+
- operations-research
|
| 10 |
+
- model-benchmarking
|
| 11 |
+
- structured-generation
|
| 12 |
+
- synthetic
|
| 13 |
+
- evaluation
|
| 14 |
+
language:
|
| 15 |
+
- en
|
| 16 |
+
- fa
|
| 17 |
+
size_categories:
|
| 18 |
+
- n<1K
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
# ORBench problems and recorded results
|
| 22 |
+
|
| 23 |
+
100 synthetic inventory, assignment, and scheduling instances for the ORBench demo.
|
| 24 |
+
|
| 25 |
+
Organization dataset and collection are public. Live Gradio and the organization card are created by `scripts/publish.py`. Runnable Space source is stored in `demo/`. Collection: [Aria AI — OR + LLM Evaluation](https://huggingface.co/collections/AriaAICompany/aria-ai-or-llm-evaluation).
|
| 26 |
+
|
| 27 |
+
Generated data, seed 25. All identifiers are synthetic. Gold objectives come from OR-Tools CP-SAT on the same schema that ships in each row. LLM rows in `results.jsonl` are explicitly `not_evaluated`.
|
| 28 |
+
|
| 29 |
+
## Files
|
| 30 |
+
|
| 31 |
+
- data/problems.jsonl
|
| 32 |
+
- data/results.jsonl
|
| 33 |
+
- data/leaderboard.csv
|
| 34 |
+
- data/splits.json
|
| 35 |
+
- data/sample_preview.json
|
| 36 |
+
- data/protocol.md
|
| 37 |
+
- demo/ — runnable Gradio Space source
|
| 38 |
+
- showcase/ — organization static card
|
| 39 |
+
|
| 40 |
+
## Splits
|
| 41 |
+
|
| 42 |
+
- development: 60 instances, templates `D-A` / `D-B` / `D-C` with a `SCHEMA_BEGIN` block
|
| 43 |
+
- test: 40 instances, templates `T-A` / `T-B` in prose
|
| 44 |
+
- interactive: 20 ids listed in `splits.json`
|
| 45 |
+
|
| 46 |
+
Development and test do not share `(family, template_id)` pairs. Near-duplicate prompt templates are therefore not reused across the split.
|
| 47 |
+
|
| 48 |
+
## Metrics
|
| 49 |
+
|
| 50 |
+
Independent validators recompute inventory balance, pack multiples, budget, capacity, assignment uniqueness/eligibility/capacity, and schedule overlap/precedence/release. Optimality gap is reported only when gold status is `optimal`. An unevaluated method is never written as 0.
|
| 51 |
+
|
| 52 |
+
## License
|
| 53 |
+
|
| 54 |
+
CC-BY-4.0. Keep the synthetic-data label.
|
data/leaderboard.csv
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
method_id,evaluated,n,parse_rate,feasible_rate,infeasible_agreement,mean_gap,mean_fidelity,mean_seconds,mean_cost_usd,n_optimal
|
| 2 |
+
heuristic,True,100,1.0,0.91,0.0,0.031919404673584915,1.0,7.628599880263209e-05,0.0,0
|
| 3 |
+
json-extractor+solver,True,100,1.0,0.92,1.0,2.613101900343095e-18,1.0,0.004290478996699676,0.0,92
|
| 4 |
+
naive-direct,True,100,1.0,0.22,0.0,0.0,1.0,4.173900291789323e-05,0.0,0
|
| 5 |
+
structured-solver,True,100,1.0,0.92,1.0,2.613101900343095e-18,1.0,0.004329786997986957,0.0,92
|
| 6 |
+
template-extractor+solver,True,100,0.6,0.6,0.0,2.033026425636911e-18,0.6,0.0030710569996153935,0.0,60
|
| 7 |
+
Qwen/Qwen3-4B-Instruct-2507,False,100,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated
|
| 8 |
+
Qwen/Qwen3.8-27B,False,100,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated
|
| 9 |
+
deepseek-ai/DeepSeek-V4.1-Flash,False,100,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated
|
| 10 |
+
moonshotai/Kimi-K3,False,100,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated
|
| 11 |
+
zai-org/GLM-5.3,False,100,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated
|
data/problems.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/protocol.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ORBench reproduction protocol v1
|
| 2 |
+
|
| 3 |
+
Seed: 25. Code version: 0.1.0. Solver: OR-Tools CP-SAT, 1 thread, 6–8 seconds.
|
| 4 |
+
|
| 5 |
+
1. Generate the catalog with `python scripts/build_artifacts.py`.
|
| 6 |
+
2. Each problem stores `schema_payload`, bilingual prompts, `gold_status`, `gold_objective`, and `gold_solution`.
|
| 7 |
+
3. Evaluated methods: `structured-solver`, `heuristic`, `json-extractor+solver`, `template-extractor+solver`, `naive-direct`.
|
| 8 |
+
4. Listed but not run: `Qwen/Qwen3-4B-Instruct-2507`, `Qwen/Qwen3.8-27B`, `moonshotai/Kimi-K3`, `zai-org/GLM-5.3`, `deepseek-ai/DeepSeek-V4.1-Flash`. Cells are `not_evaluated`.
|
| 9 |
+
5. Gap = max(0, (method_obj − gold_obj) / max(1, |gold_obj|)) only if gold status is optimal and the method plan is feasible.
|
| 10 |
+
6. Paid APIs stay off. Do not substitute a second paid provider when the first is missing.
|
| 11 |
+
7. Synthetic results in this dataset are not customer data.
|
| 12 |
+
|
| 13 |
+
Run `pytest tests/test_pipeline.py` after generation. A passing suite is the acceptance check for constraint validation, split hygiene, and honest unevaluated cells.
|
data/results.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/sample_preview.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"run_id": "orbench-eccc1a511a",
|
| 3 |
+
"status": "optimal",
|
| 4 |
+
"kpis": {
|
| 5 |
+
"n_problems": 100,
|
| 6 |
+
"structured_feasible": 0.92,
|
| 7 |
+
"heuristic_gap": 0.031919404673584915,
|
| 8 |
+
"template_fidelity": 0.6,
|
| 9 |
+
"n_methods_evaluated": 5,
|
| 10 |
+
"n_methods_listed": 10
|
| 11 |
+
},
|
| 12 |
+
"kpi_html": "<div class='kpi-grid'><article class='kpi-card'><p class='kpi-label'>Problems in view</p><p class='kpi-value'>100</p><p class='kpi-sub'>interactive subset or filtered catalog</p></article><article class='kpi-card'><p class='kpi-label'>Structured-solver feasible</p><p class='kpi-value'>92%</p><p class='kpi-sub'>share of valid plans after independent checks</p></article><article class='kpi-card'><p class='kpi-label'>Heuristic mean gap</p><p class='kpi-value'>3.2%</p><p class='kpi-sub'>only where gold status is proven optimal</p></article><article class='kpi-card'><p class='kpi-label'>Template fidelity</p><p class='kpi-value'>60%</p><p class='kpi-sub'>atomic constraint facts recovered from text</p></article><article class='kpi-card'><p class='kpi-label'>Methods evaluated</p><p class='kpi-value'>5/10</p><p class='kpi-sub'>evaluated / listed — unevaluated is not zero</p></article></div>",
|
| 13 |
+
"precomputed": true,
|
| 14 |
+
"n_problems": 100,
|
| 15 |
+
"n_eval_rows": 1000,
|
| 16 |
+
"interactive": "INV-001"
|
| 17 |
+
}
|
data/splits.json
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"development": [
|
| 3 |
+
"INV-001",
|
| 4 |
+
"INV-002",
|
| 5 |
+
"INV-003",
|
| 6 |
+
"INV-004",
|
| 7 |
+
"INV-005",
|
| 8 |
+
"INV-006",
|
| 9 |
+
"INV-007",
|
| 10 |
+
"INV-008",
|
| 11 |
+
"INV-009",
|
| 12 |
+
"INV-010",
|
| 13 |
+
"INV-011",
|
| 14 |
+
"INV-012",
|
| 15 |
+
"INV-013",
|
| 16 |
+
"INV-014",
|
| 17 |
+
"INV-015",
|
| 18 |
+
"INV-016",
|
| 19 |
+
"INV-017",
|
| 20 |
+
"INV-018",
|
| 21 |
+
"INV-019",
|
| 22 |
+
"INV-020",
|
| 23 |
+
"ASN-001",
|
| 24 |
+
"ASN-002",
|
| 25 |
+
"ASN-003",
|
| 26 |
+
"ASN-004",
|
| 27 |
+
"ASN-005",
|
| 28 |
+
"ASN-006",
|
| 29 |
+
"ASN-007",
|
| 30 |
+
"ASN-008",
|
| 31 |
+
"ASN-009",
|
| 32 |
+
"ASN-010",
|
| 33 |
+
"ASN-011",
|
| 34 |
+
"ASN-012",
|
| 35 |
+
"ASN-013",
|
| 36 |
+
"ASN-014",
|
| 37 |
+
"ASN-015",
|
| 38 |
+
"ASN-016",
|
| 39 |
+
"ASN-017",
|
| 40 |
+
"ASN-018",
|
| 41 |
+
"ASN-019",
|
| 42 |
+
"ASN-020",
|
| 43 |
+
"SCH-001",
|
| 44 |
+
"SCH-002",
|
| 45 |
+
"SCH-003",
|
| 46 |
+
"SCH-004",
|
| 47 |
+
"SCH-005",
|
| 48 |
+
"SCH-006",
|
| 49 |
+
"SCH-007",
|
| 50 |
+
"SCH-008",
|
| 51 |
+
"SCH-009",
|
| 52 |
+
"SCH-010",
|
| 53 |
+
"SCH-011",
|
| 54 |
+
"SCH-012",
|
| 55 |
+
"SCH-013",
|
| 56 |
+
"SCH-014",
|
| 57 |
+
"SCH-015",
|
| 58 |
+
"SCH-016",
|
| 59 |
+
"SCH-017",
|
| 60 |
+
"SCH-018",
|
| 61 |
+
"SCH-019",
|
| 62 |
+
"SCH-020"
|
| 63 |
+
],
|
| 64 |
+
"test": [
|
| 65 |
+
"INV-021",
|
| 66 |
+
"INV-022",
|
| 67 |
+
"INV-023",
|
| 68 |
+
"INV-024",
|
| 69 |
+
"INV-025",
|
| 70 |
+
"INV-026",
|
| 71 |
+
"INV-027",
|
| 72 |
+
"INV-028",
|
| 73 |
+
"INV-029",
|
| 74 |
+
"INV-030",
|
| 75 |
+
"INV-031",
|
| 76 |
+
"INV-032",
|
| 77 |
+
"INV-033",
|
| 78 |
+
"INV-034",
|
| 79 |
+
"ASN-021",
|
| 80 |
+
"ASN-022",
|
| 81 |
+
"ASN-023",
|
| 82 |
+
"ASN-024",
|
| 83 |
+
"ASN-025",
|
| 84 |
+
"ASN-026",
|
| 85 |
+
"ASN-027",
|
| 86 |
+
"ASN-028",
|
| 87 |
+
"ASN-029",
|
| 88 |
+
"ASN-030",
|
| 89 |
+
"ASN-031",
|
| 90 |
+
"ASN-032",
|
| 91 |
+
"ASN-033",
|
| 92 |
+
"SCH-021",
|
| 93 |
+
"SCH-022",
|
| 94 |
+
"SCH-023",
|
| 95 |
+
"SCH-024",
|
| 96 |
+
"SCH-025",
|
| 97 |
+
"SCH-026",
|
| 98 |
+
"SCH-027",
|
| 99 |
+
"SCH-028",
|
| 100 |
+
"SCH-029",
|
| 101 |
+
"SCH-030",
|
| 102 |
+
"SCH-031",
|
| 103 |
+
"SCH-032",
|
| 104 |
+
"SCH-033"
|
| 105 |
+
],
|
| 106 |
+
"interactive": [
|
| 107 |
+
"INV-001",
|
| 108 |
+
"INV-008",
|
| 109 |
+
"INV-014",
|
| 110 |
+
"INV-021",
|
| 111 |
+
"INV-028",
|
| 112 |
+
"INV-031",
|
| 113 |
+
"INV-034",
|
| 114 |
+
"ASN-001",
|
| 115 |
+
"ASN-006",
|
| 116 |
+
"ASN-012",
|
| 117 |
+
"ASN-018",
|
| 118 |
+
"ASN-024",
|
| 119 |
+
"ASN-029",
|
| 120 |
+
"ASN-033",
|
| 121 |
+
"SCH-001",
|
| 122 |
+
"SCH-007",
|
| 123 |
+
"SCH-013",
|
| 124 |
+
"SCH-019",
|
| 125 |
+
"SCH-027",
|
| 126 |
+
"SCH-033"
|
| 127 |
+
]
|
| 128 |
+
}
|
demo/.gitattributes
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
* text=auto eol=lf
|
| 2 |
+
*.py text eol=lf
|
| 3 |
+
*.md text eol=lf
|
| 4 |
+
*.csv text eol=lf
|
| 5 |
+
*.json text eol=lf
|
| 6 |
+
*.jsonl text eol=lf
|
| 7 |
+
*.html text eol=lf
|
| 8 |
+
*.txt text eol=lf
|
demo/.gitignore
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
.pytest_cache/
|
| 3 |
+
.venv/
|
| 4 |
+
*.pyc
|
| 5 |
+
.gradio/
|
| 6 |
+
tmp/
|
demo/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: ORBench Solver and Agent Benchmark
|
| 3 |
+
emoji: 🧪
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.15.1
|
| 8 |
+
app_file: app.py
|
| 9 |
+
fullWidth: true
|
| 10 |
+
python_version: "3.12"
|
| 11 |
+
short_description: Compare OR solvers and agents on 100 small problems
|
| 12 |
+
pinned: true
|
| 13 |
+
license: apache-2.0
|
| 14 |
+
tags:
|
| 15 |
+
- model-benchmarking
|
| 16 |
+
- operations-research
|
| 17 |
+
- structured-generation
|
| 18 |
+
- evaluation
|
| 19 |
+
- data-visualization
|
| 20 |
+
datasets:
|
| 21 |
+
- AriaAICompany/or-bench-problems
|
| 22 |
+
---
|
| 23 |
+
|
| 24 |
+
# ORBench — Solver and Agent Decision Benchmark
|
| 25 |
+
|
| 26 |
+
**Aria AI** research prototype. Teams want to know whether a new model can recover constraints and produce a *valid* decision. A fluent paragraph is not a feasible plan. The numeric validator is the judge.
|
| 27 |
+
|
| 28 |
+
The MVP is 100 small synthetic instances from inventory, assignment, and scheduling, with a 60/40 development–test split and 20 interactive samples. Three comparison paths are recorded: structured form + CP-SAT, text → schema → solver, and a fixed heuristic. A naive direct answer is included only as a labeled benchmark, not as an operational planner.
|
| 29 |
+
|
| 30 |
+
## What you can do
|
| 31 |
+
|
| 32 |
+
1. Load one of the 20 interactive problems (English or Persian).
|
| 33 |
+
2. Compare CP-SAT, lot-for-lot / greedy / EDD, JSON extraction, template extraction, and a naive direct answer.
|
| 34 |
+
3. Hide a hard constraint in the prompt and watch fidelity drop.
|
| 35 |
+
4. Filter the recorded 100-problem table by family, split, language, or difficulty.
|
| 36 |
+
5. Download the comparison CSV and the JSON report.
|
| 37 |
+
|
| 38 |
+
CPU only. No paid API. Named Hub models (Qwen, Kimi, GLM, DeepSeek) stay **not_evaluated**. That cell is not a zero and not a rank.
|
| 39 |
+
|
| 40 |
+
## Hosting
|
| 41 |
+
|
| 42 |
+
- Live app: this Space (`alirezaaminzadeh/or-bench` if organization Gradio quota is 0).
|
| 43 |
+
- Organization card: [AriaAICompany/or-bench](https://huggingface.co/spaces/AriaAICompany/or-bench).
|
| 44 |
+
- Dataset: [AriaAICompany/or-bench-problems](https://huggingface.co/datasets/AriaAICompany/or-bench-problems).
|
| 45 |
+
- Collection: [Aria AI — OR + LLM Evaluation](https://huggingface.co/collections/AriaAICompany/aria-ai-or-llm-evaluation).
|
| 46 |
+
|
| 47 |
+
## Persian
|
| 48 |
+
|
| 49 |
+
اوربنچ روشهای ساخت تصمیم را روی مسئلههای کوچک موجودی، تخصیص و زمانبندی مقایسه میکند. داور validator عددی است. خانه مدل اجرانشده «ارزیابی نشده» است، نه صفر.
|
| 50 |
+
|
| 51 |
+
## Links
|
| 52 |
+
|
| 53 |
+
- [AriaAICompany](https://huggingface.co/AriaAICompany)
|
| 54 |
+
- [aria-ai.ir](https://aria-ai.ir/)
|
| 55 |
+
- Roadmap project 25 of 25
|
demo/app.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
|
| 3 |
+
from src.ui import CSS, build_demo
|
| 4 |
+
|
| 5 |
+
demo = build_demo()
|
| 6 |
+
|
| 7 |
+
if __name__ == "__main__":
|
| 8 |
+
demo.launch(theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="purple"), css=CSS)
|
demo/examples/leaderboard.csv
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
method_id,evaluated,n,parse_rate,feasible_rate,infeasible_agreement,mean_gap,mean_fidelity,mean_seconds,mean_cost_usd,n_optimal
|
| 2 |
+
heuristic,True,100,1.0,0.91,0.0,0.031919404673584915,1.0,7.628599880263209e-05,0.0,0
|
| 3 |
+
json-extractor+solver,True,100,1.0,0.92,1.0,2.613101900343095e-18,1.0,0.004290478996699676,0.0,92
|
| 4 |
+
naive-direct,True,100,1.0,0.22,0.0,0.0,1.0,4.173900291789323e-05,0.0,0
|
| 5 |
+
structured-solver,True,100,1.0,0.92,1.0,2.613101900343095e-18,1.0,0.004329786997986957,0.0,92
|
| 6 |
+
template-extractor+solver,True,100,0.6,0.6,0.0,2.033026425636911e-18,0.6,0.0030710569996153935,0.0,60
|
| 7 |
+
Qwen/Qwen3-4B-Instruct-2507,False,100,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated
|
| 8 |
+
Qwen/Qwen3.8-27B,False,100,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated
|
| 9 |
+
deepseek-ai/DeepSeek-V4.1-Flash,False,100,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated
|
| 10 |
+
moonshotai/Kimi-K3,False,100,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated
|
| 11 |
+
zai-org/GLM-5.3,False,100,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated,not_evaluated
|
demo/examples/problems.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
demo/examples/protocol.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ORBench reproduction protocol v1
|
| 2 |
+
|
| 3 |
+
Seed: 25. Code version: 0.1.0. Solver: OR-Tools CP-SAT, 1 thread, 6–8 seconds.
|
| 4 |
+
|
| 5 |
+
1. Generate the catalog with `python scripts/build_artifacts.py`.
|
| 6 |
+
2. Each problem stores `schema_payload`, bilingual prompts, `gold_status`, `gold_objective`, and `gold_solution`.
|
| 7 |
+
3. Evaluated methods: `structured-solver`, `heuristic`, `json-extractor+solver`, `template-extractor+solver`, `naive-direct`.
|
| 8 |
+
4. Listed but not run: `Qwen/Qwen3-4B-Instruct-2507`, `Qwen/Qwen3.8-27B`, `moonshotai/Kimi-K3`, `zai-org/GLM-5.3`, `deepseek-ai/DeepSeek-V4.1-Flash`. Cells are `not_evaluated`.
|
| 9 |
+
5. Gap = max(0, (method_obj − gold_obj) / max(1, |gold_obj|)) only if gold status is optimal and the method plan is feasible.
|
| 10 |
+
6. Paid APIs stay off. Do not substitute a second paid provider when the first is missing.
|
| 11 |
+
7. Synthetic results in this dataset are not customer data.
|
| 12 |
+
|
| 13 |
+
Run `pytest tests/test_pipeline.py` after generation. A passing suite is the acceptance check for constraint validation, split hygiene, and honest unevaluated cells.
|
demo/examples/results.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
demo/examples/sample_preview.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"run_id": "orbench-eccc1a511a",
|
| 3 |
+
"status": "optimal",
|
| 4 |
+
"kpis": {
|
| 5 |
+
"n_problems": 100,
|
| 6 |
+
"structured_feasible": 0.92,
|
| 7 |
+
"heuristic_gap": 0.031919404673584915,
|
| 8 |
+
"template_fidelity": 0.6,
|
| 9 |
+
"n_methods_evaluated": 5,
|
| 10 |
+
"n_methods_listed": 10
|
| 11 |
+
},
|
| 12 |
+
"kpi_html": "<div class='kpi-grid'><article class='kpi-card'><p class='kpi-label'>Problems in view</p><p class='kpi-value'>100</p><p class='kpi-sub'>interactive subset or filtered catalog</p></article><article class='kpi-card'><p class='kpi-label'>Structured-solver feasible</p><p class='kpi-value'>92%</p><p class='kpi-sub'>share of valid plans after independent checks</p></article><article class='kpi-card'><p class='kpi-label'>Heuristic mean gap</p><p class='kpi-value'>3.2%</p><p class='kpi-sub'>only where gold status is proven optimal</p></article><article class='kpi-card'><p class='kpi-label'>Template fidelity</p><p class='kpi-value'>60%</p><p class='kpi-sub'>atomic constraint facts recovered from text</p></article><article class='kpi-card'><p class='kpi-label'>Methods evaluated</p><p class='kpi-value'>5/10</p><p class='kpi-sub'>evaluated / listed — unevaluated is not zero</p></article></div>",
|
| 13 |
+
"precomputed": true,
|
| 14 |
+
"n_problems": 100,
|
| 15 |
+
"n_eval_rows": 1000,
|
| 16 |
+
"interactive": "INV-001"
|
| 17 |
+
}
|
demo/examples/splits.json
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"development": [
|
| 3 |
+
"INV-001",
|
| 4 |
+
"INV-002",
|
| 5 |
+
"INV-003",
|
| 6 |
+
"INV-004",
|
| 7 |
+
"INV-005",
|
| 8 |
+
"INV-006",
|
| 9 |
+
"INV-007",
|
| 10 |
+
"INV-008",
|
| 11 |
+
"INV-009",
|
| 12 |
+
"INV-010",
|
| 13 |
+
"INV-011",
|
| 14 |
+
"INV-012",
|
| 15 |
+
"INV-013",
|
| 16 |
+
"INV-014",
|
| 17 |
+
"INV-015",
|
| 18 |
+
"INV-016",
|
| 19 |
+
"INV-017",
|
| 20 |
+
"INV-018",
|
| 21 |
+
"INV-019",
|
| 22 |
+
"INV-020",
|
| 23 |
+
"ASN-001",
|
| 24 |
+
"ASN-002",
|
| 25 |
+
"ASN-003",
|
| 26 |
+
"ASN-004",
|
| 27 |
+
"ASN-005",
|
| 28 |
+
"ASN-006",
|
| 29 |
+
"ASN-007",
|
| 30 |
+
"ASN-008",
|
| 31 |
+
"ASN-009",
|
| 32 |
+
"ASN-010",
|
| 33 |
+
"ASN-011",
|
| 34 |
+
"ASN-012",
|
| 35 |
+
"ASN-013",
|
| 36 |
+
"ASN-014",
|
| 37 |
+
"ASN-015",
|
| 38 |
+
"ASN-016",
|
| 39 |
+
"ASN-017",
|
| 40 |
+
"ASN-018",
|
| 41 |
+
"ASN-019",
|
| 42 |
+
"ASN-020",
|
| 43 |
+
"SCH-001",
|
| 44 |
+
"SCH-002",
|
| 45 |
+
"SCH-003",
|
| 46 |
+
"SCH-004",
|
| 47 |
+
"SCH-005",
|
| 48 |
+
"SCH-006",
|
| 49 |
+
"SCH-007",
|
| 50 |
+
"SCH-008",
|
| 51 |
+
"SCH-009",
|
| 52 |
+
"SCH-010",
|
| 53 |
+
"SCH-011",
|
| 54 |
+
"SCH-012",
|
| 55 |
+
"SCH-013",
|
| 56 |
+
"SCH-014",
|
| 57 |
+
"SCH-015",
|
| 58 |
+
"SCH-016",
|
| 59 |
+
"SCH-017",
|
| 60 |
+
"SCH-018",
|
| 61 |
+
"SCH-019",
|
| 62 |
+
"SCH-020"
|
| 63 |
+
],
|
| 64 |
+
"test": [
|
| 65 |
+
"INV-021",
|
| 66 |
+
"INV-022",
|
| 67 |
+
"INV-023",
|
| 68 |
+
"INV-024",
|
| 69 |
+
"INV-025",
|
| 70 |
+
"INV-026",
|
| 71 |
+
"INV-027",
|
| 72 |
+
"INV-028",
|
| 73 |
+
"INV-029",
|
| 74 |
+
"INV-030",
|
| 75 |
+
"INV-031",
|
| 76 |
+
"INV-032",
|
| 77 |
+
"INV-033",
|
| 78 |
+
"INV-034",
|
| 79 |
+
"ASN-021",
|
| 80 |
+
"ASN-022",
|
| 81 |
+
"ASN-023",
|
| 82 |
+
"ASN-024",
|
| 83 |
+
"ASN-025",
|
| 84 |
+
"ASN-026",
|
| 85 |
+
"ASN-027",
|
| 86 |
+
"ASN-028",
|
| 87 |
+
"ASN-029",
|
| 88 |
+
"ASN-030",
|
| 89 |
+
"ASN-031",
|
| 90 |
+
"ASN-032",
|
| 91 |
+
"ASN-033",
|
| 92 |
+
"SCH-021",
|
| 93 |
+
"SCH-022",
|
| 94 |
+
"SCH-023",
|
| 95 |
+
"SCH-024",
|
| 96 |
+
"SCH-025",
|
| 97 |
+
"SCH-026",
|
| 98 |
+
"SCH-027",
|
| 99 |
+
"SCH-028",
|
| 100 |
+
"SCH-029",
|
| 101 |
+
"SCH-030",
|
| 102 |
+
"SCH-031",
|
| 103 |
+
"SCH-032",
|
| 104 |
+
"SCH-033"
|
| 105 |
+
],
|
| 106 |
+
"interactive": [
|
| 107 |
+
"INV-001",
|
| 108 |
+
"INV-008",
|
| 109 |
+
"INV-014",
|
| 110 |
+
"INV-021",
|
| 111 |
+
"INV-028",
|
| 112 |
+
"INV-031",
|
| 113 |
+
"INV-034",
|
| 114 |
+
"ASN-001",
|
| 115 |
+
"ASN-006",
|
| 116 |
+
"ASN-012",
|
| 117 |
+
"ASN-018",
|
| 118 |
+
"ASN-024",
|
| 119 |
+
"ASN-029",
|
| 120 |
+
"ASN-033",
|
| 121 |
+
"SCH-001",
|
| 122 |
+
"SCH-007",
|
| 123 |
+
"SCH-013",
|
| 124 |
+
"SCH-019",
|
| 125 |
+
"SCH-027",
|
| 126 |
+
"SCH-033"
|
| 127 |
+
]
|
| 128 |
+
}
|
demo/requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pandas>=2.2.0,<3
|
| 2 |
+
numpy>=1.26.0,<3
|
| 3 |
+
pydantic>=2.6.0,<3
|
| 4 |
+
ortools>=9.10,<10
|
| 5 |
+
plotly>=5.24.0,<7
|
demo/src/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""ORBench — reproducible comparison of solvers and structured agents."""
|
demo/src/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (274 Bytes). View file
|
|
|
demo/src/__pycache__/baseline.cpython-312.pyc
ADDED
|
Binary file (12.7 kB). View file
|
|
|
demo/src/__pycache__/budget_guard.cpython-312.pyc
ADDED
|
Binary file (890 Bytes). View file
|
|
|
demo/src/__pycache__/domain.cpython-312.pyc
ADDED
|
Binary file (14.5 kB). View file
|
|
|
demo/src/__pycache__/explain.cpython-312.pyc
ADDED
|
Binary file (6.48 kB). View file
|
|
|
demo/src/__pycache__/extractor.cpython-312.pyc
ADDED
|
Binary file (11.9 kB). View file
|
|
|
demo/src/__pycache__/generator.cpython-312.pyc
ADDED
|
Binary file (29.6 kB). View file
|
|
|
demo/src/__pycache__/i18n.cpython-312.pyc
ADDED
|
Binary file (9.01 kB). View file
|
|
|
demo/src/__pycache__/metrics.cpython-312.pyc
ADDED
|
Binary file (11.5 kB). View file
|
|
|
demo/src/__pycache__/model_registry.cpython-312.pyc
ADDED
|
Binary file (3.23 kB). View file
|
|
|
demo/src/__pycache__/optimizer.cpython-312.pyc
ADDED
|
Binary file (19.8 kB). View file
|
|
|
demo/src/__pycache__/pipeline.cpython-312.pyc
ADDED
|
Binary file (16.7 kB). View file
|
|
|
demo/src/__pycache__/plots.cpython-312.pyc
ADDED
|
Binary file (8.83 kB). View file
|
|
|
demo/src/__pycache__/validation.cpython-312.pyc
ADDED
|
Binary file (19.3 kB). View file
|
|
|
demo/src/baseline.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
from src.domain import (
|
| 7 |
+
AssignmentInstance,
|
| 8 |
+
AssignmentRow,
|
| 9 |
+
Family,
|
| 10 |
+
InventoryInstance,
|
| 11 |
+
InventoryOrder,
|
| 12 |
+
ScheduleInstance,
|
| 13 |
+
ScheduleStart,
|
| 14 |
+
Solution,
|
| 15 |
+
SolveStatus,
|
| 16 |
+
parse_instance,
|
| 17 |
+
)
|
| 18 |
+
from src.optimizer import SolverOutcome
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _round_pack(qty: int, pack: int) -> int:
|
| 22 |
+
if qty <= 0:
|
| 23 |
+
return 0
|
| 24 |
+
return int(math.ceil(qty / pack) * pack)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def heuristic_inventory(instance: InventoryInstance) -> Solution:
|
| 28 |
+
remaining = int(instance.budget)
|
| 29 |
+
orders: list[InventoryOrder] = []
|
| 30 |
+
stock = {sku.sku_id: int(sku.initial_stock) for sku in instance.skus}
|
| 31 |
+
for t in range(1, instance.periods + 1):
|
| 32 |
+
for sku in sorted(instance.skus, key=lambda item: (-item.shortage_cost, item.sku_id)):
|
| 33 |
+
need = max(0, int(sku.demand[t - 1]) - stock[sku.sku_id])
|
| 34 |
+
qty = _round_pack(need, sku.pack_size)
|
| 35 |
+
cost = qty * sku.unit_cost
|
| 36 |
+
while qty and cost > remaining:
|
| 37 |
+
qty = max(0, qty - sku.pack_size)
|
| 38 |
+
cost = qty * sku.unit_cost
|
| 39 |
+
projected = sum(max(0, stock[other.sku_id] - (int(other.demand[t - 1]) if other.sku_id != sku.sku_id else 0)) for other in instance.skus)
|
| 40 |
+
projected += max(0, stock[sku.sku_id] + qty - int(sku.demand[t - 1]))
|
| 41 |
+
if projected > instance.warehouse_capacity:
|
| 42 |
+
qty = 0
|
| 43 |
+
cost = 0
|
| 44 |
+
remaining -= cost
|
| 45 |
+
orders.append(InventoryOrder(sku_id=sku.sku_id, period=t, qty=qty))
|
| 46 |
+
sold = min(stock[sku.sku_id] + qty, int(sku.demand[t - 1]))
|
| 47 |
+
stock[sku.sku_id] = stock[sku.sku_id] + qty - sold
|
| 48 |
+
return Solution(family=Family.INVENTORY, status=SolveStatus.HEURISTIC, orders=orders, message="lot-for-lot pack-rounded")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def heuristic_assignment(instance: AssignmentInstance) -> Solution:
|
| 52 |
+
costs = instance.cost_map()
|
| 53 |
+
remaining = {agent.agent_id: agent.capacity for agent in instance.agents}
|
| 54 |
+
used: set[str] = set()
|
| 55 |
+
rows: list[AssignmentRow] = []
|
| 56 |
+
leftover: list[str] = []
|
| 57 |
+
ordered = sorted(instance.tasks, key=lambda task: (not task.required, -task.penalty, task.task_id))
|
| 58 |
+
for task in ordered:
|
| 59 |
+
candidates = []
|
| 60 |
+
for agent in instance.agents:
|
| 61 |
+
if not instance.eligible(task, agent):
|
| 62 |
+
continue
|
| 63 |
+
if remaining[agent.agent_id] < task.size:
|
| 64 |
+
continue
|
| 65 |
+
pair = (task.task_id, agent.agent_id)
|
| 66 |
+
if pair not in costs:
|
| 67 |
+
continue
|
| 68 |
+
candidates.append((costs[pair], agent.agent_id))
|
| 69 |
+
if not candidates:
|
| 70 |
+
leftover.append(task.task_id)
|
| 71 |
+
continue
|
| 72 |
+
candidates.sort()
|
| 73 |
+
agent_id = candidates[0][1]
|
| 74 |
+
rows.append(AssignmentRow(task_id=task.task_id, agent_id=agent_id))
|
| 75 |
+
remaining[agent_id] -= task.size
|
| 76 |
+
used.add(task.task_id)
|
| 77 |
+
leftover.extend(task.task_id for task in instance.tasks if task.task_id not in used and task.task_id not in leftover)
|
| 78 |
+
return Solution(
|
| 79 |
+
family=Family.ASSIGNMENT,
|
| 80 |
+
status=SolveStatus.HEURISTIC,
|
| 81 |
+
assignments=rows,
|
| 82 |
+
unassigned=leftover,
|
| 83 |
+
message="cheapest eligible agent with remaining capacity",
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def heuristic_scheduling(instance: ScheduleInstance) -> Solution:
|
| 88 |
+
ready = {machine: 0 for machine in instance.machines}
|
| 89 |
+
done_end: dict[str, int] = {}
|
| 90 |
+
remaining = {job.job_id: job for job in instance.jobs}
|
| 91 |
+
starts: list[ScheduleStart] = []
|
| 92 |
+
preds: dict[str, list[str]] = {job.job_id: [] for job in instance.jobs}
|
| 93 |
+
for edge in instance.precedences:
|
| 94 |
+
if edge.after in preds:
|
| 95 |
+
preds[edge.after].append(edge.before)
|
| 96 |
+
|
| 97 |
+
guard = 0
|
| 98 |
+
while remaining and guard < 200:
|
| 99 |
+
guard += 1
|
| 100 |
+
ready_jobs = [
|
| 101 |
+
job
|
| 102 |
+
for job in remaining.values()
|
| 103 |
+
if all(pred in done_end for pred in preds[job.job_id])
|
| 104 |
+
]
|
| 105 |
+
if not ready_jobs:
|
| 106 |
+
break
|
| 107 |
+
ready_jobs.sort(key=lambda job: (job.due, -job.weight, job.job_id))
|
| 108 |
+
job = ready_jobs[0]
|
| 109 |
+
eligible = [machine for machine in instance.machines if machine in set(job.machine_eligible)] or list(instance.machines)
|
| 110 |
+
pred_end = max((done_end[pred] for pred in preds[job.job_id]), default=0)
|
| 111 |
+
machine = min(eligible, key=lambda item: (max(ready[item], job.release, pred_end), item))
|
| 112 |
+
start = max(ready[machine], job.release, pred_end)
|
| 113 |
+
end = start + job.duration
|
| 114 |
+
starts.append(ScheduleStart(job_id=job.job_id, machine_id=machine, start=start, end=end))
|
| 115 |
+
ready[machine] = end
|
| 116 |
+
done_end[job.job_id] = end
|
| 117 |
+
remaining.pop(job.job_id)
|
| 118 |
+
leftover = [job_id for job_id in remaining]
|
| 119 |
+
message = "earliest due date on the earliest eligible machine"
|
| 120 |
+
if leftover:
|
| 121 |
+
message += f"; leftover {leftover}"
|
| 122 |
+
return Solution(family=Family.SCHEDULING, status=SolveStatus.HEURISTIC, starts=starts, message=message)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def naive_direct(family: Family | str, payload: dict) -> Solution:
|
| 126 |
+
family = Family(family)
|
| 127 |
+
instance = parse_instance(family, payload)
|
| 128 |
+
if family == Family.INVENTORY:
|
| 129 |
+
orders = []
|
| 130 |
+
for sku in instance.skus:
|
| 131 |
+
for t, demand in enumerate(sku.demand, start=1):
|
| 132 |
+
orders.append(InventoryOrder(sku_id=sku.sku_id, period=t, qty=int(demand)))
|
| 133 |
+
return Solution(
|
| 134 |
+
family=family,
|
| 135 |
+
status=SolveStatus.HEURISTIC,
|
| 136 |
+
orders=orders,
|
| 137 |
+
message="naive-direct: order raw demand, ignore pack/budget/capacity",
|
| 138 |
+
)
|
| 139 |
+
if family == Family.ASSIGNMENT:
|
| 140 |
+
if not instance.agents:
|
| 141 |
+
return Solution(family=family, status=SolveStatus.HEURISTIC, message="naive-direct: no agents")
|
| 142 |
+
first = instance.agents[0].agent_id
|
| 143 |
+
rows = [AssignmentRow(task_id=task.task_id, agent_id=first) for task in instance.tasks]
|
| 144 |
+
return Solution(
|
| 145 |
+
family=family,
|
| 146 |
+
status=SolveStatus.HEURISTIC,
|
| 147 |
+
assignments=rows,
|
| 148 |
+
message="naive-direct: assign every task to the first agent",
|
| 149 |
+
)
|
| 150 |
+
starts = []
|
| 151 |
+
cursor = 0
|
| 152 |
+
machine = instance.machines[0] if instance.machines else "M1"
|
| 153 |
+
for job in instance.jobs:
|
| 154 |
+
start = max(cursor, job.release)
|
| 155 |
+
starts.append(ScheduleStart(job_id=job.job_id, machine_id=machine, start=start, end=start + job.duration))
|
| 156 |
+
cursor = start + job.duration
|
| 157 |
+
return Solution(
|
| 158 |
+
family=family,
|
| 159 |
+
status=SolveStatus.HEURISTIC,
|
| 160 |
+
starts=starts,
|
| 161 |
+
message="naive-direct: single-machine FCFS ignoring eligibility and hard dues",
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def run_heuristic(family: Family | str, payload: dict) -> SolverOutcome:
|
| 166 |
+
started = time.perf_counter()
|
| 167 |
+
family = Family(family)
|
| 168 |
+
instance = parse_instance(family, payload)
|
| 169 |
+
if family == Family.INVENTORY:
|
| 170 |
+
solution = heuristic_inventory(instance)
|
| 171 |
+
elif family == Family.ASSIGNMENT:
|
| 172 |
+
solution = heuristic_assignment(instance)
|
| 173 |
+
else:
|
| 174 |
+
solution = heuristic_scheduling(instance)
|
| 175 |
+
return SolverOutcome(solution, time.perf_counter() - started, "heuristic-v1", solution.message)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def run_naive(family: Family | str, payload: dict) -> SolverOutcome:
|
| 179 |
+
started = time.perf_counter()
|
| 180 |
+
solution = naive_direct(family, payload)
|
| 181 |
+
return SolverOutcome(solution, time.perf_counter() - started, "naive-direct-v1", solution.message)
|
demo/src/budget_guard.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# Paid provider calls stay off unless a future release adds an atomic shared budget.
|
| 6 |
+
PAID_INFERENCE_ENABLED = False
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def paid_inference_allowed() -> bool:
|
| 10 |
+
if not PAID_INFERENCE_ENABLED:
|
| 11 |
+
return False
|
| 12 |
+
if os.environ.get("ORBENCH_ALLOW_PAID") != "1":
|
| 13 |
+
return False
|
| 14 |
+
return False
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def skip_reason() -> str:
|
| 18 |
+
return (
|
| 19 |
+
"Live LLM APIs are disabled. Comparison cells for unnamed or unpaid "
|
| 20 |
+
"model runs stay not_evaluated. The free path is the CPU solver, "
|
| 21 |
+
"heuristics, and deterministic extractors."
|
| 22 |
+
)
|
demo/src/domain.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from enum import Enum
|
| 4 |
+
from typing import Any, Literal
|
| 5 |
+
|
| 6 |
+
from pydantic import BaseModel, Field
|
| 7 |
+
|
| 8 |
+
CODE_NAME = "or-bench"
|
| 9 |
+
CODE_VERSION = "0.1.0"
|
| 10 |
+
DEFAULT_SEED = 25
|
| 11 |
+
DEFAULT_SOLVER_SECONDS = 8.0
|
| 12 |
+
DEFAULT_THREADS = 1
|
| 13 |
+
MAX_UPLOAD_MB = 10
|
| 14 |
+
N_PROBLEMS = 100
|
| 15 |
+
N_INVENTORY = 34
|
| 16 |
+
N_ASSIGNMENT = 33
|
| 17 |
+
N_SCHEDULING = 33
|
| 18 |
+
N_INTERACTIVE = 20
|
| 19 |
+
N_DEVELOPMENT = 60
|
| 20 |
+
|
| 21 |
+
SOLVER_NAME = "ortools-cpsat"
|
| 22 |
+
PROTOCOL_ID = "or-bench-v1"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Family(str, Enum):
|
| 26 |
+
INVENTORY = "inventory"
|
| 27 |
+
ASSIGNMENT = "assignment"
|
| 28 |
+
SCHEDULING = "scheduling"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Split(str, Enum):
|
| 32 |
+
DEVELOPMENT = "development"
|
| 33 |
+
TEST = "test"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Difficulty(str, Enum):
|
| 37 |
+
EASY = "easy"
|
| 38 |
+
MEDIUM = "medium"
|
| 39 |
+
HARD = "hard"
|
| 40 |
+
INFEASIBLE = "infeasible"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class SolveStatus(str, Enum):
|
| 44 |
+
OPTIMAL = "optimal"
|
| 45 |
+
FEASIBLE = "feasible"
|
| 46 |
+
HEURISTIC = "heuristic"
|
| 47 |
+
INFEASIBLE = "infeasible"
|
| 48 |
+
TIMEOUT = "timeout"
|
| 49 |
+
INVALID = "invalid"
|
| 50 |
+
ERROR = "error"
|
| 51 |
+
NOT_EVALUATED = "not_evaluated"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class MethodKind(str, Enum):
|
| 55 |
+
STRUCTURED_SOLVER = "structured-solver"
|
| 56 |
+
HEURISTIC = "heuristic"
|
| 57 |
+
TEXT_TO_SCHEMA = "text-to-schema"
|
| 58 |
+
DIRECT_ANSWER = "direct-answer"
|
| 59 |
+
LLM_SCHEMA = "llm-schema"
|
| 60 |
+
LLM_DIRECT = "llm-direct"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class PromptVariant(str, Enum):
|
| 64 |
+
TEMPLATE = "template"
|
| 65 |
+
JSON = "json"
|
| 66 |
+
MISSING_BUDGET = "missing_constraint"
|
| 67 |
+
CUSTOM = "custom"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class InventorySku(BaseModel):
|
| 71 |
+
sku_id: str
|
| 72 |
+
name: str
|
| 73 |
+
demand: list[int]
|
| 74 |
+
initial_stock: int = Field(ge=0)
|
| 75 |
+
unit_cost: int = Field(ge=1)
|
| 76 |
+
holding_cost: int = Field(ge=0)
|
| 77 |
+
shortage_cost: int = Field(ge=0)
|
| 78 |
+
pack_size: int = Field(ge=1)
|
| 79 |
+
lead_time: int = Field(default=0, ge=0, le=0)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class InventoryInstance(BaseModel):
|
| 83 |
+
periods: int = Field(ge=2, le=6)
|
| 84 |
+
budget: int = Field(ge=0)
|
| 85 |
+
warehouse_capacity: int = Field(ge=0)
|
| 86 |
+
cover_required: bool = False
|
| 87 |
+
lost_sales: bool = True
|
| 88 |
+
skus: list[InventorySku]
|
| 89 |
+
|
| 90 |
+
def sku_map(self) -> dict[str, InventorySku]:
|
| 91 |
+
return {item.sku_id: item for item in self.skus}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class AssignmentTask(BaseModel):
|
| 95 |
+
task_id: str
|
| 96 |
+
name: str
|
| 97 |
+
size: int = Field(ge=1)
|
| 98 |
+
required: bool = True
|
| 99 |
+
skills: list[str]
|
| 100 |
+
penalty: int = Field(ge=0)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class AssignmentAgent(BaseModel):
|
| 104 |
+
agent_id: str
|
| 105 |
+
name: str
|
| 106 |
+
capacity: int = Field(ge=0)
|
| 107 |
+
skills: list[str]
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class AssignmentCost(BaseModel):
|
| 111 |
+
task_id: str
|
| 112 |
+
agent_id: str
|
| 113 |
+
cost: int = Field(ge=0)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class AssignmentInstance(BaseModel):
|
| 117 |
+
tasks: list[AssignmentTask]
|
| 118 |
+
agents: list[AssignmentAgent]
|
| 119 |
+
costs: list[AssignmentCost]
|
| 120 |
+
|
| 121 |
+
def cost_map(self) -> dict[tuple[str, str], int]:
|
| 122 |
+
return {(row.task_id, row.agent_id): row.cost for row in self.costs}
|
| 123 |
+
|
| 124 |
+
def eligible(self, task: AssignmentTask, agent: AssignmentAgent) -> bool:
|
| 125 |
+
return bool(set(task.skills) & set(agent.skills)) or not task.skills
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class ScheduleJob(BaseModel):
|
| 129 |
+
job_id: str
|
| 130 |
+
name: str
|
| 131 |
+
duration: int = Field(ge=1)
|
| 132 |
+
release: int = Field(ge=0)
|
| 133 |
+
due: int = Field(ge=0)
|
| 134 |
+
weight: int = Field(ge=1)
|
| 135 |
+
hard_due: bool = False
|
| 136 |
+
machine_eligible: list[str]
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class SchedulePrecedence(BaseModel):
|
| 140 |
+
before: str
|
| 141 |
+
after: str
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class ScheduleInstance(BaseModel):
|
| 145 |
+
machines: list[str]
|
| 146 |
+
jobs: list[ScheduleJob]
|
| 147 |
+
precedences: list[SchedulePrecedence]
|
| 148 |
+
horizon: int = Field(ge=1)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class InventoryOrder(BaseModel):
|
| 152 |
+
sku_id: str
|
| 153 |
+
period: int
|
| 154 |
+
qty: int
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class AssignmentRow(BaseModel):
|
| 158 |
+
task_id: str
|
| 159 |
+
agent_id: str
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class ScheduleStart(BaseModel):
|
| 163 |
+
job_id: str
|
| 164 |
+
machine_id: str
|
| 165 |
+
start: int
|
| 166 |
+
end: int
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class Solution(BaseModel):
|
| 170 |
+
family: Family
|
| 171 |
+
status: SolveStatus = SolveStatus.FEASIBLE
|
| 172 |
+
objective: float | None = None
|
| 173 |
+
bound: float | None = None
|
| 174 |
+
orders: list[InventoryOrder] = Field(default_factory=list)
|
| 175 |
+
assignments: list[AssignmentRow] = Field(default_factory=list)
|
| 176 |
+
unassigned: list[str] = Field(default_factory=list)
|
| 177 |
+
starts: list[ScheduleStart] = Field(default_factory=list)
|
| 178 |
+
message: str = ""
|
| 179 |
+
|
| 180 |
+
def as_dict(self) -> dict[str, Any]:
|
| 181 |
+
return self.model_dump(mode="json")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class ProblemRecord(BaseModel):
|
| 185 |
+
problem_id: str
|
| 186 |
+
family: Family
|
| 187 |
+
split: Split
|
| 188 |
+
interactive: bool
|
| 189 |
+
difficulty: Difficulty
|
| 190 |
+
language: Literal["en", "fa"]
|
| 191 |
+
template_id: str
|
| 192 |
+
seed: int
|
| 193 |
+
prompt_en: str
|
| 194 |
+
prompt_fa: str
|
| 195 |
+
prompt_json: str
|
| 196 |
+
schema_payload: dict[str, Any]
|
| 197 |
+
gold_status: str
|
| 198 |
+
gold_objective: float | None = None
|
| 199 |
+
gold_bound: float | None = None
|
| 200 |
+
gold_solution: dict[str, Any] = Field(default_factory=dict)
|
| 201 |
+
structural_key: str
|
| 202 |
+
notes: str = ""
|
| 203 |
+
|
| 204 |
+
def instance(self) -> InventoryInstance | AssignmentInstance | ScheduleInstance:
|
| 205 |
+
payload = self.schema_payload
|
| 206 |
+
if self.family == Family.INVENTORY:
|
| 207 |
+
return InventoryInstance.model_validate(payload)
|
| 208 |
+
if self.family == Family.ASSIGNMENT:
|
| 209 |
+
return AssignmentInstance.model_validate(payload)
|
| 210 |
+
return ScheduleInstance.model_validate(payload)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class ConstraintConfig(BaseModel):
|
| 214 |
+
solver_seconds: float = Field(default=DEFAULT_SOLVER_SECONDS, gt=1, le=30)
|
| 215 |
+
threads: int = Field(default=DEFAULT_THREADS, ge=1, le=2)
|
| 216 |
+
include_infeasible: bool = True
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class ValidationIssue(BaseModel):
|
| 220 |
+
code: str
|
| 221 |
+
message: str
|
| 222 |
+
entity_id: str | None = None
|
| 223 |
+
passed: bool = False
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
class ValidationReport(BaseModel):
|
| 227 |
+
ok: bool
|
| 228 |
+
issues: list[ValidationIssue]
|
| 229 |
+
checked: list[str]
|
| 230 |
+
recomputed_objective: float | None = None
|
| 231 |
+
|
| 232 |
+
def failed_codes(self) -> list[str]:
|
| 233 |
+
return [item.code for item in self.issues if not item.passed]
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class ConstraintFact(BaseModel):
|
| 237 |
+
key: str
|
| 238 |
+
value: Any
|
| 239 |
+
source: str = "schema"
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class MethodSpec(BaseModel):
|
| 243 |
+
method_id: str
|
| 244 |
+
display_name: str
|
| 245 |
+
kind: MethodKind
|
| 246 |
+
evaluated: bool
|
| 247 |
+
version: str
|
| 248 |
+
license: str = "apache-2.0"
|
| 249 |
+
cost_usd: float | None = None
|
| 250 |
+
notes: str = ""
|
| 251 |
+
reason_if_skipped: str = ""
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class EvalRow(BaseModel):
|
| 255 |
+
problem_id: str
|
| 256 |
+
method_id: str
|
| 257 |
+
method_kind: str
|
| 258 |
+
evaluated: bool
|
| 259 |
+
parse_success: bool | None = None
|
| 260 |
+
constraint_fidelity: float | None = None
|
| 261 |
+
status: str
|
| 262 |
+
feasible: bool | None = None
|
| 263 |
+
optimality_gap: float | None = None
|
| 264 |
+
objective: float | None = None
|
| 265 |
+
gold_objective: float | None = None
|
| 266 |
+
gold_status: str
|
| 267 |
+
seconds: float
|
| 268 |
+
cost_usd: float | None = None
|
| 269 |
+
violated: list[str] = Field(default_factory=list)
|
| 270 |
+
notes: str = ""
|
| 271 |
+
precomputed: bool = False
|
| 272 |
+
family: str
|
| 273 |
+
split: str
|
| 274 |
+
language: str
|
| 275 |
+
difficulty: str
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def not_evaluated_cell() -> str:
|
| 279 |
+
return "not_evaluated"
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def gap(objective: float | None, gold: float | None, gold_status: str) -> float | None:
|
| 283 |
+
if objective is None or gold is None:
|
| 284 |
+
return None
|
| 285 |
+
if gold_status != SolveStatus.OPTIMAL.value:
|
| 286 |
+
return None
|
| 287 |
+
denom = max(1.0, abs(float(gold)))
|
| 288 |
+
return max(0.0, (float(objective) - float(gold)) / denom)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def parse_instance(family: Family | str, payload: dict[str, Any]) -> InventoryInstance | AssignmentInstance | ScheduleInstance:
|
| 292 |
+
family = Family(family)
|
| 293 |
+
if family == Family.INVENTORY:
|
| 294 |
+
return InventoryInstance.model_validate(payload)
|
| 295 |
+
if family == Family.ASSIGNMENT:
|
| 296 |
+
return AssignmentInstance.model_validate(payload)
|
| 297 |
+
return ScheduleInstance.model_validate(payload)
|
demo/src/explain.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from src.domain import EvalRow, SolveStatus
|
| 4 |
+
from src.validation import ValidationReport
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def status_label(status: str, lang: str = "en") -> str:
|
| 8 |
+
mapping = {
|
| 9 |
+
"en": {
|
| 10 |
+
"optimal": "Proven optimal (within the model)",
|
| 11 |
+
"feasible": "Feasible incumbent within the time limit — not proven optimal",
|
| 12 |
+
"heuristic": "Heuristic feasible candidate — not a proven optimum",
|
| 13 |
+
"infeasible": "Proven infeasible under the stated constraints",
|
| 14 |
+
"timeout": "No plan found before the time limit — this is not a proof of infeasibility",
|
| 15 |
+
"invalid": "Invalid input or schema",
|
| 16 |
+
"error": "Solver error",
|
| 17 |
+
"not_evaluated": "Not evaluated — no run, so this is not a score of 0",
|
| 18 |
+
},
|
| 19 |
+
"fa": {
|
| 20 |
+
"optimal": "بهینه اثباتشده در مدل",
|
| 21 |
+
"feasible": "جواب شدنی در مهلت — بهینه بودن اثبات نشده",
|
| 22 |
+
"heuristic": "نامزد شدنی ابتکاری — بهینه اثباتشده نیست",
|
| 23 |
+
"infeasible": "ناممکن اثباتشده با قیود فعلی",
|
| 24 |
+
"timeout": "در مهلت جوابی پیدا نشد — این اثبات ناممکن بودن نیست",
|
| 25 |
+
"invalid": "ورودی یا schema نامعتبر",
|
| 26 |
+
"error": "خطای حلگر",
|
| 27 |
+
"not_evaluated": "ارزیابی نشده — اجرا نشده و این صفر یا رتبه نیست",
|
| 28 |
+
},
|
| 29 |
+
}
|
| 30 |
+
return mapping.get(lang, mapping["en"]).get(status, status)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def numeric_reasons(problem, rows: list[EvalRow], report: ValidationReport | None, lang: str = "en") -> list[str]:
|
| 34 |
+
lines: list[str] = []
|
| 35 |
+
if lang == "fa":
|
| 36 |
+
lines.append(
|
| 37 |
+
f"{problem.problem_id} خانواده {problem.family.value}، دشواری {problem.difficulty.value}، "
|
| 38 |
+
f"وضعیت طلایی {problem.gold_status}، هدف طلایی {problem.gold_objective}."
|
| 39 |
+
)
|
| 40 |
+
else:
|
| 41 |
+
lines.append(
|
| 42 |
+
f"{problem.problem_id} is a {problem.difficulty.value} {problem.family.value} instance. "
|
| 43 |
+
f"Gold status {problem.gold_status}, gold objective {problem.gold_objective}."
|
| 44 |
+
)
|
| 45 |
+
by_id = {row.method_id: row for row in rows if row.evaluated}
|
| 46 |
+
structured = by_id.get("structured-solver")
|
| 47 |
+
heuristic = by_id.get("heuristic")
|
| 48 |
+
if structured and heuristic and structured.objective is not None and heuristic.objective is not None:
|
| 49 |
+
delta = float(heuristic.objective) - float(structured.objective)
|
| 50 |
+
if lang == "fa":
|
| 51 |
+
lines.append(f"هدف ابتکاری {heuristic.objective} در برابر حلگر {structured.objective} (اختلاف {delta:+.3f}).")
|
| 52 |
+
else:
|
| 53 |
+
lines.append(f"Heuristic objective {heuristic.objective} vs solver {structured.objective} (delta {delta:+.3f}).")
|
| 54 |
+
extractor = by_id.get("template-extractor+solver")
|
| 55 |
+
if extractor and extractor.constraint_fidelity is not None:
|
| 56 |
+
if lang == "fa":
|
| 57 |
+
lines.append(f"وفاداری استخراج قالب {extractor.constraint_fidelity:.3f}؛ parse={'موفق' if extractor.parse_success else 'ناموفق'}.")
|
| 58 |
+
else:
|
| 59 |
+
lines.append(f"Template-extractor fidelity {extractor.constraint_fidelity:.3f}; parse={'ok' if extractor.parse_success else 'failed'}.")
|
| 60 |
+
naive = by_id.get("naive-direct")
|
| 61 |
+
if naive and naive.violated:
|
| 62 |
+
if lang == "fa":
|
| 63 |
+
lines.append(f"پاسخ مستقیم سادهلوح قیود را نقض کرد: {', '.join(naive.violated[:6])}.")
|
| 64 |
+
else:
|
| 65 |
+
lines.append(f"Naive direct answer violated: {', '.join(naive.violated[:6])}.")
|
| 66 |
+
if report and not report.ok:
|
| 67 |
+
codes = ", ".join(report.failed_codes()[:6])
|
| 68 |
+
if lang == "fa":
|
| 69 |
+
lines.append(f"validator مستقل قیود نقضشده را گزارش کرد: {codes}.")
|
| 70 |
+
else:
|
| 71 |
+
lines.append(f"Independent validator flagged: {codes}.")
|
| 72 |
+
if problem.gold_status == SolveStatus.INFEASIBLE.value:
|
| 73 |
+
if lang == "fa":
|
| 74 |
+
lines.append("این نمونه ناممکن طراحی شده است. خانههای مدل اجرانشده «ارزیابی نشده» میمانند.")
|
| 75 |
+
else:
|
| 76 |
+
lines.append("This instance is designed to be infeasible. Unevaluated model cells stay not_evaluated.")
|
| 77 |
+
if lang == "fa":
|
| 78 |
+
lines.append("امتیاز یک مدل زبانی داور نیست؛ validator عددی مرجع است. مسیر پاسخ مستقیم فقط برای بنچمارک است.")
|
| 79 |
+
else:
|
| 80 |
+
lines.append("An LLM score is not the judge. The numeric validator is the reference. Direct answers are benchmark-only.")
|
| 81 |
+
return lines[:8]
|
demo/src/extractor.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from src.domain import Family, InventoryInstance
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def extract_json(text: str) -> dict[str, Any] | None:
|
| 11 |
+
if not text or not str(text).strip():
|
| 12 |
+
return None
|
| 13 |
+
raw = str(text).strip()
|
| 14 |
+
candidates = [raw]
|
| 15 |
+
fenced = re.findall(r"```(?:json)?\s*(\{.*?\})\s*```", raw, flags=re.S)
|
| 16 |
+
candidates.extend(fenced)
|
| 17 |
+
start = raw.find("{")
|
| 18 |
+
end = raw.rfind("}")
|
| 19 |
+
if start >= 0 and end > start:
|
| 20 |
+
candidates.append(raw[start : end + 1])
|
| 21 |
+
for item in candidates:
|
| 22 |
+
try:
|
| 23 |
+
payload = json.loads(item)
|
| 24 |
+
except json.JSONDecodeError:
|
| 25 |
+
continue
|
| 26 |
+
if isinstance(payload, dict) and payload:
|
| 27 |
+
if "schema_payload" in payload and isinstance(payload["schema_payload"], dict):
|
| 28 |
+
return payload["schema_payload"]
|
| 29 |
+
return payload
|
| 30 |
+
return None
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def extract_template(text: str, family: Family | str) -> dict[str, Any] | None:
|
| 34 |
+
family = Family(family)
|
| 35 |
+
if not text:
|
| 36 |
+
return None
|
| 37 |
+
labeled = _extract_labeled_blocks(text)
|
| 38 |
+
if labeled:
|
| 39 |
+
return labeled
|
| 40 |
+
if family == Family.INVENTORY:
|
| 41 |
+
return _extract_inventory_prose(text)
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _extract_labeled_blocks(text: str) -> dict[str, Any] | None:
|
| 46 |
+
blocks = re.findall(r"SCHEMA_BEGIN\s*(\{.*?\})\s*SCHEMA_END", text, flags=re.S)
|
| 47 |
+
for block in blocks:
|
| 48 |
+
try:
|
| 49 |
+
payload = json.loads(block)
|
| 50 |
+
except json.JSONDecodeError:
|
| 51 |
+
continue
|
| 52 |
+
if isinstance(payload, dict):
|
| 53 |
+
return payload
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _extract_inventory_prose(text: str) -> dict[str, Any] | None:
|
| 58 |
+
budget = _first_int(text, r"(?:BUDGET|budget|بودجه)\s*[:=]?\s*(\d+)")
|
| 59 |
+
capacity = _first_int(text, r"(?:CAPACITY|capacity|ظرفیت انبار)\s*[:=]?\s*(\d+)")
|
| 60 |
+
periods = _first_int(text, r"(?:PERIODS|periods|دوره)\s*[:=]?\s*(\d+)")
|
| 61 |
+
cover = bool(re.search(r"COVER_REQUIRED:\s*1|cover is required|پوشش کامل الزامی", text, flags=re.I))
|
| 62 |
+
sku_lines = re.findall(
|
| 63 |
+
r"SKU\s+([A-Za-z0-9_-]+).*?demand=([0-9,]+).*?pack=(\d+).*?cost=(\d+).*?hold=(\d+).*?short=(\d+).*?stock=(\d+)",
|
| 64 |
+
text,
|
| 65 |
+
flags=re.I,
|
| 66 |
+
)
|
| 67 |
+
if budget is None or not sku_lines:
|
| 68 |
+
return None
|
| 69 |
+
skus = []
|
| 70 |
+
for sku_id, demand, pack, cost, hold, short, stock in sku_lines:
|
| 71 |
+
values = [int(item) for item in demand.split(",") if item.strip().isdigit()]
|
| 72 |
+
skus.append(
|
| 73 |
+
{
|
| 74 |
+
"sku_id": sku_id,
|
| 75 |
+
"name": sku_id,
|
| 76 |
+
"demand": values,
|
| 77 |
+
"initial_stock": int(stock),
|
| 78 |
+
"unit_cost": int(cost),
|
| 79 |
+
"holding_cost": int(hold),
|
| 80 |
+
"shortage_cost": int(short),
|
| 81 |
+
"pack_size": int(pack),
|
| 82 |
+
"lead_time": 0,
|
| 83 |
+
}
|
| 84 |
+
)
|
| 85 |
+
periods = periods or (len(skus[0]["demand"]) if skus else 0)
|
| 86 |
+
try:
|
| 87 |
+
InventoryInstance.model_validate(
|
| 88 |
+
{
|
| 89 |
+
"periods": periods,
|
| 90 |
+
"budget": budget,
|
| 91 |
+
"warehouse_capacity": capacity if capacity is not None else 10**6,
|
| 92 |
+
"cover_required": cover,
|
| 93 |
+
"lost_sales": True,
|
| 94 |
+
"skus": skus,
|
| 95 |
+
}
|
| 96 |
+
)
|
| 97 |
+
except Exception:
|
| 98 |
+
return None
|
| 99 |
+
return {
|
| 100 |
+
"periods": periods,
|
| 101 |
+
"budget": budget,
|
| 102 |
+
"warehouse_capacity": capacity if capacity is not None else 10**6,
|
| 103 |
+
"cover_required": cover,
|
| 104 |
+
"lost_sales": True,
|
| 105 |
+
"skus": skus,
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _first_int(text: str, pattern: str) -> int | None:
|
| 110 |
+
match = re.search(pattern, text, flags=re.I)
|
| 111 |
+
if not match:
|
| 112 |
+
return None
|
| 113 |
+
return int(match.group(1))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def flatten_facts(family: Family | str, payload: dict) -> dict[str, str]:
|
| 117 |
+
family = Family(family)
|
| 118 |
+
facts: dict[str, str] = {}
|
| 119 |
+
if family == Family.INVENTORY:
|
| 120 |
+
facts["periods"] = str(payload.get("periods"))
|
| 121 |
+
facts["budget"] = str(payload.get("budget"))
|
| 122 |
+
facts["warehouse_capacity"] = str(payload.get("warehouse_capacity"))
|
| 123 |
+
facts["cover_required"] = str(bool(payload.get("cover_required")))
|
| 124 |
+
for sku in payload.get("skus") or []:
|
| 125 |
+
key = sku.get("sku_id")
|
| 126 |
+
facts[f"{key}.demand"] = ",".join(str(int(v)) for v in sku.get("demand") or [])
|
| 127 |
+
facts[f"{key}.pack"] = str(sku.get("pack_size"))
|
| 128 |
+
facts[f"{key}.cost"] = str(sku.get("unit_cost"))
|
| 129 |
+
facts[f"{key}.stock"] = str(sku.get("initial_stock"))
|
| 130 |
+
facts[f"{key}.hold"] = str(sku.get("holding_cost"))
|
| 131 |
+
facts[f"{key}.short"] = str(sku.get("shortage_cost"))
|
| 132 |
+
elif family == Family.ASSIGNMENT:
|
| 133 |
+
facts["n_tasks"] = str(len(payload.get("tasks") or []))
|
| 134 |
+
facts["n_agents"] = str(len(payload.get("agents") or []))
|
| 135 |
+
for task in payload.get("tasks") or []:
|
| 136 |
+
facts[f"task.{task.get('task_id')}.size"] = str(task.get("size"))
|
| 137 |
+
facts[f"task.{task.get('task_id')}.required"] = str(bool(task.get("required")))
|
| 138 |
+
facts[f"task.{task.get('task_id')}.skills"] = ",".join(sorted(task.get("skills") or []))
|
| 139 |
+
for agent in payload.get("agents") or []:
|
| 140 |
+
facts[f"agent.{agent.get('agent_id')}.cap"] = str(agent.get("capacity"))
|
| 141 |
+
facts[f"agent.{agent.get('agent_id')}.skills"] = ",".join(sorted(agent.get("skills") or []))
|
| 142 |
+
for row in payload.get("costs") or []:
|
| 143 |
+
facts[f"cost.{row.get('task_id')}.{row.get('agent_id')}"] = str(row.get("cost"))
|
| 144 |
+
else:
|
| 145 |
+
facts["machines"] = ",".join(payload.get("machines") or [])
|
| 146 |
+
for job in payload.get("jobs") or []:
|
| 147 |
+
jid = job.get("job_id")
|
| 148 |
+
facts[f"job.{jid}.dur"] = str(job.get("duration"))
|
| 149 |
+
facts[f"job.{jid}.rel"] = str(job.get("release"))
|
| 150 |
+
facts[f"job.{jid}.due"] = str(job.get("due"))
|
| 151 |
+
facts[f"job.{jid}.w"] = str(job.get("weight"))
|
| 152 |
+
facts[f"job.{jid}.hard"] = str(bool(job.get("hard_due")))
|
| 153 |
+
facts[f"job.{jid}.m"] = ",".join(sorted(job.get("machine_eligible") or []))
|
| 154 |
+
for idx, edge in enumerate(payload.get("precedences") or []):
|
| 155 |
+
facts[f"pred.{idx}"] = f"{edge.get('before')}->{edge.get('after')}"
|
| 156 |
+
return facts
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def constraint_fidelity(family: Family | str, gold: dict, extracted: dict | None) -> float | None:
|
| 160 |
+
if extracted is None:
|
| 161 |
+
return 0.0
|
| 162 |
+
gold_facts = flatten_facts(family, gold)
|
| 163 |
+
got = flatten_facts(family, extracted)
|
| 164 |
+
if not gold_facts:
|
| 165 |
+
return 1.0
|
| 166 |
+
hits = sum(1 for key, value in gold_facts.items() if got.get(key) == value)
|
| 167 |
+
return hits / len(gold_facts)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def drop_constraint(family: Family | str, payload: dict, prompt: str) -> tuple[dict, str]:
|
| 171 |
+
family = Family(family)
|
| 172 |
+
clone = json.loads(json.dumps(payload))
|
| 173 |
+
if family == Family.INVENTORY:
|
| 174 |
+
clone["budget"] = 10**9
|
| 175 |
+
stripped = re.sub(r"(BUDGET|budget|بودجه)\s*[:=]?\s*\d+", "BUDGET omitted", prompt)
|
| 176 |
+
return clone, stripped
|
| 177 |
+
if family == Family.ASSIGNMENT:
|
| 178 |
+
for agent in clone.get("agents") or []:
|
| 179 |
+
agent["capacity"] = 10**6
|
| 180 |
+
stripped = re.sub(r"(capacity|ظرفیت)\s*[:=]?\s*\d+", "capacity omitted", prompt, flags=re.I)
|
| 181 |
+
return clone, stripped
|
| 182 |
+
for job in clone.get("jobs") or []:
|
| 183 |
+
job["hard_due"] = False
|
| 184 |
+
job["due"] = job.get("due", 0) + 10**4
|
| 185 |
+
stripped = re.sub(r"(hard due|موعد سخت)", "due relaxed", prompt, flags=re.I)
|
| 186 |
+
return clone, stripped
|
demo/src/generator.py
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import random
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from src.domain import (
|
| 9 |
+
DEFAULT_SEED,
|
| 10 |
+
N_ASSIGNMENT,
|
| 11 |
+
N_INVENTORY,
|
| 12 |
+
N_PROBLEMS,
|
| 13 |
+
N_SCHEDULING,
|
| 14 |
+
AssignmentAgent,
|
| 15 |
+
AssignmentCost,
|
| 16 |
+
AssignmentInstance,
|
| 17 |
+
AssignmentTask,
|
| 18 |
+
Difficulty,
|
| 19 |
+
Family,
|
| 20 |
+
InventoryInstance,
|
| 21 |
+
InventorySku,
|
| 22 |
+
ProblemRecord,
|
| 23 |
+
ScheduleInstance,
|
| 24 |
+
ScheduleJob,
|
| 25 |
+
SchedulePrecedence,
|
| 26 |
+
Split,
|
| 27 |
+
)
|
| 28 |
+
from src.optimizer import solve_instance
|
| 29 |
+
|
| 30 |
+
DEV_TEMPLATES = ("D-A", "D-B", "D-C")
|
| 31 |
+
TEST_TEMPLATES = ("T-A", "T-B")
|
| 32 |
+
SKU_NAMES = ("bearing", "seal", "gasket", "filter", "hose", "valve")
|
| 33 |
+
SKU_FA = ("بلبرینگ", "آببند", "واشر", "فیلتر", "شیلنگ", "شیر")
|
| 34 |
+
TASK_SKILLS = ("weld", "inspect", "pack", "lift")
|
| 35 |
+
INTERACTIVE_IDS = (
|
| 36 |
+
"INV-001",
|
| 37 |
+
"INV-008",
|
| 38 |
+
"INV-014",
|
| 39 |
+
"INV-021",
|
| 40 |
+
"INV-028",
|
| 41 |
+
"INV-031",
|
| 42 |
+
"INV-034",
|
| 43 |
+
"ASN-001",
|
| 44 |
+
"ASN-006",
|
| 45 |
+
"ASN-012",
|
| 46 |
+
"ASN-018",
|
| 47 |
+
"ASN-024",
|
| 48 |
+
"ASN-029",
|
| 49 |
+
"ASN-033",
|
| 50 |
+
"SCH-001",
|
| 51 |
+
"SCH-007",
|
| 52 |
+
"SCH-013",
|
| 53 |
+
"SCH-019",
|
| 54 |
+
"SCH-027",
|
| 55 |
+
"SCH-033",
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _split_for(index: int, n_items: int) -> Split:
|
| 60 |
+
# First 20 of each family → 60 development / 40 test overall.
|
| 61 |
+
_ = n_items
|
| 62 |
+
return Split.DEVELOPMENT if index <= 20 else Split.TEST
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _difficulty(index: int, n_items: int, infeasible_tail: int) -> Difficulty:
|
| 66 |
+
if index > n_items - infeasible_tail:
|
| 67 |
+
return Difficulty.INFEASIBLE
|
| 68 |
+
if index % 7 == 0:
|
| 69 |
+
return Difficulty.HARD
|
| 70 |
+
if index % 3 == 0:
|
| 71 |
+
return Difficulty.MEDIUM
|
| 72 |
+
return Difficulty.EASY
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _template(split: Split, index: int) -> str:
|
| 76 |
+
pool = DEV_TEMPLATES if split == Split.DEVELOPMENT else TEST_TEMPLATES
|
| 77 |
+
return pool[(index - 1) % len(pool)]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _key(*parts: object) -> str:
|
| 81 |
+
raw = "|".join(str(item) for item in parts)
|
| 82 |
+
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _wrap_schema(payload: dict, template_id: str) -> str:
|
| 86 |
+
if template_id.startswith("D-"):
|
| 87 |
+
return "SCHEMA_BEGIN\n" + json.dumps(payload, ensure_ascii=False) + "\nSCHEMA_END\n"
|
| 88 |
+
return ""
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _json_prompt(payload: dict) -> str:
|
| 92 |
+
return json.dumps(payload, ensure_ascii=False, indent=2)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def make_inventory(index: int, rng: random.Random) -> tuple[InventoryInstance, str]:
|
| 96 |
+
difficulty = _difficulty(index, N_INVENTORY, 3)
|
| 97 |
+
n_sku = 2 if difficulty == Difficulty.EASY else 3 if difficulty != Difficulty.HARD else 4
|
| 98 |
+
periods = 3 if difficulty != Difficulty.HARD else 4
|
| 99 |
+
cover = difficulty in {Difficulty.HARD, Difficulty.INFEASIBLE} or index % 5 == 0
|
| 100 |
+
skus = []
|
| 101 |
+
for k in range(n_sku):
|
| 102 |
+
demand = [rng.randint(2, 8) for _ in range(periods)]
|
| 103 |
+
pack = rng.choice([1, 2, 3])
|
| 104 |
+
skus.append(
|
| 105 |
+
InventorySku(
|
| 106 |
+
sku_id=f"S{k + 1}",
|
| 107 |
+
name=SKU_NAMES[k],
|
| 108 |
+
demand=demand,
|
| 109 |
+
initial_stock=rng.randint(0, 3),
|
| 110 |
+
unit_cost=rng.randint(3, 9),
|
| 111 |
+
holding_cost=rng.randint(1, 3),
|
| 112 |
+
shortage_cost=rng.randint(6, 14),
|
| 113 |
+
pack_size=pack,
|
| 114 |
+
lead_time=0,
|
| 115 |
+
)
|
| 116 |
+
)
|
| 117 |
+
total_need = sum(max(0, sum(sku.demand) - sku.initial_stock) for sku in skus)
|
| 118 |
+
min_buy = 0
|
| 119 |
+
for sku in skus:
|
| 120 |
+
need = max(0, sum(sku.demand) - sku.initial_stock)
|
| 121 |
+
packs = (need + sku.pack_size - 1) // sku.pack_size
|
| 122 |
+
min_buy += packs * sku.pack_size * sku.unit_cost
|
| 123 |
+
cap = max(8, int(total_need * 0.7) + rng.randint(2, 8))
|
| 124 |
+
if difficulty == Difficulty.INFEASIBLE:
|
| 125 |
+
for sku in skus:
|
| 126 |
+
sku.initial_stock = 0
|
| 127 |
+
sku.demand = [max(3, value) for value in sku.demand]
|
| 128 |
+
total_need = sum(sum(sku.demand) for sku in skus)
|
| 129 |
+
min_buy = 0
|
| 130 |
+
for sku in skus:
|
| 131 |
+
packs = (sum(sku.demand) + sku.pack_size - 1) // sku.pack_size
|
| 132 |
+
min_buy += packs * sku.pack_size * sku.unit_cost
|
| 133 |
+
budget = max(1, min_buy // 5)
|
| 134 |
+
cover = True
|
| 135 |
+
cap = max(6, total_need)
|
| 136 |
+
elif difficulty == Difficulty.HARD:
|
| 137 |
+
budget = max(min_buy, int(min_buy * 1.05) + 2)
|
| 138 |
+
else:
|
| 139 |
+
budget = min_buy + rng.randint(8, 24)
|
| 140 |
+
instance = InventoryInstance(
|
| 141 |
+
periods=periods,
|
| 142 |
+
budget=int(budget),
|
| 143 |
+
warehouse_capacity=int(cap),
|
| 144 |
+
cover_required=cover,
|
| 145 |
+
lost_sales=True,
|
| 146 |
+
skus=skus,
|
| 147 |
+
)
|
| 148 |
+
return instance, difficulty.value
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def render_inventory(instance: InventoryInstance, template_id: str, language: str) -> tuple[str, str]:
|
| 152 |
+
labeled = []
|
| 153 |
+
for sku in instance.skus:
|
| 154 |
+
labeled.append(
|
| 155 |
+
f"SKU {sku.sku_id} demand={','.join(str(v) for v in sku.demand)} pack={sku.pack_size} "
|
| 156 |
+
f"cost={sku.unit_cost} hold={sku.holding_cost} short={sku.shortage_cost} stock={sku.initial_stock}"
|
| 157 |
+
)
|
| 158 |
+
labels = (
|
| 159 |
+
f"PERIODS: {instance.periods}\nBUDGET: {instance.budget}\nCAPACITY: {instance.warehouse_capacity}\n"
|
| 160 |
+
f"COVER_REQUIRED: {1 if instance.cover_required else 0}\n" + "\n".join(labeled)
|
| 161 |
+
)
|
| 162 |
+
schema_block = _wrap_schema(instance.model_dump(), template_id)
|
| 163 |
+
names = ", ".join(f"{sku.sku_id} ({sku.name})" for sku in instance.skus)
|
| 164 |
+
names_fa = ", ".join(f"{sku.sku_id} ({SKU_FA[int(sku.sku_id[1:]) - 1]})" for sku in instance.skus)
|
| 165 |
+
cover_en = "All demand must be covered; lost sales are forbidden." if instance.cover_required else "Lost sales are allowed and charged."
|
| 166 |
+
cover_fa = "پوشش کامل تقاضا الزامی است." if instance.cover_required else "کمبود مجاز است و جریمه دارد."
|
| 167 |
+
if template_id in {"D-A", "D-B", "D-C"}:
|
| 168 |
+
en = (
|
| 169 |
+
f"A B2B warehouse plans {instance.periods} weeks for {len(instance.skus)} SKUs: {names}. "
|
| 170 |
+
f"{cover_en} Orders are pack multiples. Lead time is 0. "
|
| 171 |
+
f"Budget is {instance.budget} currency units. Storage holds at most {instance.warehouse_capacity} units in total. "
|
| 172 |
+
"Minimize purchase + holding + shortage.\n"
|
| 173 |
+
f"{labels}\n{schema_block}"
|
| 174 |
+
)
|
| 175 |
+
fa = (
|
| 176 |
+
f"یک انبار B2B برای {instance.periods} هفته و {len(instance.skus)} کالا برنامه میخرد: {names_fa}. "
|
| 177 |
+
f"{cover_fa} سفارش مضرب بسته است. زمان تأمین صفر است. "
|
| 178 |
+
f"بودجه برابر {instance.budget} واحد پول و ظرفیت انبار {instance.warehouse_capacity} واحد است. "
|
| 179 |
+
"هدف کمینهکردن خرید + نگهداری + کمبود است.\n"
|
| 180 |
+
f"{labels}\n{schema_block}"
|
| 181 |
+
)
|
| 182 |
+
else:
|
| 183 |
+
demand_txt = "; ".join(f"{sku.sku_id} wants {sku.demand} at pack {sku.pack_size}" for sku in instance.skus)
|
| 184 |
+
en = (
|
| 185 |
+
f"Replenish {names} over a {instance.periods}-week horizon. {cover_en} "
|
| 186 |
+
f"The buyer cannot spend more than {instance.budget}. On-hand stock across SKUs cannot exceed {instance.warehouse_capacity}. "
|
| 187 |
+
f"{demand_txt}. Costs and opening stock are in the JSON companion."
|
| 188 |
+
)
|
| 189 |
+
fa = (
|
| 190 |
+
f"برای {names_fa} در افق {instance.periods} هفته خرید کنید. {cover_fa} "
|
| 191 |
+
f"سقف هزینه {instance.budget} و سقف موجودی کل {instance.warehouse_capacity} است. "
|
| 192 |
+
"جزئیات تقاضا و بسته در فایل JSON همراه است."
|
| 193 |
+
)
|
| 194 |
+
return en, fa
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def make_assignment(index: int, rng: random.Random) -> tuple[AssignmentInstance, str]:
|
| 198 |
+
difficulty = _difficulty(index, N_ASSIGNMENT, 2)
|
| 199 |
+
n_tasks = 4 if difficulty == Difficulty.EASY else 6 if difficulty != Difficulty.HARD else 8
|
| 200 |
+
n_agents = 3 if difficulty != Difficulty.HARD else 4
|
| 201 |
+
tasks = []
|
| 202 |
+
for k in range(n_tasks):
|
| 203 |
+
skills = [rng.choice(TASK_SKILLS)]
|
| 204 |
+
if difficulty != Difficulty.EASY and rng.random() < 0.35:
|
| 205 |
+
skills.append(rng.choice(TASK_SKILLS))
|
| 206 |
+
skills = sorted(set(skills))
|
| 207 |
+
tasks.append(
|
| 208 |
+
AssignmentTask(
|
| 209 |
+
task_id=f"T{k + 1}",
|
| 210 |
+
name=f"job-{k + 1}",
|
| 211 |
+
size=rng.randint(1, 3),
|
| 212 |
+
required=True if difficulty == Difficulty.INFEASIBLE else (k < n_tasks - 1 or difficulty != Difficulty.EASY),
|
| 213 |
+
skills=skills,
|
| 214 |
+
penalty=rng.randint(20, 40),
|
| 215 |
+
)
|
| 216 |
+
)
|
| 217 |
+
agents = []
|
| 218 |
+
for k in range(n_agents):
|
| 219 |
+
skills = [TASK_SKILLS[k % len(TASK_SKILLS)]]
|
| 220 |
+
if difficulty != Difficulty.EASY:
|
| 221 |
+
skills.append(TASK_SKILLS[(k + 1) % len(TASK_SKILLS)])
|
| 222 |
+
agents.append(
|
| 223 |
+
AssignmentAgent(
|
| 224 |
+
agent_id=f"A{k + 1}",
|
| 225 |
+
name=f"tech-{k + 1}",
|
| 226 |
+
capacity=rng.randint(3, 6) if difficulty != Difficulty.INFEASIBLE else 1,
|
| 227 |
+
skills=sorted(set(skills)),
|
| 228 |
+
)
|
| 229 |
+
)
|
| 230 |
+
if difficulty == Difficulty.INFEASIBLE:
|
| 231 |
+
for task in tasks:
|
| 232 |
+
task.required = True
|
| 233 |
+
task.size = 3
|
| 234 |
+
for agent in agents:
|
| 235 |
+
agent.capacity = 1
|
| 236 |
+
else:
|
| 237 |
+
for idx, task in enumerate(tasks):
|
| 238 |
+
agent = agents[idx % len(agents)]
|
| 239 |
+
if not (set(task.skills) & set(agent.skills)):
|
| 240 |
+
task.skills = sorted(set(task.skills + agent.skills[:1]))
|
| 241 |
+
required_load = sum(task.size for task in tasks if task.required)
|
| 242 |
+
agents[-1].skills = sorted(set(TASK_SKILLS))
|
| 243 |
+
total_cap = sum(agent.capacity for agent in agents)
|
| 244 |
+
if required_load > total_cap:
|
| 245 |
+
agents[-1].capacity += required_load - total_cap + 2
|
| 246 |
+
else:
|
| 247 |
+
agents[-1].capacity += 2
|
| 248 |
+
costs = []
|
| 249 |
+
for task in tasks:
|
| 250 |
+
for agent in agents:
|
| 251 |
+
if set(task.skills) & set(agent.skills) or not task.skills:
|
| 252 |
+
costs.append(AssignmentCost(task_id=task.task_id, agent_id=agent.agent_id, cost=rng.randint(4, 18)))
|
| 253 |
+
return AssignmentInstance(tasks=tasks, agents=agents, costs=costs), difficulty.value
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def render_assignment(instance: AssignmentInstance, template_id: str) -> tuple[str, str]:
|
| 257 |
+
payload = instance.model_dump()
|
| 258 |
+
schema_block = _wrap_schema(payload, template_id)
|
| 259 |
+
task_txt = ", ".join(f"{task.task_id} size {task.size} skills {'/'.join(task.skills)}" for task in instance.tasks)
|
| 260 |
+
agent_txt = ", ".join(f"{agent.agent_id} cap {agent.capacity} skills {'/'.join(agent.skills)}" for agent in instance.agents)
|
| 261 |
+
if template_id.startswith("D-"):
|
| 262 |
+
en = (
|
| 263 |
+
"Assign each required maintenance task to at most one eligible technician. "
|
| 264 |
+
"Do not exceed agent capacity. Optional leftover tasks pay a penalty.\n"
|
| 265 |
+
f"TASKS: {task_txt}\nAGENTS: {agent_txt}\n{schema_block}"
|
| 266 |
+
)
|
| 267 |
+
fa = (
|
| 268 |
+
"هر کار الزامی را حداکثر به یک تکنسین واجد مهارت بدهید و از ظرفیت نفر تجاوز نکنید. "
|
| 269 |
+
"کار اختیاریِ انجامنشده جریمه دارد.\n"
|
| 270 |
+
f"TASKS: {task_txt}\nAGENTS: {agent_txt}\n{schema_block}"
|
| 271 |
+
)
|
| 272 |
+
else:
|
| 273 |
+
en = (
|
| 274 |
+
f"A service desk has technicians {agent_txt}. Work orders: {task_txt}. "
|
| 275 |
+
"A task may use an agent only when they share a skill. Minimize assignment cost plus leftover penalties."
|
| 276 |
+
)
|
| 277 |
+
fa = (
|
| 278 |
+
f"میز خدمت تکنسینهای {agent_txt} را دارد. سفارشها: {task_txt}. "
|
| 279 |
+
"تخصیص فقط با مهارت مشترک مجاز است. هزینه تخصیص بهعلاوه جریمه کار باقیمانده کمینه شود."
|
| 280 |
+
)
|
| 281 |
+
return en, fa
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def make_schedule(index: int, rng: random.Random) -> tuple[ScheduleInstance, str]:
|
| 285 |
+
difficulty = _difficulty(index, N_SCHEDULING, 3)
|
| 286 |
+
n_jobs = 4 if difficulty == Difficulty.EASY else 6 if difficulty != Difficulty.HARD else 8
|
| 287 |
+
machines = ["M1"] if difficulty == Difficulty.EASY else ["M1", "M2"]
|
| 288 |
+
jobs = []
|
| 289 |
+
cursor = 0
|
| 290 |
+
for k in range(n_jobs):
|
| 291 |
+
duration = rng.randint(2, 5)
|
| 292 |
+
release = rng.choice([0, 0, 1, 2])
|
| 293 |
+
due = cursor + duration + rng.randint(1, 4)
|
| 294 |
+
hard = difficulty == Difficulty.INFEASIBLE and k < 2
|
| 295 |
+
if difficulty == Difficulty.INFEASIBLE and k < 2:
|
| 296 |
+
due = release + duration - 1
|
| 297 |
+
eligible = machines[:] if difficulty == Difficulty.EASY or rng.random() < 0.7 else [rng.choice(machines)]
|
| 298 |
+
jobs.append(
|
| 299 |
+
ScheduleJob(
|
| 300 |
+
job_id=f"J{k + 1}",
|
| 301 |
+
name=f"op-{k + 1}",
|
| 302 |
+
duration=duration,
|
| 303 |
+
release=release,
|
| 304 |
+
due=max(due, release + duration),
|
| 305 |
+
weight=rng.randint(1, 4),
|
| 306 |
+
hard_due=hard,
|
| 307 |
+
machine_eligible=eligible,
|
| 308 |
+
)
|
| 309 |
+
)
|
| 310 |
+
cursor += duration
|
| 311 |
+
if difficulty == Difficulty.INFEASIBLE and len(jobs) >= 2:
|
| 312 |
+
jobs[0].hard_due = True
|
| 313 |
+
jobs[0].due = jobs[0].release + jobs[0].duration - 1
|
| 314 |
+
jobs[1].hard_due = True
|
| 315 |
+
jobs[1].due = jobs[1].release + jobs[1].duration - 1
|
| 316 |
+
if jobs[0].due < jobs[0].release + jobs[0].duration:
|
| 317 |
+
pass
|
| 318 |
+
precedences = []
|
| 319 |
+
if difficulty != Difficulty.EASY and n_jobs >= 3:
|
| 320 |
+
precedences.append(SchedulePrecedence(before="J1", after="J3"))
|
| 321 |
+
if difficulty == Difficulty.HARD and n_jobs >= 5:
|
| 322 |
+
precedences.append(SchedulePrecedence(before="J2", after="J5"))
|
| 323 |
+
horizon = sum(job.duration for job in jobs) + 8
|
| 324 |
+
return ScheduleInstance(machines=machines, jobs=jobs, precedences=precedences, horizon=horizon), difficulty.value
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def render_schedule(instance: ScheduleInstance, template_id: str) -> tuple[str, str]:
|
| 328 |
+
payload = instance.model_dump()
|
| 329 |
+
schema_block = _wrap_schema(payload, template_id)
|
| 330 |
+
job_txt = ", ".join(
|
| 331 |
+
f"{job.job_id} dur {job.duration} rel {job.release} due {job.due}{' hard' if job.hard_due else ''}"
|
| 332 |
+
for job in instance.jobs
|
| 333 |
+
)
|
| 334 |
+
pred = ", ".join(f"{edge.before}->{edge.after}" for edge in instance.precedences) or "none"
|
| 335 |
+
if template_id.startswith("D-"):
|
| 336 |
+
en = (
|
| 337 |
+
f"Schedule jobs on machines {', '.join(instance.machines)} without overlap. "
|
| 338 |
+
f"Respect release times and precedences ({pred}). Hard due dates are deadlines.\n"
|
| 339 |
+
f"JOBS: {job_txt}\n{schema_block}"
|
| 340 |
+
)
|
| 341 |
+
fa = (
|
| 342 |
+
f"کارها را روی ماشینهای {', '.join(instance.machines)} بدون همپوشانی زمانبندی کنید. "
|
| 343 |
+
f"زمان آزادسازی و تقدم ({pred}) رعایت شود. موعد سخت ضربالاجل است.\n"
|
| 344 |
+
f"JOBS: {job_txt}\n{schema_block}"
|
| 345 |
+
)
|
| 346 |
+
else:
|
| 347 |
+
en = (
|
| 348 |
+
f"A shop has machines {', '.join(instance.machines)}. Jobs: {job_txt}. "
|
| 349 |
+
f"Precedence: {pred}. Minimize weighted tardiness. Do not overlap a machine."
|
| 350 |
+
)
|
| 351 |
+
fa = (
|
| 352 |
+
f"کارگاه ماشینهای {', '.join(instance.machines)} را دارد. کارها: {job_txt}. "
|
| 353 |
+
f"تقدم: {pred}. تأخیر وزنی کمینه شود و ماشین همپوشانی نداشته باشد."
|
| 354 |
+
)
|
| 355 |
+
return en, fa
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def _finalize(
|
| 359 |
+
problem_id: str,
|
| 360 |
+
family: Family,
|
| 361 |
+
index: int,
|
| 362 |
+
n_items: int,
|
| 363 |
+
instance,
|
| 364 |
+
difficulty: str,
|
| 365 |
+
template_id: str,
|
| 366 |
+
language: str,
|
| 367 |
+
seed: int,
|
| 368 |
+
prompt_en: str,
|
| 369 |
+
prompt_fa: str,
|
| 370 |
+
notes: str,
|
| 371 |
+
) -> ProblemRecord:
|
| 372 |
+
split = _split_for(index, n_items)
|
| 373 |
+
payload = instance.model_dump()
|
| 374 |
+
gold = solve_instance(family, payload, seconds=6.0, threads=1)
|
| 375 |
+
wanted = Difficulty(difficulty)
|
| 376 |
+
if wanted == Difficulty.INFEASIBLE and gold.solution.status.value != "infeasible":
|
| 377 |
+
notes = (notes + " requested infeasible; solver found a plan so the row is hard.").strip()
|
| 378 |
+
wanted = Difficulty.HARD
|
| 379 |
+
structural = _key(
|
| 380 |
+
family.value,
|
| 381 |
+
split.value,
|
| 382 |
+
template_id,
|
| 383 |
+
problem_id,
|
| 384 |
+
json.dumps(payload, sort_keys=True, ensure_ascii=False),
|
| 385 |
+
wanted.value,
|
| 386 |
+
)
|
| 387 |
+
return ProblemRecord(
|
| 388 |
+
problem_id=problem_id,
|
| 389 |
+
family=family,
|
| 390 |
+
split=split,
|
| 391 |
+
interactive=problem_id in INTERACTIVE_IDS,
|
| 392 |
+
difficulty=wanted,
|
| 393 |
+
language=language,
|
| 394 |
+
template_id=template_id,
|
| 395 |
+
seed=seed,
|
| 396 |
+
prompt_en=prompt_en,
|
| 397 |
+
prompt_fa=prompt_fa,
|
| 398 |
+
prompt_json=_json_prompt(payload),
|
| 399 |
+
schema_payload=payload,
|
| 400 |
+
gold_status=gold.solution.status.value,
|
| 401 |
+
gold_objective=gold.solution.objective,
|
| 402 |
+
gold_bound=gold.solution.bound,
|
| 403 |
+
gold_solution=gold.solution.as_dict(),
|
| 404 |
+
structural_key=structural,
|
| 405 |
+
notes=notes,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def generate_catalog(seed: int = DEFAULT_SEED) -> list[ProblemRecord]:
|
| 410 |
+
problems: list[ProblemRecord] = []
|
| 411 |
+
for index in range(1, N_INVENTORY + 1):
|
| 412 |
+
rng = random.Random(seed * 1000 + index)
|
| 413 |
+
instance, difficulty = make_inventory(index, rng)
|
| 414 |
+
split = _split_for(index, N_INVENTORY)
|
| 415 |
+
template_id = _template(split, index)
|
| 416 |
+
language = "en" if index % 2 else "fa"
|
| 417 |
+
en, fa = render_inventory(instance, template_id, language)
|
| 418 |
+
problems.append(
|
| 419 |
+
_finalize(
|
| 420 |
+
f"INV-{index:03d}",
|
| 421 |
+
Family.INVENTORY,
|
| 422 |
+
index,
|
| 423 |
+
N_INVENTORY,
|
| 424 |
+
instance,
|
| 425 |
+
difficulty,
|
| 426 |
+
template_id,
|
| 427 |
+
language,
|
| 428 |
+
seed * 1000 + index,
|
| 429 |
+
en,
|
| 430 |
+
fa,
|
| 431 |
+
"lead time is 0; units are abstract currency and pieces",
|
| 432 |
+
)
|
| 433 |
+
)
|
| 434 |
+
for index in range(1, N_ASSIGNMENT + 1):
|
| 435 |
+
rng = random.Random(seed * 2000 + index)
|
| 436 |
+
instance, difficulty = make_assignment(index, rng)
|
| 437 |
+
split = _split_for(index, N_ASSIGNMENT)
|
| 438 |
+
template_id = _template(split, index)
|
| 439 |
+
language = "fa" if index % 2 else "en"
|
| 440 |
+
en, fa = render_assignment(instance, template_id)
|
| 441 |
+
problems.append(
|
| 442 |
+
_finalize(
|
| 443 |
+
f"ASN-{index:03d}",
|
| 444 |
+
Family.ASSIGNMENT,
|
| 445 |
+
index,
|
| 446 |
+
N_ASSIGNMENT,
|
| 447 |
+
instance,
|
| 448 |
+
difficulty,
|
| 449 |
+
template_id,
|
| 450 |
+
language,
|
| 451 |
+
seed * 2000 + index,
|
| 452 |
+
en,
|
| 453 |
+
fa,
|
| 454 |
+
"skill intersection is the eligibility rule",
|
| 455 |
+
)
|
| 456 |
+
)
|
| 457 |
+
for index in range(1, N_SCHEDULING + 1):
|
| 458 |
+
rng = random.Random(seed * 3000 + index)
|
| 459 |
+
instance, difficulty = make_schedule(index, rng)
|
| 460 |
+
split = _split_for(index, N_SCHEDULING)
|
| 461 |
+
template_id = _template(split, index)
|
| 462 |
+
language = "en" if index % 3 else "fa"
|
| 463 |
+
en, fa = render_schedule(instance, template_id)
|
| 464 |
+
problems.append(
|
| 465 |
+
_finalize(
|
| 466 |
+
f"SCH-{index:03d}",
|
| 467 |
+
Family.SCHEDULING,
|
| 468 |
+
index,
|
| 469 |
+
N_SCHEDULING,
|
| 470 |
+
instance,
|
| 471 |
+
difficulty,
|
| 472 |
+
template_id,
|
| 473 |
+
language,
|
| 474 |
+
seed * 3000 + index,
|
| 475 |
+
en,
|
| 476 |
+
fa,
|
| 477 |
+
"objective reported as weighted tardiness; makespan is a tie-break inside the solver only",
|
| 478 |
+
)
|
| 479 |
+
)
|
| 480 |
+
if len(problems) != N_PROBLEMS:
|
| 481 |
+
raise RuntimeError(f"expected {N_PROBLEMS} problems, got {len(problems)}")
|
| 482 |
+
return problems
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def write_catalog(path: Path, seed: int = DEFAULT_SEED) -> list[ProblemRecord]:
|
| 486 |
+
problems = generate_catalog(seed)
|
| 487 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 488 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 489 |
+
for row in problems:
|
| 490 |
+
handle.write(row.model_dump_json() + "\n")
|
| 491 |
+
return problems
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def load_catalog(path: Path | None = None) -> list[ProblemRecord]:
|
| 495 |
+
if path and path.exists():
|
| 496 |
+
rows = []
|
| 497 |
+
for line in path.read_text(encoding="utf-8").splitlines():
|
| 498 |
+
if line.strip():
|
| 499 |
+
rows.append(ProblemRecord.model_validate_json(line))
|
| 500 |
+
return rows
|
| 501 |
+
return generate_catalog()
|
demo/src/i18n.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
TEXTS = {
|
| 4 |
+
"en": {
|
| 5 |
+
"title": "ORBench — Solver and Agent Decision Benchmark",
|
| 6 |
+
"subtitle": "Compare structured solvers, heuristics, and text-to-schema agents on 100 small inventory, assignment, and scheduling tasks.",
|
| 7 |
+
"kind": "Research prototype · numeric validator is the judge · CPU · no paid API",
|
| 8 |
+
"run_sample": "Run sample",
|
| 9 |
+
"cancel": "Cancel run",
|
| 10 |
+
"reset": "Reset defaults",
|
| 11 |
+
"load_sample": "Load 20 interactive problems",
|
| 12 |
+
"language": "Language",
|
| 13 |
+
"problem": "Interactive problem",
|
| 14 |
+
"variant": "Prompt variant",
|
| 15 |
+
"template": "Labeled / narrative template",
|
| 16 |
+
"json": "JSON schema only",
|
| 17 |
+
"missing": "Hide a hard constraint in the text",
|
| 18 |
+
"time_limit": "Solver time limit (s)",
|
| 19 |
+
"advanced": "Advanced solver settings",
|
| 20 |
+
"sample_note": "Preview KPIs are a precomputed sample on the recorded 100-problem catalog. LLM rows stay not_evaluated. A fluent paragraph is not a feasible plan.",
|
| 21 |
+
"live_note": "Live CPU comparison: structured CP-SAT, fixed heuristic, JSON extractor, template extractor, and a naive direct answer. Named Hub models were not run.",
|
| 22 |
+
"kpi_n": "Problems in view",
|
| 23 |
+
"kpi_n_sub": "interactive subset or filtered catalog",
|
| 24 |
+
"kpi_feas": "Structured-solver feasible",
|
| 25 |
+
"kpi_feas_sub": "share of valid plans after independent checks",
|
| 26 |
+
"kpi_gap": "Heuristic mean gap",
|
| 27 |
+
"kpi_gap_sub": "only where gold status is proven optimal",
|
| 28 |
+
"kpi_fid": "Template fidelity",
|
| 29 |
+
"kpi_fid_sub": "atomic constraint facts recovered from text",
|
| 30 |
+
"kpi_eval": "Methods evaluated",
|
| 31 |
+
"kpi_eval_sub": "evaluated / listed — unevaluated is not zero",
|
| 32 |
+
"empty": "No live result yet. Load a sample problem and run a comparison.",
|
| 33 |
+
"status": "Reference status",
|
| 34 |
+
"upload_hint": "Edit the schema JSON only if you want a structured-solver what-if. Prompts stay synthetic. Direct-answer JSON is benchmark-only.",
|
| 35 |
+
"method_plot": "Parse and feasibility rates for evaluated methods",
|
| 36 |
+
"family_plot": "Feasibility by family for evaluated methods",
|
| 37 |
+
"sol_plot": "Reference CP-SAT plan",
|
| 38 |
+
"custom_text": "Optional custom prompt",
|
| 39 |
+
"custom_schema": "Editable schema JSON",
|
| 40 |
+
"direct_json": "Optional direct-answer JSON (benchmark only)",
|
| 41 |
+
"method_body": """
|
| 42 |
+
ORBench is a research prototype for comparing decision-making *methods*, not a ranking of companies or a production optimizer.
|
| 43 |
+
|
| 44 |
+
**What it decides.** For each tiny instance it records parse success, constraint fidelity, feasibility, and optimality gap versus a gold CP-SAT run. An LLM score is never the judge.
|
| 45 |
+
|
| 46 |
+
**Three families.** Inventory (pack multiples, budget, warehouse capacity, optional hard cover), assignment (skill + capacity), and scheduling (release, precedence, optional hard due dates). Lead time is 0. Units are abstract.
|
| 47 |
+
|
| 48 |
+
**Methods actually run.** `structured-solver`, `heuristic`, `json-extractor+solver`, `template-extractor+solver`, `naive-direct`. Development prompts include a `SCHEMA_BEGIN` block; test prompts are prose so the template extractor can fail honestly.
|
| 49 |
+
|
| 50 |
+
**Methods listed but not run.** Qwen, Kimi, GLM, and DeepSeek cards stay `not_evaluated`. That cell is not a zero and not a rank.
|
| 51 |
+
|
| 52 |
+
**Validator.** An independent checker recomputes inventory balance, pack, budget, capacity, assignment uniqueness/eligibility/capacity, and schedule overlap/precedence/release. Gap is reported only when gold status is optimal.
|
| 53 |
+
|
| 54 |
+
**Limits.** 100 synthetic instances, CPU only, no paid API, no agent tool-use environment in this MVP, no claim that a fluent answer is operationally safe. Direct LLM-style answers are labeled benchmark-only.
|
| 55 |
+
""",
|
| 56 |
+
},
|
| 57 |
+
"fa": {
|
| 58 |
+
"title": "اوربنچ — آزمایشگاه مقایسه حلگر و عامل تصمیم",
|
| 59 |
+
"subtitle": "حلگر ساختاریافته، ابتکاری ثابت و عامل متنبهطرح را روی ۱۰۰ مسئله کوچک موجودی، تخصیص و زمانبندی مقایسه کنید.",
|
| 60 |
+
"kind": "نمونه پژوهشی · داور validator عددی است · CPU · بدون API پولی",
|
| 61 |
+
"run_sample": "اجرای نمونه",
|
| 62 |
+
"cancel": "لغو اجرا",
|
| 63 |
+
"reset": "بازگشت به پیشفرض",
|
| 64 |
+
"load_sample": "بارگذاری ۲۰ مسئله تعاملی",
|
| 65 |
+
"language": "زبان",
|
| 66 |
+
"problem": "مسئله تعاملی",
|
| 67 |
+
"variant": "نوع متن",
|
| 68 |
+
"template": "قالب برچسبدار / روایی",
|
| 69 |
+
"json": "فقط JSON",
|
| 70 |
+
"missing": "حذف یک قید سخت از متن",
|
| 71 |
+
"time_limit": "مهلت حلگر (ثانیه)",
|
| 72 |
+
"advanced": "تنظیمات پیشرفته حلگر",
|
| 73 |
+
"sample_note": "شاخصها نمونه از پیش محاسبهشده روی کاتالوگ ۱۰۰ مسئلهاند. ردیف مدل ��بانی «ارزیابی نشده» است. متن روان بهمعنای برنامه شدنی نیست.",
|
| 74 |
+
"live_note": "مقایسه زنده CPU: CP-SAT ساختاریافته، ابتکاری ثابت، استخراج JSON، استخراج قالب، و پاسخ مستقیم سادهلوح. مدلهای Hub اجرا نشدهاند.",
|
| 75 |
+
"kpi_n": "مسئله در نما",
|
| 76 |
+
"kpi_n_sub": "زیرمجموعه تعاملی یا کاتالوگ فیلترشده",
|
| 77 |
+
"kpi_feas": "شدنی بودن حلگر ساختاریافته",
|
| 78 |
+
"kpi_feas_sub": "سهم برنامه معتبر پس از کنترل مستقل",
|
| 79 |
+
"kpi_gap": "میانگین شکاف ابتکاری",
|
| 80 |
+
"kpi_gap_sub": "فقط وقتی وضعیت طلایی بهینه اثباتشده است",
|
| 81 |
+
"kpi_fid": "وفاداری استخراج قالب",
|
| 82 |
+
"kpi_fid_sub": "حقایق اتمی قید بازیابیشده از متن",
|
| 83 |
+
"kpi_eval": "روشهای ارزیابیشده",
|
| 84 |
+
"kpi_eval_sub": "ارزیابیشده / فهرستشده — ارزیابینشده صفر نیست",
|
| 85 |
+
"empty": "هنوز نتیجه زندهای نیست. یک مسئله نمونه را اجرا کنید.",
|
| 86 |
+
"status": "وضعیت مرجع",
|
| 87 |
+
"upload_hint": "JSON طرح را فقط برای آزمون حلگر ساختاریافته ویرایش کنید. پاسخ مستقیم فقط برای بنچمارک است.",
|
| 88 |
+
"method_plot": "نرخ تجزیه و امکانپذیری روشهای ارزیابیشده",
|
| 89 |
+
"family_plot": "امکانپذیری به تفکیک خانواده",
|
| 90 |
+
"sol_plot": "برنامه مرجع CP-SAT",
|
| 91 |
+
"custom_text": "متن سفارشی اختیاری",
|
| 92 |
+
"custom_schema": "JSON طرح قابل ویرایش",
|
| 93 |
+
"direct_json": "JSON پاسخ مستقیم اختیاری (فقط بنچمارک)",
|
| 94 |
+
"method_body": """
|
| 95 |
+
اوربنچ نمونه پژوهشی مقایسه *روش* است، نه رتبهبندی شرکت و نه بهینهساز عملیاتی.
|
| 96 |
+
|
| 97 |
+
**تصمیم.** برای هر نمونه کوچک، موفقیت تجزیه، وفاداری قید، امکانپذیری و شکاف بهینگی نسبت به اجرای طلایی CP-SAT ثبت میشود. امتیاز مدل زبانی داور نیست.
|
| 98 |
+
|
| 99 |
+
**سه خانواده.** موجودی، تخصیص و زمانبندی. زمان تأمین صفر است. واحدها انتزاعیاند.
|
| 100 |
+
|
| 101 |
+
**روشهای اجراشده.** حلگر ساختاریافته، ابتکاری، استخراج JSON، استخراج قالب، پاسخ مستقیم سادهلوح. متن توسعه بلوک SCHEMA دارد؛ متن آزمون نثر است تا استخراج قالب صادقانه شکست بخورد.
|
| 102 |
+
|
| 103 |
+
**روشهای اجرانشده.** Qwen، Kimi، GLM و DeepSeek در خانه «ارزیابی نشده» میمانند؛ این صفر یا رتبه نیست.
|
| 104 |
+
|
| 105 |
+
**محدودیت.** ۱۰۰ نمونه ساختگی، فقط CPU، بدون API پولی، بدون ادعای ایمنی عملیاتی برای متن روان.
|
| 106 |
+
""",
|
| 107 |
+
},
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def t(lang: str, key: str) -> str:
|
| 112 |
+
return TEXTS.get(lang, TEXTS["en"]).get(key, TEXTS["en"].get(key, key))
|
demo/src/metrics.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
from src.domain import EvalRow, SolveStatus, gap, not_evaluated_cell
|
| 8 |
+
from src.model_registry import UNEVALUATED_MODELS, evaluated_ids
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def row_from_run(
|
| 12 |
+
problem,
|
| 13 |
+
method_id: str,
|
| 14 |
+
method_kind: str,
|
| 15 |
+
parse_success: bool | None,
|
| 16 |
+
fidelity: float | None,
|
| 17 |
+
status: str,
|
| 18 |
+
feasible: bool | None,
|
| 19 |
+
objective: float | None,
|
| 20 |
+
seconds: float,
|
| 21 |
+
violated: list[str],
|
| 22 |
+
notes: str,
|
| 23 |
+
precomputed: bool = False,
|
| 24 |
+
cost_usd: float | None = 0.0,
|
| 25 |
+
) -> EvalRow:
|
| 26 |
+
gold_status = problem.gold_status
|
| 27 |
+
gold_obj = problem.gold_objective
|
| 28 |
+
opt_gap = gap(objective, gold_obj, gold_status) if feasible else None
|
| 29 |
+
return EvalRow(
|
| 30 |
+
problem_id=problem.problem_id,
|
| 31 |
+
method_id=method_id,
|
| 32 |
+
method_kind=method_kind,
|
| 33 |
+
evaluated=True,
|
| 34 |
+
parse_success=parse_success,
|
| 35 |
+
constraint_fidelity=fidelity,
|
| 36 |
+
status=status,
|
| 37 |
+
feasible=feasible,
|
| 38 |
+
optimality_gap=opt_gap,
|
| 39 |
+
objective=objective,
|
| 40 |
+
gold_objective=gold_obj,
|
| 41 |
+
gold_status=gold_status,
|
| 42 |
+
seconds=seconds,
|
| 43 |
+
cost_usd=cost_usd,
|
| 44 |
+
violated=violated,
|
| 45 |
+
notes=notes,
|
| 46 |
+
precomputed=precomputed,
|
| 47 |
+
family=problem.family.value,
|
| 48 |
+
split=problem.split.value,
|
| 49 |
+
language=problem.language,
|
| 50 |
+
difficulty=problem.difficulty.value,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def skipped_rows(problem) -> list[EvalRow]:
|
| 55 |
+
rows = []
|
| 56 |
+
for spec in UNEVALUATED_MODELS:
|
| 57 |
+
rows.append(
|
| 58 |
+
EvalRow(
|
| 59 |
+
problem_id=problem.problem_id,
|
| 60 |
+
method_id=spec.method_id,
|
| 61 |
+
method_kind=spec.kind.value,
|
| 62 |
+
evaluated=False,
|
| 63 |
+
parse_success=None,
|
| 64 |
+
constraint_fidelity=None,
|
| 65 |
+
status=not_evaluated_cell(),
|
| 66 |
+
feasible=None,
|
| 67 |
+
optimality_gap=None,
|
| 68 |
+
objective=None,
|
| 69 |
+
gold_objective=problem.gold_objective,
|
| 70 |
+
gold_status=problem.gold_status,
|
| 71 |
+
seconds=0.0,
|
| 72 |
+
cost_usd=None,
|
| 73 |
+
violated=[],
|
| 74 |
+
notes=spec.reason_if_skipped,
|
| 75 |
+
precomputed=True,
|
| 76 |
+
family=problem.family.value,
|
| 77 |
+
split=problem.split.value,
|
| 78 |
+
language=problem.language,
|
| 79 |
+
difficulty=problem.difficulty.value,
|
| 80 |
+
)
|
| 81 |
+
)
|
| 82 |
+
return rows
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def summarize(rows: list[EvalRow] | pd.DataFrame) -> pd.DataFrame:
|
| 86 |
+
frame = rows if isinstance(rows, pd.DataFrame) else pd.DataFrame([row.model_dump() for row in rows])
|
| 87 |
+
if frame.empty:
|
| 88 |
+
return pd.DataFrame()
|
| 89 |
+
out = []
|
| 90 |
+
for method_id, group in frame.groupby("method_id", dropna=False):
|
| 91 |
+
evaluated = bool(group["evaluated"].iloc[0])
|
| 92 |
+
if not evaluated:
|
| 93 |
+
out.append(
|
| 94 |
+
{
|
| 95 |
+
"method_id": method_id,
|
| 96 |
+
"evaluated": False,
|
| 97 |
+
"n": int(len(group)),
|
| 98 |
+
"parse_rate": not_evaluated_cell(),
|
| 99 |
+
"feasible_rate": not_evaluated_cell(),
|
| 100 |
+
"infeasible_agreement": not_evaluated_cell(),
|
| 101 |
+
"mean_gap": not_evaluated_cell(),
|
| 102 |
+
"mean_fidelity": not_evaluated_cell(),
|
| 103 |
+
"mean_seconds": not_evaluated_cell(),
|
| 104 |
+
"mean_cost_usd": not_evaluated_cell(),
|
| 105 |
+
"n_optimal": not_evaluated_cell(),
|
| 106 |
+
}
|
| 107 |
+
)
|
| 108 |
+
continue
|
| 109 |
+
parsed = group["parse_success"].dropna()
|
| 110 |
+
feasible = group["feasible"].dropna()
|
| 111 |
+
inf_gold = group.loc[group["gold_status"] == SolveStatus.INFEASIBLE.value]
|
| 112 |
+
agree = None
|
| 113 |
+
if len(inf_gold):
|
| 114 |
+
agree = float((inf_gold["status"] == SolveStatus.INFEASIBLE.value).mean())
|
| 115 |
+
gaps = group["optimality_gap"].dropna()
|
| 116 |
+
fidelity = group["constraint_fidelity"].dropna()
|
| 117 |
+
out.append(
|
| 118 |
+
{
|
| 119 |
+
"method_id": method_id,
|
| 120 |
+
"evaluated": True,
|
| 121 |
+
"n": int(len(group)),
|
| 122 |
+
"parse_rate": None if parsed.empty else float(parsed.mean()),
|
| 123 |
+
"feasible_rate": None if feasible.empty else float(feasible.mean()),
|
| 124 |
+
"infeasible_agreement": agree,
|
| 125 |
+
"mean_gap": None if gaps.empty else float(gaps.mean()),
|
| 126 |
+
"mean_fidelity": None if fidelity.empty else float(fidelity.mean()),
|
| 127 |
+
"mean_seconds": float(group["seconds"].mean()),
|
| 128 |
+
"mean_cost_usd": float(group["cost_usd"].fillna(0).mean()),
|
| 129 |
+
"n_optimal": int((group["status"] == SolveStatus.OPTIMAL.value).sum()),
|
| 130 |
+
}
|
| 131 |
+
)
|
| 132 |
+
return pd.DataFrame(out).sort_values(["evaluated", "method_id"], ascending=[False, True]).reset_index(drop=True)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def family_summary(rows: list[EvalRow] | pd.DataFrame) -> pd.DataFrame:
|
| 136 |
+
frame = rows if isinstance(rows, pd.DataFrame) else pd.DataFrame([row.model_dump() for row in rows])
|
| 137 |
+
if frame.empty:
|
| 138 |
+
return pd.DataFrame()
|
| 139 |
+
live = frame.loc[frame["evaluated"] == True] # noqa: E712
|
| 140 |
+
if live.empty:
|
| 141 |
+
return pd.DataFrame()
|
| 142 |
+
records = []
|
| 143 |
+
for (family, method_id), group in live.groupby(["family", "method_id"]):
|
| 144 |
+
feasible = group["feasible"].dropna()
|
| 145 |
+
gaps = group["optimality_gap"].dropna()
|
| 146 |
+
records.append(
|
| 147 |
+
{
|
| 148 |
+
"family": family,
|
| 149 |
+
"method_id": method_id,
|
| 150 |
+
"n": int(len(group)),
|
| 151 |
+
"feasible_rate": None if feasible.empty else float(feasible.mean()),
|
| 152 |
+
"mean_gap": None if gaps.empty else float(gaps.mean()),
|
| 153 |
+
}
|
| 154 |
+
)
|
| 155 |
+
return pd.DataFrame(records).sort_values(["family", "method_id"]).reset_index(drop=True)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def display_cell(value) -> str:
|
| 159 |
+
if value is None:
|
| 160 |
+
return not_evaluated_cell()
|
| 161 |
+
if isinstance(value, float):
|
| 162 |
+
return f"{value:.3f}"
|
| 163 |
+
return str(value)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def kpi_snapshot(rows: list[EvalRow] | pd.DataFrame) -> dict[str, float | str | int]:
|
| 167 |
+
frame = rows if isinstance(rows, pd.DataFrame) else pd.DataFrame([row.model_dump() for row in rows])
|
| 168 |
+
live = frame.loc[frame["method_id"].isin(evaluated_ids())] if not frame.empty else frame
|
| 169 |
+
structured = live.loc[live["method_id"] == "structured-solver"] if not live.empty else live
|
| 170 |
+
heuristic = live.loc[live["method_id"] == "heuristic"] if not live.empty else live
|
| 171 |
+
extractor = live.loc[live["method_id"] == "template-extractor+solver"] if not live.empty else live
|
| 172 |
+
return {
|
| 173 |
+
"n_problems": int(structured["problem_id"].nunique()) if not structured.empty else 0,
|
| 174 |
+
"structured_feasible": float(structured["feasible"].dropna().mean()) if not structured.empty else 0.0,
|
| 175 |
+
"heuristic_gap": float(heuristic["optimality_gap"].dropna().mean()) if not heuristic.empty and heuristic["optimality_gap"].notna().any() else None,
|
| 176 |
+
"template_fidelity": float(extractor["constraint_fidelity"].dropna().mean()) if not extractor.empty and extractor["constraint_fidelity"].notna().any() else None,
|
| 177 |
+
"n_methods_evaluated": int(len(evaluated_ids())),
|
| 178 |
+
"n_methods_listed": int(frame["method_id"].nunique()) if not frame.empty else 0,
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def compare_two(rows: pd.DataFrame, left: str, right: str) -> pd.DataFrame:
|
| 183 |
+
if rows.empty:
|
| 184 |
+
return pd.DataFrame()
|
| 185 |
+
a = rows.loc[rows["method_id"] == left].set_index("problem_id")
|
| 186 |
+
b = rows.loc[rows["method_id"] == right].set_index("problem_id")
|
| 187 |
+
ids = sorted(set(a.index) & set(b.index))
|
| 188 |
+
out = []
|
| 189 |
+
for problem_id in ids:
|
| 190 |
+
out.append(
|
| 191 |
+
{
|
| 192 |
+
"problem_id": problem_id,
|
| 193 |
+
f"{left}_status": a.loc[problem_id, "status"],
|
| 194 |
+
f"{right}_status": b.loc[problem_id, "status"],
|
| 195 |
+
f"{left}_obj": a.loc[problem_id, "objective"],
|
| 196 |
+
f"{right}_obj": b.loc[problem_id, "objective"],
|
| 197 |
+
f"{left}_feasible": a.loc[problem_id, "feasible"],
|
| 198 |
+
f"{right}_feasible": b.loc[problem_id, "feasible"],
|
| 199 |
+
}
|
| 200 |
+
)
|
| 201 |
+
return pd.DataFrame(out)
|
demo/src/model_registry.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from src.domain import MethodKind, MethodSpec
|
| 4 |
+
|
| 5 |
+
REGISTRY_VERSION = "2026-09-20"
|
| 6 |
+
|
| 7 |
+
# Named Hub models are listed so the comparison table stays honest.
|
| 8 |
+
# None of the LLM rows were executed in this release. Cells stay
|
| 9 |
+
# "not_evaluated" rather than 0 or a fabricated rank.
|
| 10 |
+
EVALUATED_METHODS = (
|
| 11 |
+
MethodSpec(
|
| 12 |
+
method_id="structured-solver",
|
| 13 |
+
display_name="Structured form + CP-SAT",
|
| 14 |
+
kind=MethodKind.STRUCTURED_SOLVER,
|
| 15 |
+
evaluated=True,
|
| 16 |
+
version="ortools-cpsat",
|
| 17 |
+
notes="Gold schema or user-edited schema enters the solver. Numeric reference.",
|
| 18 |
+
),
|
| 19 |
+
MethodSpec(
|
| 20 |
+
method_id="heuristic",
|
| 21 |
+
display_name="Fixed heuristic (LFL / greedy / EDD)",
|
| 22 |
+
kind=MethodKind.HEURISTIC,
|
| 23 |
+
evaluated=True,
|
| 24 |
+
version="or-bench-heuristic-v1",
|
| 25 |
+
notes="Lot-for-lot inventory, cheapest-eligible assignment, earliest-due-date scheduling.",
|
| 26 |
+
),
|
| 27 |
+
MethodSpec(
|
| 28 |
+
method_id="template-extractor+solver",
|
| 29 |
+
display_name="Template extractor → solver",
|
| 30 |
+
kind=MethodKind.TEXT_TO_SCHEMA,
|
| 31 |
+
evaluated=True,
|
| 32 |
+
version="or-bench-template-v1",
|
| 33 |
+
notes="Deterministic labeled-field parser, then CP-SAT. Not an LLM.",
|
| 34 |
+
),
|
| 35 |
+
MethodSpec(
|
| 36 |
+
method_id="json-extractor+solver",
|
| 37 |
+
display_name="JSON extractor → solver",
|
| 38 |
+
kind=MethodKind.TEXT_TO_SCHEMA,
|
| 39 |
+
evaluated=True,
|
| 40 |
+
version="or-bench-json-v1",
|
| 41 |
+
notes="Parses a JSON object from the prompt, then CP-SAT.",
|
| 42 |
+
),
|
| 43 |
+
MethodSpec(
|
| 44 |
+
method_id="naive-direct",
|
| 45 |
+
display_name="Naive direct answer (benchmark only)",
|
| 46 |
+
kind=MethodKind.DIRECT_ANSWER,
|
| 47 |
+
evaluated=True,
|
| 48 |
+
version="or-bench-naive-v1",
|
| 49 |
+
notes="Writes a sloppy numeric plan without a solver. Operational use is not allowed.",
|
| 50 |
+
),
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
UNEVALUATED_MODELS = (
|
| 54 |
+
MethodSpec(
|
| 55 |
+
method_id="Qwen/Qwen3-4B-Instruct-2507",
|
| 56 |
+
display_name="Qwen3-4B-Instruct-2507",
|
| 57 |
+
kind=MethodKind.LLM_SCHEMA,
|
| 58 |
+
evaluated=False,
|
| 59 |
+
version="hub-card",
|
| 60 |
+
license="see model card",
|
| 61 |
+
reason_if_skipped="Paid/local LLM inference is off. No batch was run.",
|
| 62 |
+
),
|
| 63 |
+
MethodSpec(
|
| 64 |
+
method_id="Qwen/Qwen3.8-27B",
|
| 65 |
+
display_name="Qwen3.8-27B",
|
| 66 |
+
kind=MethodKind.LLM_SCHEMA,
|
| 67 |
+
evaluated=False,
|
| 68 |
+
version="hub-card",
|
| 69 |
+
license="see model card",
|
| 70 |
+
reason_if_skipped="Not hosted on this CPU Space. No API batch.",
|
| 71 |
+
),
|
| 72 |
+
MethodSpec(
|
| 73 |
+
method_id="moonshotai/Kimi-K3",
|
| 74 |
+
display_name="Kimi K3",
|
| 75 |
+
kind=MethodKind.LLM_SCHEMA,
|
| 76 |
+
evaluated=False,
|
| 77 |
+
version="hub-card",
|
| 78 |
+
license="see model card",
|
| 79 |
+
reason_if_skipped="API optional and disabled. Not evaluated.",
|
| 80 |
+
),
|
| 81 |
+
MethodSpec(
|
| 82 |
+
method_id="zai-org/GLM-5.3",
|
| 83 |
+
display_name="GLM 5.3",
|
| 84 |
+
kind=MethodKind.LLM_SCHEMA,
|
| 85 |
+
evaluated=False,
|
| 86 |
+
version="hub-card",
|
| 87 |
+
license="see model card",
|
| 88 |
+
reason_if_skipped="API optional and disabled. Not evaluated.",
|
| 89 |
+
),
|
| 90 |
+
MethodSpec(
|
| 91 |
+
method_id="deepseek-ai/DeepSeek-V4.1-Flash",
|
| 92 |
+
display_name="DeepSeek V4.1 Flash",
|
| 93 |
+
kind=MethodKind.LLM_SCHEMA,
|
| 94 |
+
evaluated=False,
|
| 95 |
+
version="hub-card",
|
| 96 |
+
license="see model card",
|
| 97 |
+
reason_if_skipped="API optional and disabled. Not evaluated.",
|
| 98 |
+
),
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def all_methods() -> list[MethodSpec]:
|
| 103 |
+
return list(EVALUATED_METHODS) + list(UNEVALUATED_MODELS)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def evaluated_ids() -> list[str]:
|
| 107 |
+
return [item.method_id for item in EVALUATED_METHODS]
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def method_by_id(method_id: str) -> MethodSpec | None:
|
| 111 |
+
for item in all_methods():
|
| 112 |
+
if item.method_id == method_id:
|
| 113 |
+
return item
|
| 114 |
+
return None
|
demo/src/optimizer.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import time
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
|
| 6 |
+
from ortools.sat.python import cp_model
|
| 7 |
+
|
| 8 |
+
from src.domain import (
|
| 9 |
+
AssignmentInstance,
|
| 10 |
+
AssignmentRow,
|
| 11 |
+
Family,
|
| 12 |
+
InventoryInstance,
|
| 13 |
+
InventoryOrder,
|
| 14 |
+
ScheduleInstance,
|
| 15 |
+
ScheduleStart,
|
| 16 |
+
Solution,
|
| 17 |
+
SolveStatus,
|
| 18 |
+
parse_instance,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class SolverOutcome:
|
| 24 |
+
solution: Solution
|
| 25 |
+
seconds: float
|
| 26 |
+
solver_name: str
|
| 27 |
+
message: str
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _status(model_status: int) -> SolveStatus:
|
| 31 |
+
if model_status == cp_model.OPTIMAL:
|
| 32 |
+
return SolveStatus.OPTIMAL
|
| 33 |
+
if model_status == cp_model.FEASIBLE:
|
| 34 |
+
return SolveStatus.FEASIBLE
|
| 35 |
+
if model_status == cp_model.INFEASIBLE:
|
| 36 |
+
return SolveStatus.INFEASIBLE
|
| 37 |
+
if model_status in {cp_model.UNKNOWN, cp_model.MODEL_INVALID}:
|
| 38 |
+
return SolveStatus.TIMEOUT
|
| 39 |
+
return SolveStatus.ERROR
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _status_name(model_status: int) -> str:
|
| 43 |
+
names = {
|
| 44 |
+
cp_model.OPTIMAL: "OPTIMAL",
|
| 45 |
+
cp_model.FEASIBLE: "FEASIBLE",
|
| 46 |
+
cp_model.INFEASIBLE: "INFEASIBLE",
|
| 47 |
+
cp_model.UNKNOWN: "UNKNOWN",
|
| 48 |
+
cp_model.MODEL_INVALID: "MODEL_INVALID",
|
| 49 |
+
}
|
| 50 |
+
return names.get(model_status, str(model_status))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def solve_inventory(instance: InventoryInstance, seconds: float, threads: int = 1) -> SolverOutcome:
|
| 54 |
+
started = time.perf_counter()
|
| 55 |
+
model = cp_model.CpModel()
|
| 56 |
+
periods = instance.periods
|
| 57 |
+
skus = instance.skus
|
| 58 |
+
order: dict[tuple[str, int], cp_model.IntVar] = {}
|
| 59 |
+
inv: dict[tuple[str, int], cp_model.IntVar] = {}
|
| 60 |
+
short: dict[tuple[str, int], cp_model.IntVar] = {}
|
| 61 |
+
sold: dict[tuple[str, int], cp_model.IntVar] = {}
|
| 62 |
+
|
| 63 |
+
max_demand = max((max(sku.demand) for sku in skus), default=1)
|
| 64 |
+
max_pack = max((sku.pack_size for sku in skus), default=1)
|
| 65 |
+
max_order = max(max_demand * periods + max_pack * 4, 1)
|
| 66 |
+
|
| 67 |
+
for sku in skus:
|
| 68 |
+
for t in range(1, periods + 1):
|
| 69 |
+
packs = model.NewIntVar(0, max_order // sku.pack_size + 1, f"packs_{sku.sku_id}_{t}")
|
| 70 |
+
qty = model.NewIntVar(0, max_order, f"ord_{sku.sku_id}_{t}")
|
| 71 |
+
model.Add(qty == packs * sku.pack_size)
|
| 72 |
+
order[(sku.sku_id, t)] = qty
|
| 73 |
+
inv[(sku.sku_id, t)] = model.NewIntVar(0, instance.warehouse_capacity, f"inv_{sku.sku_id}_{t}")
|
| 74 |
+
demand = int(sku.demand[t - 1])
|
| 75 |
+
short[(sku.sku_id, t)] = model.NewIntVar(0, demand, f"sh_{sku.sku_id}_{t}")
|
| 76 |
+
sold[(sku.sku_id, t)] = model.NewIntVar(0, demand, f"sd_{sku.sku_id}_{t}")
|
| 77 |
+
prev = sku.initial_stock if t == 1 else inv[(sku.sku_id, t - 1)]
|
| 78 |
+
model.Add(inv[(sku.sku_id, t)] + sold[(sku.sku_id, t)] == prev + qty)
|
| 79 |
+
model.Add(sold[(sku.sku_id, t)] + short[(sku.sku_id, t)] == demand)
|
| 80 |
+
if instance.cover_required:
|
| 81 |
+
model.Add(short[(sku.sku_id, t)] == 0)
|
| 82 |
+
|
| 83 |
+
for t in range(1, periods + 1):
|
| 84 |
+
model.Add(sum(inv[(sku.sku_id, t)] for sku in skus) <= instance.warehouse_capacity)
|
| 85 |
+
|
| 86 |
+
model.Add(
|
| 87 |
+
sum(sku.unit_cost * order[(sku.sku_id, t)] for sku in skus for t in range(1, periods + 1)) <= instance.budget
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
objective = []
|
| 91 |
+
for sku in skus:
|
| 92 |
+
for t in range(1, periods + 1):
|
| 93 |
+
objective.append(sku.unit_cost * order[(sku.sku_id, t)])
|
| 94 |
+
objective.append(sku.holding_cost * inv[(sku.sku_id, t)])
|
| 95 |
+
objective.append(sku.shortage_cost * short[(sku.sku_id, t)])
|
| 96 |
+
model.Minimize(sum(objective))
|
| 97 |
+
|
| 98 |
+
solver = cp_model.CpSolver()
|
| 99 |
+
solver.parameters.max_time_in_seconds = float(seconds)
|
| 100 |
+
solver.parameters.num_search_workers = int(threads)
|
| 101 |
+
raw = solver.Solve(model)
|
| 102 |
+
status = _status(raw)
|
| 103 |
+
elapsed = time.perf_counter() - started
|
| 104 |
+
message = _status_name(raw)
|
| 105 |
+
if status in {SolveStatus.OPTIMAL, SolveStatus.FEASIBLE}:
|
| 106 |
+
orders = [
|
| 107 |
+
InventoryOrder(sku_id=sku.sku_id, period=t, qty=int(solver.Value(order[(sku.sku_id, t)])))
|
| 108 |
+
for sku in skus
|
| 109 |
+
for t in range(1, periods + 1)
|
| 110 |
+
]
|
| 111 |
+
obj = float(solver.ObjectiveValue())
|
| 112 |
+
bound = float(solver.BestObjectiveBound()) if status == SolveStatus.FEASIBLE else obj
|
| 113 |
+
return SolverOutcome(
|
| 114 |
+
Solution(
|
| 115 |
+
family=Family.INVENTORY,
|
| 116 |
+
status=status,
|
| 117 |
+
objective=obj,
|
| 118 |
+
bound=bound,
|
| 119 |
+
orders=orders,
|
| 120 |
+
message=message,
|
| 121 |
+
),
|
| 122 |
+
elapsed,
|
| 123 |
+
"ortools-cpsat",
|
| 124 |
+
message,
|
| 125 |
+
)
|
| 126 |
+
return SolverOutcome(
|
| 127 |
+
Solution(family=Family.INVENTORY, status=status, message=message),
|
| 128 |
+
elapsed,
|
| 129 |
+
"ortools-cpsat",
|
| 130 |
+
message,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def solve_assignment(instance: AssignmentInstance, seconds: float, threads: int = 1) -> SolverOutcome:
|
| 135 |
+
started = time.perf_counter()
|
| 136 |
+
model = cp_model.CpModel()
|
| 137 |
+
x: dict[tuple[str, str], cp_model.IntVar] = {}
|
| 138 |
+
costs = instance.cost_map()
|
| 139 |
+
for task in instance.tasks:
|
| 140 |
+
for agent in instance.agents:
|
| 141 |
+
if instance.eligible(task, agent) and (task.task_id, agent.agent_id) in costs:
|
| 142 |
+
x[(task.task_id, agent.agent_id)] = model.NewBoolVar(f"x_{task.task_id}_{agent.agent_id}")
|
| 143 |
+
|
| 144 |
+
unassigned: dict[str, cp_model.IntVar] = {}
|
| 145 |
+
for task in instance.tasks:
|
| 146 |
+
assigned = [x[(task.task_id, agent.agent_id)] for agent in instance.agents if (task.task_id, agent.agent_id) in x]
|
| 147 |
+
miss = model.NewBoolVar(f"u_{task.task_id}")
|
| 148 |
+
unassigned[task.task_id] = miss
|
| 149 |
+
model.Add(sum(assigned) + miss == 1)
|
| 150 |
+
if task.required:
|
| 151 |
+
model.Add(miss == 0)
|
| 152 |
+
|
| 153 |
+
for agent in instance.agents:
|
| 154 |
+
load = [
|
| 155 |
+
task.size * x[(task.task_id, agent.agent_id)]
|
| 156 |
+
for task in instance.tasks
|
| 157 |
+
if (task.task_id, agent.agent_id) in x
|
| 158 |
+
]
|
| 159 |
+
if load:
|
| 160 |
+
model.Add(sum(load) <= agent.capacity)
|
| 161 |
+
|
| 162 |
+
obj_terms = []
|
| 163 |
+
for (task_id, agent_id), var in x.items():
|
| 164 |
+
obj_terms.append(costs[(task_id, agent_id)] * var)
|
| 165 |
+
for task in instance.tasks:
|
| 166 |
+
obj_terms.append(task.penalty * unassigned[task.task_id])
|
| 167 |
+
model.Minimize(sum(obj_terms) if obj_terms else 0)
|
| 168 |
+
|
| 169 |
+
solver = cp_model.CpSolver()
|
| 170 |
+
solver.parameters.max_time_in_seconds = float(seconds)
|
| 171 |
+
solver.parameters.num_search_workers = int(threads)
|
| 172 |
+
raw = solver.Solve(model)
|
| 173 |
+
status = _status(raw)
|
| 174 |
+
elapsed = time.perf_counter() - started
|
| 175 |
+
message = _status_name(raw)
|
| 176 |
+
if status in {SolveStatus.OPTIMAL, SolveStatus.FEASIBLE}:
|
| 177 |
+
rows = [
|
| 178 |
+
AssignmentRow(task_id=task_id, agent_id=agent_id)
|
| 179 |
+
for (task_id, agent_id), var in x.items()
|
| 180 |
+
if solver.Value(var)
|
| 181 |
+
]
|
| 182 |
+
leftover = [task_id for task_id, var in unassigned.items() if solver.Value(var)]
|
| 183 |
+
obj = float(solver.ObjectiveValue())
|
| 184 |
+
bound = float(solver.BestObjectiveBound()) if status == SolveStatus.FEASIBLE else obj
|
| 185 |
+
return SolverOutcome(
|
| 186 |
+
Solution(
|
| 187 |
+
family=Family.ASSIGNMENT,
|
| 188 |
+
status=status,
|
| 189 |
+
objective=obj,
|
| 190 |
+
bound=bound,
|
| 191 |
+
assignments=rows,
|
| 192 |
+
unassigned=leftover,
|
| 193 |
+
message=message,
|
| 194 |
+
),
|
| 195 |
+
elapsed,
|
| 196 |
+
"ortools-cpsat",
|
| 197 |
+
message,
|
| 198 |
+
)
|
| 199 |
+
return SolverOutcome(
|
| 200 |
+
Solution(family=Family.ASSIGNMENT, status=status, message=message),
|
| 201 |
+
elapsed,
|
| 202 |
+
"ortools-cpsat",
|
| 203 |
+
message,
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def solve_scheduling(instance: ScheduleInstance, seconds: float, threads: int = 1) -> SolverOutcome:
|
| 208 |
+
started = time.perf_counter()
|
| 209 |
+
model = cp_model.CpModel()
|
| 210 |
+
horizon = max(instance.horizon, sum(job.duration for job in instance.jobs) + max((job.release for job in instance.jobs), default=0) + 2)
|
| 211 |
+
intervals_by_machine: dict[str, list] = {machine: [] for machine in instance.machines}
|
| 212 |
+
start: dict[str, cp_model.IntVar] = {}
|
| 213 |
+
end: dict[str, cp_model.IntVar] = {}
|
| 214 |
+
tardy: dict[str, cp_model.IntVar] = {}
|
| 215 |
+
assign: dict[tuple[str, str], cp_model.IntVar] = {}
|
| 216 |
+
|
| 217 |
+
for job in instance.jobs:
|
| 218 |
+
start[job.job_id] = model.NewIntVar(job.release, horizon, f"s_{job.job_id}")
|
| 219 |
+
end[job.job_id] = model.NewIntVar(job.release + job.duration, horizon + job.duration, f"e_{job.job_id}")
|
| 220 |
+
model.Add(end[job.job_id] == start[job.job_id] + job.duration)
|
| 221 |
+
tardy[job.job_id] = model.NewIntVar(0, horizon + job.duration, f"tard_{job.job_id}")
|
| 222 |
+
model.Add(tardy[job.job_id] >= end[job.job_id] - job.due)
|
| 223 |
+
if job.hard_due:
|
| 224 |
+
model.Add(end[job.job_id] <= job.due)
|
| 225 |
+
eligible = [machine for machine in instance.machines if machine in set(job.machine_eligible)]
|
| 226 |
+
if not eligible:
|
| 227 |
+
eligible = list(instance.machines)
|
| 228 |
+
machine_bools = []
|
| 229 |
+
for machine in eligible:
|
| 230 |
+
flag = model.NewBoolVar(f"m_{job.job_id}_{machine}")
|
| 231 |
+
assign[(job.job_id, machine)] = flag
|
| 232 |
+
interval = model.NewOptionalIntervalVar(start[job.job_id], job.duration, end[job.job_id], flag, f"iv_{job.job_id}_{machine}")
|
| 233 |
+
intervals_by_machine[machine].append(interval)
|
| 234 |
+
machine_bools.append(flag)
|
| 235 |
+
model.AddExactlyOne(machine_bools)
|
| 236 |
+
|
| 237 |
+
for machine, intervals in intervals_by_machine.items():
|
| 238 |
+
if intervals:
|
| 239 |
+
model.AddNoOverlap(intervals)
|
| 240 |
+
|
| 241 |
+
job_ids = {job.job_id for job in instance.jobs}
|
| 242 |
+
for edge in instance.precedences:
|
| 243 |
+
if edge.before in job_ids and edge.after in job_ids:
|
| 244 |
+
model.Add(end[edge.before] <= start[edge.after])
|
| 245 |
+
|
| 246 |
+
makespan = model.NewIntVar(0, horizon + 8, "makespan")
|
| 247 |
+
for job in instance.jobs:
|
| 248 |
+
model.Add(makespan >= end[job.job_id])
|
| 249 |
+
model.Minimize(sum(job.weight * tardy[job.job_id] for job in instance.jobs) * 100 + makespan)
|
| 250 |
+
|
| 251 |
+
solver = cp_model.CpSolver()
|
| 252 |
+
solver.parameters.max_time_in_seconds = float(seconds)
|
| 253 |
+
solver.parameters.num_search_workers = int(threads)
|
| 254 |
+
raw = solver.Solve(model)
|
| 255 |
+
status = _status(raw)
|
| 256 |
+
elapsed = time.perf_counter() - started
|
| 257 |
+
message = _status_name(raw)
|
| 258 |
+
if status in {SolveStatus.OPTIMAL, SolveStatus.FEASIBLE}:
|
| 259 |
+
starts = []
|
| 260 |
+
for job in instance.jobs:
|
| 261 |
+
machine_id = next(machine for machine in instance.machines if (job.job_id, machine) in assign and solver.Value(assign[(job.job_id, machine)]))
|
| 262 |
+
starts.append(
|
| 263 |
+
ScheduleStart(
|
| 264 |
+
job_id=job.job_id,
|
| 265 |
+
machine_id=machine_id,
|
| 266 |
+
start=int(solver.Value(start[job.job_id])),
|
| 267 |
+
end=int(solver.Value(end[job.job_id])),
|
| 268 |
+
)
|
| 269 |
+
)
|
| 270 |
+
weighted = sum(job.weight * max(0, int(solver.Value(end[job.job_id])) - job.due) for job in instance.jobs)
|
| 271 |
+
obj = float(weighted)
|
| 272 |
+
return SolverOutcome(
|
| 273 |
+
Solution(
|
| 274 |
+
family=Family.SCHEDULING,
|
| 275 |
+
status=status,
|
| 276 |
+
objective=obj,
|
| 277 |
+
bound=obj if status == SolveStatus.OPTIMAL else None,
|
| 278 |
+
starts=starts,
|
| 279 |
+
message=message,
|
| 280 |
+
),
|
| 281 |
+
elapsed,
|
| 282 |
+
"ortools-cpsat",
|
| 283 |
+
message,
|
| 284 |
+
)
|
| 285 |
+
return SolverOutcome(
|
| 286 |
+
Solution(family=Family.SCHEDULING, status=status, message=message),
|
| 287 |
+
elapsed,
|
| 288 |
+
"ortools-cpsat",
|
| 289 |
+
message,
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def solve_instance(family: Family | str, payload: dict, seconds: float, threads: int = 1) -> SolverOutcome:
|
| 294 |
+
family = Family(family)
|
| 295 |
+
instance = parse_instance(family, payload)
|
| 296 |
+
if family == Family.INVENTORY:
|
| 297 |
+
return solve_inventory(instance, seconds, threads)
|
| 298 |
+
if family == Family.ASSIGNMENT:
|
| 299 |
+
return solve_assignment(instance, seconds, threads)
|
| 300 |
+
return solve_scheduling(instance, seconds, threads)
|
demo/src/pipeline.py
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import time
|
| 6 |
+
import uuid
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
from src.baseline import run_heuristic, run_naive
|
| 13 |
+
from src.budget_guard import skip_reason
|
| 14 |
+
from src.domain import (
|
| 15 |
+
CODE_VERSION,
|
| 16 |
+
DEFAULT_SEED,
|
| 17 |
+
DEFAULT_SOLVER_SECONDS,
|
| 18 |
+
PROTOCOL_ID,
|
| 19 |
+
SOLVER_NAME,
|
| 20 |
+
ConstraintConfig,
|
| 21 |
+
EvalRow,
|
| 22 |
+
Family,
|
| 23 |
+
ProblemRecord,
|
| 24 |
+
PromptVariant,
|
| 25 |
+
Solution,
|
| 26 |
+
SolveStatus,
|
| 27 |
+
)
|
| 28 |
+
from src.explain import status_label
|
| 29 |
+
from src.extractor import constraint_fidelity, drop_constraint, extract_json, extract_template
|
| 30 |
+
from src.generator import INTERACTIVE_IDS, generate_catalog, load_catalog
|
| 31 |
+
from src.metrics import row_from_run, skipped_rows, summarize
|
| 32 |
+
from src.model_registry import REGISTRY_VERSION, method_by_id
|
| 33 |
+
from src.optimizer import solve_instance
|
| 34 |
+
from src.validation import format_input_error, validate_schema, validate_solution
|
| 35 |
+
|
| 36 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 37 |
+
CATALOG_PATH = ROOT / "examples" / "problems.jsonl"
|
| 38 |
+
RESULTS_PATH = ROOT / "examples" / "results.jsonl"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _input_hash(payload: dict) -> str:
|
| 42 |
+
raw = json.dumps(payload, sort_keys=True, ensure_ascii=False)
|
| 43 |
+
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def load_problems(path: Path | None = None) -> list[ProblemRecord]:
|
| 47 |
+
return load_catalog(path or CATALOG_PATH if (path or CATALOG_PATH).exists() else None)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def load_results(path: Path | None = None) -> pd.DataFrame:
|
| 51 |
+
target = path or RESULTS_PATH
|
| 52 |
+
if not target.exists():
|
| 53 |
+
return pd.DataFrame()
|
| 54 |
+
rows = [json.loads(line) for line in target.read_text(encoding="utf-8").splitlines() if line.strip()]
|
| 55 |
+
return pd.DataFrame(rows)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def interactive_problems(problems: list[ProblemRecord] | None = None) -> list[ProblemRecord]:
|
| 59 |
+
problems = problems or load_problems()
|
| 60 |
+
chosen = [item for item in problems if item.interactive]
|
| 61 |
+
if len(chosen) < 5:
|
| 62 |
+
chosen = problems[:20]
|
| 63 |
+
return chosen
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def problem_by_id(problem_id: str, problems: list[ProblemRecord] | None = None) -> ProblemRecord:
|
| 67 |
+
problems = problems or load_problems()
|
| 68 |
+
for item in problems:
|
| 69 |
+
if item.problem_id == problem_id:
|
| 70 |
+
return item
|
| 71 |
+
raise KeyError(problem_id)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _prompt_for(problem: ProblemRecord, lang: str, variant: PromptVariant) -> str:
|
| 75 |
+
if variant == PromptVariant.JSON:
|
| 76 |
+
return problem.prompt_json
|
| 77 |
+
text = problem.prompt_fa if lang == "fa" else problem.prompt_en
|
| 78 |
+
if variant == PromptVariant.MISSING_BUDGET:
|
| 79 |
+
_, text = drop_constraint(problem.family, problem.schema_payload, text)
|
| 80 |
+
return text
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _evaluate_solver(problem: ProblemRecord, payload: dict, seconds: float, threads: int, method_id: str, method_kind: str, parse_success: bool | None, fidelity: float | None, notes: str) -> EvalRow:
|
| 84 |
+
schema = validate_schema(problem.family, payload)
|
| 85 |
+
if not schema.ok:
|
| 86 |
+
return row_from_run(
|
| 87 |
+
problem,
|
| 88 |
+
method_id,
|
| 89 |
+
method_kind,
|
| 90 |
+
False if parse_success is None else parse_success,
|
| 91 |
+
fidelity,
|
| 92 |
+
SolveStatus.INVALID.value,
|
| 93 |
+
False,
|
| 94 |
+
None,
|
| 95 |
+
0.0,
|
| 96 |
+
schema.failed_codes(),
|
| 97 |
+
format_input_error(schema),
|
| 98 |
+
)
|
| 99 |
+
outcome = solve_instance(problem.family, payload, seconds=seconds, threads=threads)
|
| 100 |
+
solution = outcome.solution
|
| 101 |
+
if solution.status == SolveStatus.INFEASIBLE:
|
| 102 |
+
feasible = False
|
| 103 |
+
violated: list[str] = ["infeasible"]
|
| 104 |
+
objective = None
|
| 105 |
+
report_notes = solution.message
|
| 106 |
+
elif solution.status in {SolveStatus.TIMEOUT, SolveStatus.ERROR}:
|
| 107 |
+
feasible = None
|
| 108 |
+
violated = [solution.status.value]
|
| 109 |
+
objective = None
|
| 110 |
+
report_notes = solution.message
|
| 111 |
+
else:
|
| 112 |
+
report = validate_solution(problem.family, payload, solution)
|
| 113 |
+
feasible = report.ok
|
| 114 |
+
violated = report.failed_codes()
|
| 115 |
+
objective = report.recomputed_objective if report.recomputed_objective is not None else solution.objective
|
| 116 |
+
report_notes = notes or solution.message
|
| 117 |
+
if not report.ok:
|
| 118 |
+
solution.status = SolveStatus.INVALID
|
| 119 |
+
return row_from_run(
|
| 120 |
+
problem,
|
| 121 |
+
method_id,
|
| 122 |
+
method_kind,
|
| 123 |
+
True if parse_success is None else parse_success,
|
| 124 |
+
fidelity,
|
| 125 |
+
solution.status.value,
|
| 126 |
+
feasible,
|
| 127 |
+
objective,
|
| 128 |
+
outcome.seconds,
|
| 129 |
+
violated,
|
| 130 |
+
report_notes,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _evaluate_direct(problem: ProblemRecord, payload: dict, solution: Solution, seconds: float, method_id: str, notes: str) -> EvalRow:
|
| 135 |
+
report = validate_solution(problem.family, payload, solution)
|
| 136 |
+
return row_from_run(
|
| 137 |
+
problem,
|
| 138 |
+
method_id,
|
| 139 |
+
"direct-answer",
|
| 140 |
+
True,
|
| 141 |
+
1.0,
|
| 142 |
+
SolveStatus.HEURISTIC.value if report.ok else SolveStatus.INVALID.value,
|
| 143 |
+
report.ok,
|
| 144 |
+
report.recomputed_objective,
|
| 145 |
+
seconds,
|
| 146 |
+
report.failed_codes(),
|
| 147 |
+
notes,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def evaluate_problem(
|
| 152 |
+
problem: ProblemRecord,
|
| 153 |
+
lang: str = "en",
|
| 154 |
+
variant: PromptVariant | str = PromptVariant.TEMPLATE,
|
| 155 |
+
config: ConstraintConfig | None = None,
|
| 156 |
+
custom_text: str | None = None,
|
| 157 |
+
custom_schema: dict | None = None,
|
| 158 |
+
custom_solution: dict | None = None,
|
| 159 |
+
) -> dict[str, Any]:
|
| 160 |
+
started = time.perf_counter()
|
| 161 |
+
config = config or ConstraintConfig()
|
| 162 |
+
variant = PromptVariant(variant)
|
| 163 |
+
prompt = custom_text if custom_text else _prompt_for(problem, lang, variant)
|
| 164 |
+
payload = custom_schema or problem.schema_payload
|
| 165 |
+
rows: list[EvalRow] = []
|
| 166 |
+
|
| 167 |
+
structured_payload = payload
|
| 168 |
+
rows.append(
|
| 169 |
+
_evaluate_solver(
|
| 170 |
+
problem,
|
| 171 |
+
structured_payload,
|
| 172 |
+
config.solver_seconds,
|
| 173 |
+
config.threads,
|
| 174 |
+
"structured-solver",
|
| 175 |
+
"structured-solver",
|
| 176 |
+
True,
|
| 177 |
+
1.0,
|
| 178 |
+
"schema entered the solver without an LLM",
|
| 179 |
+
)
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
heuristic = run_heuristic(problem.family, payload)
|
| 183 |
+
heur_report = validate_solution(problem.family, payload, heuristic.solution)
|
| 184 |
+
rows.append(
|
| 185 |
+
row_from_run(
|
| 186 |
+
problem,
|
| 187 |
+
"heuristic",
|
| 188 |
+
"heuristic",
|
| 189 |
+
True,
|
| 190 |
+
1.0,
|
| 191 |
+
SolveStatus.HEURISTIC.value if heur_report.ok else SolveStatus.INVALID.value,
|
| 192 |
+
heur_report.ok,
|
| 193 |
+
heur_report.recomputed_objective,
|
| 194 |
+
heuristic.seconds,
|
| 195 |
+
heur_report.failed_codes(),
|
| 196 |
+
heuristic.message,
|
| 197 |
+
)
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
json_payload = extract_json(prompt) or extract_json(problem.prompt_json)
|
| 201 |
+
json_ok = json_payload is not None
|
| 202 |
+
json_fid = constraint_fidelity(problem.family, problem.schema_payload, json_payload)
|
| 203 |
+
if json_ok:
|
| 204 |
+
rows.append(
|
| 205 |
+
_evaluate_solver(
|
| 206 |
+
problem,
|
| 207 |
+
json_payload,
|
| 208 |
+
config.solver_seconds,
|
| 209 |
+
config.threads,
|
| 210 |
+
"json-extractor+solver",
|
| 211 |
+
"text-to-schema",
|
| 212 |
+
True,
|
| 213 |
+
json_fid,
|
| 214 |
+
"JSON extracted from the prompt",
|
| 215 |
+
)
|
| 216 |
+
)
|
| 217 |
+
else:
|
| 218 |
+
rows.append(
|
| 219 |
+
row_from_run(
|
| 220 |
+
problem,
|
| 221 |
+
"json-extractor+solver",
|
| 222 |
+
"text-to-schema",
|
| 223 |
+
False,
|
| 224 |
+
0.0,
|
| 225 |
+
SolveStatus.INVALID.value,
|
| 226 |
+
False,
|
| 227 |
+
None,
|
| 228 |
+
0.0,
|
| 229 |
+
["parse"],
|
| 230 |
+
"no JSON object found",
|
| 231 |
+
)
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
tmpl_payload = extract_template(prompt, problem.family)
|
| 235 |
+
tmpl_ok = tmpl_payload is not None
|
| 236 |
+
tmpl_fid = constraint_fidelity(problem.family, problem.schema_payload, tmpl_payload)
|
| 237 |
+
if tmpl_ok:
|
| 238 |
+
rows.append(
|
| 239 |
+
_evaluate_solver(
|
| 240 |
+
problem,
|
| 241 |
+
tmpl_payload,
|
| 242 |
+
config.solver_seconds,
|
| 243 |
+
config.threads,
|
| 244 |
+
"template-extractor+solver",
|
| 245 |
+
"text-to-schema",
|
| 246 |
+
True,
|
| 247 |
+
tmpl_fid,
|
| 248 |
+
"labeled fields or SCHEMA_BEGIN block",
|
| 249 |
+
)
|
| 250 |
+
)
|
| 251 |
+
else:
|
| 252 |
+
rows.append(
|
| 253 |
+
row_from_run(
|
| 254 |
+
problem,
|
| 255 |
+
"template-extractor+solver",
|
| 256 |
+
"text-to-schema",
|
| 257 |
+
False,
|
| 258 |
+
0.0,
|
| 259 |
+
SolveStatus.INVALID.value,
|
| 260 |
+
False,
|
| 261 |
+
None,
|
| 262 |
+
0.0,
|
| 263 |
+
["parse"],
|
| 264 |
+
"template extractor found no labeled schema",
|
| 265 |
+
)
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
naive = run_naive(problem.family, payload)
|
| 269 |
+
rows.append(_evaluate_direct(problem, payload, naive.solution, naive.seconds, "naive-direct", naive.message))
|
| 270 |
+
|
| 271 |
+
if custom_solution:
|
| 272 |
+
try:
|
| 273 |
+
proposed = Solution.model_validate(custom_solution)
|
| 274 |
+
rows.append(_evaluate_direct(problem, payload, proposed, 0.0, "user-direct", "user-supplied direct answer"))
|
| 275 |
+
except Exception as exc:
|
| 276 |
+
rows.append(
|
| 277 |
+
row_from_run(
|
| 278 |
+
problem,
|
| 279 |
+
"user-direct",
|
| 280 |
+
"direct-answer",
|
| 281 |
+
True,
|
| 282 |
+
1.0,
|
| 283 |
+
SolveStatus.INVALID.value,
|
| 284 |
+
False,
|
| 285 |
+
None,
|
| 286 |
+
0.0,
|
| 287 |
+
["schema"],
|
| 288 |
+
f"direct answer rejected: {exc}",
|
| 289 |
+
)
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
rows.extend(skipped_rows(problem))
|
| 293 |
+
structured = next(row for row in rows if row.method_id == "structured-solver")
|
| 294 |
+
report = None
|
| 295 |
+
live_solution = None
|
| 296 |
+
if structured.status in {SolveStatus.OPTIMAL.value, SolveStatus.FEASIBLE.value, SolveStatus.HEURISTIC.value}:
|
| 297 |
+
live = solve_instance(problem.family, structured_payload, seconds=config.solver_seconds, threads=config.threads)
|
| 298 |
+
live_solution = live.solution
|
| 299 |
+
report = validate_solution(problem.family, structured_payload, live.solution)
|
| 300 |
+
|
| 301 |
+
elapsed = time.perf_counter() - started
|
| 302 |
+
run_id = f"orbench-{uuid.uuid4().hex[:10]}"
|
| 303 |
+
table = pd.DataFrame([row.model_dump() for row in rows])
|
| 304 |
+
return {
|
| 305 |
+
"run_id": run_id,
|
| 306 |
+
"error": None,
|
| 307 |
+
"problem": problem,
|
| 308 |
+
"prompt": prompt,
|
| 309 |
+
"variant": variant.value,
|
| 310 |
+
"schema": structured_payload,
|
| 311 |
+
"rows": rows,
|
| 312 |
+
"table": table,
|
| 313 |
+
"summary": summarize(rows),
|
| 314 |
+
"solution": live_solution.as_dict() if live_solution else {},
|
| 315 |
+
"validation": report,
|
| 316 |
+
"status": structured.status,
|
| 317 |
+
"status_label": status_label(structured.status, lang),
|
| 318 |
+
"seconds": elapsed,
|
| 319 |
+
"report": build_report(run_id, problem, rows, structured_payload, elapsed, lang, variant.value),
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def build_report(run_id: str, problem: ProblemRecord, rows: list[EvalRow], payload: dict, seconds: float, lang: str, variant: str) -> dict[str, Any]:
|
| 324 |
+
return {
|
| 325 |
+
"run_id": run_id,
|
| 326 |
+
"protocol_id": PROTOCOL_ID,
|
| 327 |
+
"code_version": CODE_VERSION,
|
| 328 |
+
"registry_version": REGISTRY_VERSION,
|
| 329 |
+
"solver_version": SOLVER_NAME,
|
| 330 |
+
"input_hash": _input_hash(payload),
|
| 331 |
+
"seed": problem.seed,
|
| 332 |
+
"problem_id": problem.problem_id,
|
| 333 |
+
"family": problem.family.value,
|
| 334 |
+
"split": problem.split.value,
|
| 335 |
+
"language": lang,
|
| 336 |
+
"prompt_variant": variant,
|
| 337 |
+
"gold_status": problem.gold_status,
|
| 338 |
+
"gold_objective": problem.gold_objective,
|
| 339 |
+
"seconds": seconds,
|
| 340 |
+
"budget_note": skip_reason(),
|
| 341 |
+
"rows": [row.model_dump() for row in rows],
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def evaluate_catalog(
|
| 346 |
+
problems: list[ProblemRecord] | None = None,
|
| 347 |
+
config: ConstraintConfig | None = None,
|
| 348 |
+
lang: str = "en",
|
| 349 |
+
) -> list[EvalRow]:
|
| 350 |
+
problems = problems or generate_catalog(DEFAULT_SEED)
|
| 351 |
+
config = config or ConstraintConfig(solver_seconds=DEFAULT_SOLVER_SECONDS)
|
| 352 |
+
rows: list[EvalRow] = []
|
| 353 |
+
for problem in problems:
|
| 354 |
+
result = evaluate_problem(problem, lang=problem.language, config=config)
|
| 355 |
+
for row in result["rows"]:
|
| 356 |
+
row.precomputed = True
|
| 357 |
+
rows.append(row)
|
| 358 |
+
return rows
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def result_to_downloads(result: dict[str, Any], folder: Path) -> dict[str, str]:
|
| 362 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 363 |
+
run_id = result["run_id"]
|
| 364 |
+
files = {}
|
| 365 |
+
table: pd.DataFrame = result["table"]
|
| 366 |
+
csv_path = folder / f"{run_id}_comparison.csv"
|
| 367 |
+
table.to_csv(csv_path, index=False)
|
| 368 |
+
files["comparison"] = str(csv_path)
|
| 369 |
+
report_path = folder / f"{run_id}_report.json"
|
| 370 |
+
report_path.write_text(json.dumps(result["report"], indent=2, ensure_ascii=False), encoding="utf-8")
|
| 371 |
+
files["report"] = str(report_path)
|
| 372 |
+
if result.get("summary") is not None and len(result["summary"]):
|
| 373 |
+
summary_path = folder / f"{run_id}_summary.csv"
|
| 374 |
+
result["summary"].to_csv(summary_path, index=False)
|
| 375 |
+
files["summary"] = str(summary_path)
|
| 376 |
+
schema_path = folder / f"{run_id}_schema.json"
|
| 377 |
+
schema_path.write_text(json.dumps(result["schema"], indent=2, ensure_ascii=False), encoding="utf-8")
|
| 378 |
+
files["schema"] = str(schema_path)
|
| 379 |
+
return files
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def load_sample() -> dict[str, Any]:
|
| 383 |
+
problems = load_problems()
|
| 384 |
+
sample = next((item for item in problems if item.problem_id == INTERACTIVE_IDS[0]), problems[0])
|
| 385 |
+
return {"problem": sample, "problems": problems}
|
demo/src/plots.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import plotly.graph_objects as go
|
| 5 |
+
|
| 6 |
+
from src.domain import Family, not_evaluated_cell
|
| 7 |
+
from src.i18n import t
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def empty_plot(title: str = "—") -> go.Figure:
|
| 11 |
+
fig = go.Figure()
|
| 12 |
+
fig.update_layout(template="plotly_white", height=380, title=title, margin=dict(l=40, r=20, t=50, b=40))
|
| 13 |
+
return fig
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def kpi_html(kpis: dict, lang: str = "en") -> str:
|
| 17 |
+
gap = kpis.get("heuristic_gap")
|
| 18 |
+
fidelity = kpis.get("template_fidelity")
|
| 19 |
+
cards = [
|
| 20 |
+
(t(lang, "kpi_n"), f"{kpis.get('n_problems', 0):.0f}", t(lang, "kpi_n_sub")),
|
| 21 |
+
(t(lang, "kpi_feas"), f"{100 * float(kpis.get('structured_feasible') or 0):.0f}%", t(lang, "kpi_feas_sub")),
|
| 22 |
+
(t(lang, "kpi_gap"), "—" if gap is None else f"{100 * float(gap):.1f}%", t(lang, "kpi_gap_sub")),
|
| 23 |
+
(t(lang, "kpi_fid"), "—" if fidelity is None else f"{100 * float(fidelity):.0f}%", t(lang, "kpi_fid_sub")),
|
| 24 |
+
(t(lang, "kpi_eval"), f"{kpis.get('n_methods_evaluated', 0):.0f}/{kpis.get('n_methods_listed', 0):.0f}", t(lang, "kpi_eval_sub")),
|
| 25 |
+
]
|
| 26 |
+
blocks = []
|
| 27 |
+
for label, value, sub in cards:
|
| 28 |
+
blocks.append(
|
| 29 |
+
f"<article class='kpi-card'><p class='kpi-label'>{label}</p>"
|
| 30 |
+
f"<p class='kpi-value'>{value}</p><p class='kpi-sub'>{sub}</p></article>"
|
| 31 |
+
)
|
| 32 |
+
return f"<div class='kpi-grid'>{''.join(blocks)}</div>"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def method_bars(summary: pd.DataFrame, title: str) -> go.Figure:
|
| 36 |
+
if summary is None or summary.empty:
|
| 37 |
+
return empty_plot(title)
|
| 38 |
+
live = summary.loc[summary["evaluated"] == True] # noqa: E712
|
| 39 |
+
if live.empty:
|
| 40 |
+
return empty_plot(title)
|
| 41 |
+
fig = go.Figure()
|
| 42 |
+
fig.add_bar(name="feasible", x=live["method_id"], y=live["feasible_rate"].fillna(0))
|
| 43 |
+
fig.add_bar(name="parse", x=live["method_id"], y=live["parse_rate"].fillna(0))
|
| 44 |
+
fig.update_layout(
|
| 45 |
+
template="plotly_white",
|
| 46 |
+
barmode="group",
|
| 47 |
+
height=400,
|
| 48 |
+
title=title,
|
| 49 |
+
yaxis=dict(range=[0, 1], title="rate"),
|
| 50 |
+
legend=dict(orientation="h"),
|
| 51 |
+
margin=dict(l=40, r=20, t=50, b=80),
|
| 52 |
+
)
|
| 53 |
+
return fig
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def family_bars(family_tbl: pd.DataFrame, title: str) -> go.Figure:
|
| 57 |
+
if family_tbl is None or family_tbl.empty:
|
| 58 |
+
return empty_plot(title)
|
| 59 |
+
fig = go.Figure()
|
| 60 |
+
for method_id, group in family_tbl.groupby("method_id"):
|
| 61 |
+
fig.add_bar(name=str(method_id), x=group["family"], y=group["feasible_rate"].fillna(0))
|
| 62 |
+
fig.update_layout(
|
| 63 |
+
template="plotly_white",
|
| 64 |
+
barmode="group",
|
| 65 |
+
height=400,
|
| 66 |
+
title=title,
|
| 67 |
+
yaxis=dict(range=[0, 1], title="feasible rate"),
|
| 68 |
+
legend=dict(orientation="h"),
|
| 69 |
+
margin=dict(l=40, r=20, t=50, b=40),
|
| 70 |
+
)
|
| 71 |
+
return fig
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def schedule_gantt(solution: dict, title: str) -> go.Figure:
|
| 75 |
+
starts = (solution or {}).get("starts") or []
|
| 76 |
+
if not starts:
|
| 77 |
+
return empty_plot(title)
|
| 78 |
+
fig = go.Figure()
|
| 79 |
+
colors = ["#2563eb", "#0f766e", "#7c3aed", "#b45309", "#db2777", "#334155"]
|
| 80 |
+
for idx, row in enumerate(starts):
|
| 81 |
+
fig.add_bar(
|
| 82 |
+
x=[int(row["end"]) - int(row["start"])],
|
| 83 |
+
y=[row["machine_id"]],
|
| 84 |
+
base=[int(row["start"])],
|
| 85 |
+
orientation="h",
|
| 86 |
+
marker_color=colors[idx % len(colors)],
|
| 87 |
+
name=row["job_id"],
|
| 88 |
+
text=row["job_id"],
|
| 89 |
+
textposition="inside",
|
| 90 |
+
hovertemplate=f"{row['job_id']} {row['start']}-{row['end']}<extra></extra>",
|
| 91 |
+
)
|
| 92 |
+
fig.update_layout(template="plotly_white", height=360, title=title, barmode="stack", showlegend=False)
|
| 93 |
+
return fig
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def inventory_orders(solution: dict, title: str) -> go.Figure:
|
| 97 |
+
orders = (solution or {}).get("orders") or []
|
| 98 |
+
if not orders:
|
| 99 |
+
return empty_plot(title)
|
| 100 |
+
frame = pd.DataFrame(orders)
|
| 101 |
+
fig = go.Figure()
|
| 102 |
+
for sku_id, group in frame.groupby("sku_id"):
|
| 103 |
+
fig.add_bar(name=str(sku_id), x=group["period"].astype(str), y=group["qty"])
|
| 104 |
+
fig.update_layout(template="plotly_white", barmode="group", height=360, title=title)
|
| 105 |
+
return fig
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def assignment_table_plot(solution: dict, title: str) -> go.Figure:
|
| 109 |
+
rows = (solution or {}).get("assignments") or []
|
| 110 |
+
if not rows:
|
| 111 |
+
return empty_plot(title)
|
| 112 |
+
fig = go.Figure(
|
| 113 |
+
data=[
|
| 114 |
+
go.Table(
|
| 115 |
+
header=dict(values=["task_id", "agent_id"], fill_color="#e0e7ff"),
|
| 116 |
+
cells=dict(values=[[row["task_id"] for row in rows], [row["agent_id"] for row in rows]]),
|
| 117 |
+
)
|
| 118 |
+
]
|
| 119 |
+
)
|
| 120 |
+
fig.update_layout(template="plotly_white", height=320, title=title)
|
| 121 |
+
return fig
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def solution_plot(family: str, solution: dict, title: str) -> go.Figure:
|
| 125 |
+
if family == Family.SCHEDULING.value:
|
| 126 |
+
return schedule_gantt(solution, title)
|
| 127 |
+
if family == Family.INVENTORY.value:
|
| 128 |
+
return inventory_orders(solution, title)
|
| 129 |
+
return assignment_table_plot(solution, title)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def format_leaderboard(frame: pd.DataFrame) -> pd.DataFrame:
|
| 133 |
+
if frame is None or frame.empty:
|
| 134 |
+
return pd.DataFrame()
|
| 135 |
+
show = frame.copy()
|
| 136 |
+
for col in ("parse_success", "feasible", "constraint_fidelity", "optimality_gap", "objective", "cost_usd"):
|
| 137 |
+
if col in show.columns:
|
| 138 |
+
show[col] = show[col].apply(lambda value: not_evaluated_cell() if pd.isna(value) else value)
|
| 139 |
+
uneval = show["evaluated"] == False # noqa: E712
|
| 140 |
+
if "status" in show.columns:
|
| 141 |
+
show.loc[uneval, "status"] = not_evaluated_cell()
|
| 142 |
+
return show
|
demo/src/ui.py
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import tempfile
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from zipfile import ZipFile
|
| 7 |
+
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import plotly.graph_objects as go
|
| 11 |
+
|
| 12 |
+
from src.domain import DEFAULT_SOLVER_SECONDS, ConstraintConfig, PromptVariant
|
| 13 |
+
from src.explain import numeric_reasons, status_label
|
| 14 |
+
from src.i18n import TEXTS, t
|
| 15 |
+
from src.metrics import family_summary, kpi_snapshot, summarize
|
| 16 |
+
from src.model_registry import all_methods
|
| 17 |
+
from src.pipeline import (
|
| 18 |
+
evaluate_problem,
|
| 19 |
+
interactive_problems,
|
| 20 |
+
load_problems,
|
| 21 |
+
load_results,
|
| 22 |
+
load_sample,
|
| 23 |
+
problem_by_id,
|
| 24 |
+
result_to_downloads,
|
| 25 |
+
)
|
| 26 |
+
from src.plots import empty_plot, family_bars, format_leaderboard, kpi_html, method_bars, solution_plot
|
| 27 |
+
from src.validation import ValidationReport
|
| 28 |
+
|
| 29 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 30 |
+
SAMPLE_PREVIEW = ROOT / "examples" / "sample_preview.json"
|
| 31 |
+
CSS = """
|
| 32 |
+
.gradio-container {max-width: 1280px !important; margin: 0 auto;}
|
| 33 |
+
.dark .gradio-container {color: var(--body-text-color);}
|
| 34 |
+
.aria-header h1 {margin-bottom: 0.2rem;}
|
| 35 |
+
.aria-header p {opacity: 0.85;}
|
| 36 |
+
.kpi-grid {display:grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px;}
|
| 37 |
+
.kpi-card {background: linear-gradient(180deg, #eef2ff, #ffffff); border: 1px solid #c7d2fe; border-radius: 16px; padding: 14px 16px;}
|
| 38 |
+
.kpi-label {font-size: 0.8rem; color: #3730a3; margin: 0;}
|
| 39 |
+
.kpi-value {font-size: 1.55rem; font-weight: 700; color: #312e81; margin: 4px 0;}
|
| 40 |
+
.kpi-sub {margin: 0; font-size: 0.78rem; color: #334155;}
|
| 41 |
+
.rtl-mode {direction: rtl; text-align: right;}
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _preview_payload() -> dict:
|
| 46 |
+
if SAMPLE_PREVIEW.exists():
|
| 47 |
+
return json.loads(SAMPLE_PREVIEW.read_text(encoding="utf-8"))
|
| 48 |
+
return {}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _empty_plot() -> go.Figure:
|
| 52 |
+
return empty_plot("—")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _variant_choices(lang: str) -> list[str]:
|
| 56 |
+
return [t(lang, "template"), t(lang, "json"), t(lang, "missing")]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _parse_variant(value: str) -> PromptVariant:
|
| 60 |
+
if value in {PromptVariant.JSON.value, t("en", "json"), t("fa", "json")}:
|
| 61 |
+
return PromptVariant.JSON
|
| 62 |
+
if value in {PromptVariant.MISSING_BUDGET.value, t("en", "missing"), t("fa", "missing")}:
|
| 63 |
+
return PromptVariant.MISSING_BUDGET
|
| 64 |
+
return PromptVariant.TEMPLATE
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _problem_choices() -> list[str]:
|
| 68 |
+
return [item.problem_id for item in interactive_problems()]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def apply_language(lang: str):
|
| 72 |
+
rtl = lang == "fa"
|
| 73 |
+
preview = _preview_payload()
|
| 74 |
+
header = (
|
| 75 |
+
f"<div class='aria-header {'rtl-mode' if rtl else ''}'>"
|
| 76 |
+
f"<h1>{t(lang, 'title')}</h1><p>{t(lang, 'subtitle')}</p><p>{t(lang, 'kind')}</p></div>"
|
| 77 |
+
)
|
| 78 |
+
return (
|
| 79 |
+
gr.update(value=header),
|
| 80 |
+
gr.update(value=t(lang, "run_sample")),
|
| 81 |
+
gr.update(value=t(lang, "cancel")),
|
| 82 |
+
gr.update(value=t(lang, "reset")),
|
| 83 |
+
gr.update(value=t(lang, "load_sample")),
|
| 84 |
+
gr.update(label=t(lang, "problem")),
|
| 85 |
+
gr.update(label=t(lang, "variant"), choices=_variant_choices(lang), value=_variant_choices(lang)[0]),
|
| 86 |
+
gr.update(label=t(lang, "time_limit")),
|
| 87 |
+
gr.update(value=t(lang, "sample_note")),
|
| 88 |
+
gr.update(value=preview.get("kpi_html", "")),
|
| 89 |
+
gr.update(open=False, label=t(lang, "advanced")),
|
| 90 |
+
gr.update(value=t(lang, "method_body"), rtl=rtl),
|
| 91 |
+
gr.update(value=t(lang, "upload_hint")),
|
| 92 |
+
gr.update(label=t(lang, "custom_text")),
|
| 93 |
+
gr.update(label=t(lang, "custom_schema")),
|
| 94 |
+
gr.update(label=t(lang, "direct_json")),
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _load_problem_fields(problem_id: str):
|
| 99 |
+
problem = problem_by_id(problem_id)
|
| 100 |
+
return (
|
| 101 |
+
problem.prompt_en,
|
| 102 |
+
problem.prompt_fa,
|
| 103 |
+
problem.prompt_json,
|
| 104 |
+
json.dumps(problem.schema_payload, indent=2, ensure_ascii=False),
|
| 105 |
+
problem.gold_status,
|
| 106 |
+
problem.gold_objective,
|
| 107 |
+
problem.family.value,
|
| 108 |
+
problem.split.value,
|
| 109 |
+
problem.difficulty.value,
|
| 110 |
+
problem.language,
|
| 111 |
+
problem.template_id,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def load_sample_ui():
|
| 116 |
+
ids = _problem_choices()
|
| 117 |
+
fields = _load_problem_fields(ids[0])
|
| 118 |
+
return (ids[0], *fields)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def run_live(lang, problem_id, variant, time_limit, custom_text, schema_text, direct_text):
|
| 122 |
+
problem = problem_by_id(problem_id)
|
| 123 |
+
schema = None
|
| 124 |
+
if schema_text and str(schema_text).strip():
|
| 125 |
+
try:
|
| 126 |
+
schema = json.loads(schema_text)
|
| 127 |
+
except json.JSONDecodeError as exc:
|
| 128 |
+
raise gr.Error(f"schema JSON: {exc}") from exc
|
| 129 |
+
direct = None
|
| 130 |
+
if direct_text and str(direct_text).strip():
|
| 131 |
+
try:
|
| 132 |
+
direct = json.loads(direct_text)
|
| 133 |
+
except json.JSONDecodeError as exc:
|
| 134 |
+
raise gr.Error(f"direct-answer JSON: {exc}") from exc
|
| 135 |
+
result = evaluate_problem(
|
| 136 |
+
problem,
|
| 137 |
+
lang=lang,
|
| 138 |
+
variant=_parse_variant(variant),
|
| 139 |
+
config=ConstraintConfig(solver_seconds=float(time_limit)),
|
| 140 |
+
custom_text=custom_text or None,
|
| 141 |
+
custom_schema=schema,
|
| 142 |
+
custom_solution=direct,
|
| 143 |
+
)
|
| 144 |
+
if result.get("error"):
|
| 145 |
+
raise gr.Error(result["error"])
|
| 146 |
+
validation: ValidationReport | None = result["validation"]
|
| 147 |
+
reasons = "\n".join(f"- {line}" for line in numeric_reasons(problem, result["rows"], validation, lang))
|
| 148 |
+
kpis = kpi_snapshot(result["table"])
|
| 149 |
+
status = (
|
| 150 |
+
f"**{t(lang, 'status')}:** {result['status_label']}\n\n"
|
| 151 |
+
f"{t(lang, 'live_note')}\n\n"
|
| 152 |
+
f"Gold `{problem.gold_status}` / {problem.gold_objective}. Validator "
|
| 153 |
+
f"{'ok' if validation is None or validation.ok else 'failed'}."
|
| 154 |
+
)
|
| 155 |
+
tmp = Path(tempfile.mkdtemp(prefix="orbench-"))
|
| 156 |
+
files = result_to_downloads(result, tmp)
|
| 157 |
+
zip_path = tmp / f"{result['run_id']}_tables.zip"
|
| 158 |
+
with ZipFile(zip_path, "w") as zipped:
|
| 159 |
+
for key, path in files.items():
|
| 160 |
+
zipped.write(path, arcname=Path(path).name)
|
| 161 |
+
live_table = format_leaderboard(result["table"])
|
| 162 |
+
summary = result["summary"]
|
| 163 |
+
fam = family_summary(result["table"])
|
| 164 |
+
plot = solution_plot(problem.family.value, result.get("solution") or {}, t(lang, "sol_plot"))
|
| 165 |
+
method_fig = method_bars(summary, t(lang, "method_plot"))
|
| 166 |
+
family_fig = family_bars(fam, t(lang, "family_plot"))
|
| 167 |
+
violated = pd.DataFrame(
|
| 168 |
+
[{"method_id": row.method_id, "status": row.status, "violated": ", ".join(row.violated), "notes": row.notes} for row in result["rows"]]
|
| 169 |
+
)
|
| 170 |
+
facts = pd.DataFrame(
|
| 171 |
+
[
|
| 172 |
+
{"field": "family", "value": problem.family.value},
|
| 173 |
+
{"field": "split", "value": problem.split.value},
|
| 174 |
+
{"field": "difficulty", "value": problem.difficulty.value},
|
| 175 |
+
{"field": "template_id", "value": problem.template_id},
|
| 176 |
+
{"field": "gold_status", "value": problem.gold_status},
|
| 177 |
+
{"field": "gold_objective", "value": problem.gold_objective},
|
| 178 |
+
{"field": "cover_or_hard", "value": str(problem.schema_payload.get("cover_required") or "")},
|
| 179 |
+
]
|
| 180 |
+
)
|
| 181 |
+
return (
|
| 182 |
+
kpi_html(kpis, lang),
|
| 183 |
+
status,
|
| 184 |
+
reasons,
|
| 185 |
+
live_table,
|
| 186 |
+
summary,
|
| 187 |
+
violated,
|
| 188 |
+
facts,
|
| 189 |
+
plot,
|
| 190 |
+
method_fig,
|
| 191 |
+
family_fig,
|
| 192 |
+
str(zip_path),
|
| 193 |
+
files["report"],
|
| 194 |
+
result["prompt"],
|
| 195 |
+
json.dumps(result["schema"], indent=2, ensure_ascii=False),
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def filter_catalog(family, split, language, difficulty, evaluated_only):
|
| 200 |
+
frame = load_results()
|
| 201 |
+
if frame.empty:
|
| 202 |
+
return pd.DataFrame(), pd.DataFrame(), _empty_plot(), _empty_plot()
|
| 203 |
+
view = frame.copy()
|
| 204 |
+
if family and family != "all":
|
| 205 |
+
view = view.loc[view["family"] == family]
|
| 206 |
+
if split and split != "all":
|
| 207 |
+
view = view.loc[view["split"] == split]
|
| 208 |
+
if language and language != "all":
|
| 209 |
+
view = view.loc[view["language"] == language]
|
| 210 |
+
if difficulty and difficulty != "all":
|
| 211 |
+
view = view.loc[view["difficulty"] == difficulty]
|
| 212 |
+
if evaluated_only:
|
| 213 |
+
view = view.loc[view["evaluated"] == True] # noqa: E712
|
| 214 |
+
summary = summarize(view)
|
| 215 |
+
fam = family_summary(view)
|
| 216 |
+
return format_leaderboard(view), summary, method_bars(summary, "Filtered methods"), family_bars(fam, "Filtered families")
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def compare_interactive(lang, time_limit):
|
| 220 |
+
rows = []
|
| 221 |
+
for problem in interactive_problems():
|
| 222 |
+
result = evaluate_problem(problem, lang=lang, config=ConstraintConfig(solver_seconds=min(6.0, float(time_limit))))
|
| 223 |
+
for row in result["rows"]:
|
| 224 |
+
if row.method_id in {"structured-solver", "heuristic", "template-extractor+solver"}:
|
| 225 |
+
rows.append(row.model_dump())
|
| 226 |
+
frame = pd.DataFrame(rows)
|
| 227 |
+
return format_leaderboard(frame), summarize(frame)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def registry_table() -> pd.DataFrame:
|
| 231 |
+
return pd.DataFrame(
|
| 232 |
+
[
|
| 233 |
+
{
|
| 234 |
+
"method_id": item.method_id,
|
| 235 |
+
"kind": item.kind.value,
|
| 236 |
+
"evaluated": item.evaluated,
|
| 237 |
+
"version": item.version,
|
| 238 |
+
"notes": item.notes or item.reason_if_skipped,
|
| 239 |
+
}
|
| 240 |
+
for item in all_methods()
|
| 241 |
+
]
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def solve_sample_api():
|
| 246 |
+
pack = load_sample()
|
| 247 |
+
result = evaluate_problem(pack["problem"], lang="en", config=ConstraintConfig(solver_seconds=6))
|
| 248 |
+
structured = result["table"].loc[result["table"]["method_id"] == "structured-solver"].iloc[0]
|
| 249 |
+
return result["status"], float(structured.get("feasible") or 0), float(structured.get("objective") or 0), float(result["seconds"])
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def build_demo() -> gr.Blocks:
|
| 253 |
+
pack = load_sample()
|
| 254 |
+
preview = _preview_payload()
|
| 255 |
+
ids = _problem_choices()
|
| 256 |
+
recorded = load_results()
|
| 257 |
+
preview_kpis = preview.get("kpis") or kpi_snapshot(recorded) if not recorded.empty else {
|
| 258 |
+
"n_problems": 100,
|
| 259 |
+
"structured_feasible": 0.0,
|
| 260 |
+
"heuristic_gap": None,
|
| 261 |
+
"template_fidelity": None,
|
| 262 |
+
"n_methods_evaluated": 5,
|
| 263 |
+
"n_methods_listed": 10,
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="purple"), css=CSS) as demo:
|
| 267 |
+
lang = gr.Radio(["en", "fa"], value="en", label=TEXTS["en"]["language"])
|
| 268 |
+
header = gr.HTML()
|
| 269 |
+
with gr.Row():
|
| 270 |
+
run_btn = gr.Button(t("en", "run_sample"), variant="primary")
|
| 271 |
+
cancel_btn = gr.Button(t("en", "cancel"), variant="stop")
|
| 272 |
+
reset_btn = gr.Button(t("en", "reset"))
|
| 273 |
+
load_btn = gr.Button(t("en", "load_sample"))
|
| 274 |
+
note = gr.Markdown(t("en", "sample_note"))
|
| 275 |
+
kpis = gr.HTML(preview.get("kpi_html") or kpi_html(preview_kpis, "en"))
|
| 276 |
+
status = gr.Markdown(t("en", "empty"))
|
| 277 |
+
|
| 278 |
+
with gr.Tabs():
|
| 279 |
+
with gr.Tab("Data"):
|
| 280 |
+
hint = gr.Markdown(t("en", "upload_hint"))
|
| 281 |
+
problem = gr.Dropdown(choices=ids, value=ids[0] if ids else None, label=t("en", "problem"))
|
| 282 |
+
with gr.Row():
|
| 283 |
+
prompt_en = gr.Textbox(value=pack["problem"].prompt_en, label="prompt_en", lines=8)
|
| 284 |
+
prompt_fa = gr.Textbox(value=pack["problem"].prompt_fa, label="prompt_fa", lines=8)
|
| 285 |
+
prompt_json = gr.Code(value=pack["problem"].prompt_json, language="json", label="prompt_json")
|
| 286 |
+
custom_text = gr.Textbox(label=t("en", "custom_text"), lines=4)
|
| 287 |
+
schema_text = gr.Code(
|
| 288 |
+
value=json.dumps(pack["problem"].schema_payload, indent=2, ensure_ascii=False),
|
| 289 |
+
language="json",
|
| 290 |
+
label=t("en", "custom_schema"),
|
| 291 |
+
)
|
| 292 |
+
direct_text = gr.Textbox(label=t("en", "direct_json"), lines=4, placeholder='{"orders":[],"assignments":[],"starts":[]}')
|
| 293 |
+
|
| 294 |
+
with gr.Tab("Constraints"):
|
| 295 |
+
variant = gr.Radio(choices=_variant_choices("en"), value=_variant_choices("en")[0], label=t("en", "variant"))
|
| 296 |
+
with gr.Accordion(t("en", "advanced"), open=False) as advanced:
|
| 297 |
+
time_limit = gr.Slider(3, 20, value=DEFAULT_SOLVER_SECONDS, step=1, label=t("en", "time_limit"))
|
| 298 |
+
facts = gr.Dataframe(
|
| 299 |
+
value=pd.DataFrame(
|
| 300 |
+
[
|
| 301 |
+
{"field": "family", "value": pack["problem"].family.value},
|
| 302 |
+
{"field": "gold_status", "value": pack["problem"].gold_status},
|
| 303 |
+
{"field": "gold_objective", "value": pack["problem"].gold_objective},
|
| 304 |
+
]
|
| 305 |
+
),
|
| 306 |
+
label="Instance facts",
|
| 307 |
+
)
|
| 308 |
+
meta = gr.Markdown(
|
| 309 |
+
f"family `{pack['problem'].family.value}` · split `{pack['problem'].split.value}` · "
|
| 310 |
+
f"difficulty `{pack['problem'].difficulty.value}` · template `{pack['problem'].template_id}`"
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
with gr.Tab("Results"):
|
| 314 |
+
reasons = gr.Markdown()
|
| 315 |
+
live_table = gr.Dataframe(label="Per-method cells (not_evaluated is not a score)")
|
| 316 |
+
violated = gr.Dataframe(label="Violated constraints / skip reasons")
|
| 317 |
+
sol_plot = gr.Plot(value=_empty_plot())
|
| 318 |
+
method_plot = gr.Plot(value=_empty_plot())
|
| 319 |
+
live_summary = gr.Dataframe(label="Evaluated-method summary")
|
| 320 |
+
with gr.Row():
|
| 321 |
+
zip_out = gr.File(label="CSV / JSON bundle")
|
| 322 |
+
json_out = gr.File(label="JSON report")
|
| 323 |
+
|
| 324 |
+
with gr.Tab("Scenario comparison"):
|
| 325 |
+
with gr.Row():
|
| 326 |
+
family_f = gr.Dropdown(["all", "inventory", "assignment", "scheduling"], value="all", label="family")
|
| 327 |
+
split_f = gr.Dropdown(["all", "development", "test"], value="all", label="split")
|
| 328 |
+
lang_f = gr.Dropdown(["all", "en", "fa"], value="all", label="prompt language")
|
| 329 |
+
diff_f = gr.Dropdown(["all", "easy", "medium", "hard", "infeasible"], value="all", label="difficulty")
|
| 330 |
+
eval_only = gr.Checkbox(value=False, label="hide not_evaluated rows")
|
| 331 |
+
filter_btn = gr.Button("Filter recorded catalog")
|
| 332 |
+
compare_btn = gr.Button("Re-run 20 interactive problems")
|
| 333 |
+
board = gr.Dataframe(label="Recorded leaderboard", value=format_leaderboard(recorded) if not recorded.empty else None)
|
| 334 |
+
board_summary = gr.Dataframe(label="Catalog summary")
|
| 335 |
+
family_plot = gr.Plot(value=_empty_plot())
|
| 336 |
+
catalog_plot = gr.Plot(value=_empty_plot())
|
| 337 |
+
interactive_tbl = gr.Dataframe(label="Interactive re-run")
|
| 338 |
+
interactive_sum = gr.Dataframe(label="Interactive summary")
|
| 339 |
+
|
| 340 |
+
with gr.Tab("Method and limits"):
|
| 341 |
+
method = gr.Markdown(t("en", "method_body"))
|
| 342 |
+
registry = gr.Dataframe(value=registry_table(), label="Versioned method registry")
|
| 343 |
+
gr.Markdown(
|
| 344 |
+
"Organization: [AriaAICompany](https://huggingface.co/AriaAICompany) · "
|
| 345 |
+
"Dataset: [or-bench-problems](https://huggingface.co/datasets/AriaAICompany/or-bench-problems) · "
|
| 346 |
+
"Site: [aria-ai.ir](https://aria-ai.ir/)"
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
hidden_gold_status = gr.Textbox(visible=False, value=pack["problem"].gold_status)
|
| 350 |
+
hidden_gold_obj = gr.Number(visible=False, value=pack["problem"].gold_objective or 0)
|
| 351 |
+
hidden_family = gr.Textbox(visible=False, value=pack["problem"].family.value)
|
| 352 |
+
hidden_split = gr.Textbox(visible=False, value=pack["problem"].split.value)
|
| 353 |
+
hidden_diff = gr.Textbox(visible=False, value=pack["problem"].difficulty.value)
|
| 354 |
+
hidden_plang = gr.Textbox(visible=False, value=pack["problem"].language)
|
| 355 |
+
hidden_tmpl = gr.Textbox(visible=False, value=pack["problem"].template_id)
|
| 356 |
+
|
| 357 |
+
outputs_lang = [
|
| 358 |
+
header,
|
| 359 |
+
run_btn,
|
| 360 |
+
cancel_btn,
|
| 361 |
+
reset_btn,
|
| 362 |
+
load_btn,
|
| 363 |
+
problem,
|
| 364 |
+
variant,
|
| 365 |
+
time_limit,
|
| 366 |
+
note,
|
| 367 |
+
kpis,
|
| 368 |
+
advanced,
|
| 369 |
+
method,
|
| 370 |
+
hint,
|
| 371 |
+
custom_text,
|
| 372 |
+
schema_text,
|
| 373 |
+
direct_text,
|
| 374 |
+
]
|
| 375 |
+
lang.change(apply_language, inputs=[lang], outputs=outputs_lang)
|
| 376 |
+
demo.load(apply_language, inputs=[lang], outputs=outputs_lang)
|
| 377 |
+
|
| 378 |
+
problem.change(
|
| 379 |
+
_load_problem_fields,
|
| 380 |
+
inputs=[problem],
|
| 381 |
+
outputs=[
|
| 382 |
+
prompt_en,
|
| 383 |
+
prompt_fa,
|
| 384 |
+
prompt_json,
|
| 385 |
+
schema_text,
|
| 386 |
+
hidden_gold_status,
|
| 387 |
+
hidden_gold_obj,
|
| 388 |
+
hidden_family,
|
| 389 |
+
hidden_split,
|
| 390 |
+
hidden_diff,
|
| 391 |
+
hidden_plang,
|
| 392 |
+
hidden_tmpl,
|
| 393 |
+
],
|
| 394 |
+
)
|
| 395 |
+
load_btn.click(
|
| 396 |
+
load_sample_ui,
|
| 397 |
+
outputs=[
|
| 398 |
+
problem,
|
| 399 |
+
prompt_en,
|
| 400 |
+
prompt_fa,
|
| 401 |
+
prompt_json,
|
| 402 |
+
schema_text,
|
| 403 |
+
hidden_gold_status,
|
| 404 |
+
hidden_gold_obj,
|
| 405 |
+
hidden_family,
|
| 406 |
+
hidden_split,
|
| 407 |
+
hidden_diff,
|
| 408 |
+
hidden_plang,
|
| 409 |
+
hidden_tmpl,
|
| 410 |
+
],
|
| 411 |
+
)
|
| 412 |
+
reset_btn.click(
|
| 413 |
+
load_sample_ui,
|
| 414 |
+
outputs=[
|
| 415 |
+
problem,
|
| 416 |
+
prompt_en,
|
| 417 |
+
prompt_fa,
|
| 418 |
+
prompt_json,
|
| 419 |
+
schema_text,
|
| 420 |
+
hidden_gold_status,
|
| 421 |
+
hidden_gold_obj,
|
| 422 |
+
hidden_family,
|
| 423 |
+
hidden_split,
|
| 424 |
+
hidden_diff,
|
| 425 |
+
hidden_plang,
|
| 426 |
+
hidden_tmpl,
|
| 427 |
+
],
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
run_event = run_live
|
| 431 |
+
event = run_btn.click(
|
| 432 |
+
run_live,
|
| 433 |
+
inputs=[lang, problem, variant, time_limit, custom_text, schema_text, direct_text],
|
| 434 |
+
outputs=[
|
| 435 |
+
kpis,
|
| 436 |
+
status,
|
| 437 |
+
reasons,
|
| 438 |
+
live_table,
|
| 439 |
+
live_summary,
|
| 440 |
+
violated,
|
| 441 |
+
facts,
|
| 442 |
+
sol_plot,
|
| 443 |
+
method_plot,
|
| 444 |
+
family_plot,
|
| 445 |
+
zip_out,
|
| 446 |
+
json_out,
|
| 447 |
+
custom_text,
|
| 448 |
+
schema_text,
|
| 449 |
+
],
|
| 450 |
+
)
|
| 451 |
+
cancel_btn.click(lambda: None, cancels=[event])
|
| 452 |
+
filter_btn.click(
|
| 453 |
+
filter_catalog,
|
| 454 |
+
inputs=[family_f, split_f, lang_f, diff_f, eval_only],
|
| 455 |
+
outputs=[board, board_summary, catalog_plot, family_plot],
|
| 456 |
+
)
|
| 457 |
+
compare_btn.click(compare_interactive, inputs=[lang, time_limit], outputs=[interactive_tbl, interactive_sum])
|
| 458 |
+
|
| 459 |
+
api_status = gr.Textbox(visible=False)
|
| 460 |
+
api_feas = gr.Number(visible=False)
|
| 461 |
+
api_obj = gr.Number(visible=False)
|
| 462 |
+
api_sec = gr.Number(visible=False)
|
| 463 |
+
api_btn = gr.Button("solve_sample_api", visible=False)
|
| 464 |
+
api_btn.click(solve_sample_api, outputs=[api_status, api_feas, api_obj, api_sec], api_name="solve_sample")
|
| 465 |
+
|
| 466 |
+
_ = run_event
|
| 467 |
+
_ = meta
|
| 468 |
+
|
| 469 |
+
demo.queue(default_concurrency_limit=1)
|
| 470 |
+
return demo
|
demo/src/validation.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
|
| 5 |
+
from src.domain import (
|
| 6 |
+
AssignmentInstance,
|
| 7 |
+
Family,
|
| 8 |
+
InventoryInstance,
|
| 9 |
+
ScheduleInstance,
|
| 10 |
+
Solution,
|
| 11 |
+
ValidationIssue,
|
| 12 |
+
ValidationReport,
|
| 13 |
+
parse_instance,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _issue(code: str, message: str, entity_id: str | None = None, passed: bool = False) -> ValidationIssue:
|
| 18 |
+
return ValidationIssue(code=code, message=message, entity_id=entity_id, passed=passed)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def validate_schema(family: Family | str, payload: dict) -> ValidationReport:
|
| 22 |
+
issues: list[ValidationIssue] = []
|
| 23 |
+
checked = ["schema", "ids", "values"]
|
| 24 |
+
try:
|
| 25 |
+
instance = parse_instance(family, payload)
|
| 26 |
+
except Exception as exc:
|
| 27 |
+
return ValidationReport(ok=False, issues=[_issue("schema", f"schema rejected: {exc}")], checked=checked)
|
| 28 |
+
|
| 29 |
+
if isinstance(instance, InventoryInstance):
|
| 30 |
+
ids = [sku.sku_id for sku in instance.skus]
|
| 31 |
+
if len(ids) != len(set(ids)):
|
| 32 |
+
issues.append(_issue("ids", "duplicate SKU ids"))
|
| 33 |
+
if not instance.skus:
|
| 34 |
+
issues.append(_issue("schema", "inventory needs at least one SKU"))
|
| 35 |
+
for sku in instance.skus:
|
| 36 |
+
if len(sku.demand) != instance.periods:
|
| 37 |
+
issues.append(_issue("values", f"{sku.sku_id} demand length must equal periods", sku.sku_id))
|
| 38 |
+
if any(value < 0 for value in sku.demand):
|
| 39 |
+
issues.append(_issue("values", f"{sku.sku_id} demand must be non-negative", sku.sku_id))
|
| 40 |
+
elif isinstance(instance, AssignmentInstance):
|
| 41 |
+
if not instance.tasks or not instance.agents:
|
| 42 |
+
issues.append(_issue("schema", "assignment needs tasks and agents"))
|
| 43 |
+
task_ids = [task.task_id for task in instance.tasks]
|
| 44 |
+
agent_ids = [agent.agent_id for agent in instance.agents]
|
| 45 |
+
if len(task_ids) != len(set(task_ids)) or len(agent_ids) != len(set(agent_ids)):
|
| 46 |
+
issues.append(_issue("ids", "duplicate task or agent ids"))
|
| 47 |
+
known = {(task.task_id, agent.agent_id) for task in instance.tasks for agent in instance.agents}
|
| 48 |
+
for row in instance.costs:
|
| 49 |
+
if (row.task_id, row.agent_id) not in known:
|
| 50 |
+
issues.append(_issue("references", f"cost for unknown pair {row.task_id}/{row.agent_id}"))
|
| 51 |
+
else:
|
| 52 |
+
job_ids = [job.job_id for job in instance.jobs]
|
| 53 |
+
if len(job_ids) != len(set(job_ids)):
|
| 54 |
+
issues.append(_issue("ids", "duplicate job ids"))
|
| 55 |
+
if not instance.machines or not instance.jobs:
|
| 56 |
+
issues.append(_issue("schema", "scheduling needs jobs and machines"))
|
| 57 |
+
seen = set()
|
| 58 |
+
for edge in instance.precedences:
|
| 59 |
+
if edge.before not in job_ids or edge.after not in job_ids:
|
| 60 |
+
issues.append(_issue("references", f"precedence {edge.before}->{edge.after} is unknown"))
|
| 61 |
+
if edge.before == edge.after:
|
| 62 |
+
issues.append(_issue("values", f"self precedence on {edge.before}", edge.before))
|
| 63 |
+
pair = (edge.before, edge.after)
|
| 64 |
+
if pair in seen:
|
| 65 |
+
continue
|
| 66 |
+
seen.add(pair)
|
| 67 |
+
if _has_cycle(instance.precedences):
|
| 68 |
+
issues.append(_issue("values", "precedence graph has a cycle"))
|
| 69 |
+
return ValidationReport(ok=not issues, issues=issues, checked=checked)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _has_cycle(edges) -> bool:
|
| 73 |
+
graph: dict[str, list[str]] = defaultdict(list)
|
| 74 |
+
nodes: set[str] = set()
|
| 75 |
+
for edge in edges:
|
| 76 |
+
graph[edge.before].append(edge.after)
|
| 77 |
+
nodes.add(edge.before)
|
| 78 |
+
nodes.add(edge.after)
|
| 79 |
+
state: dict[str, int] = {}
|
| 80 |
+
|
| 81 |
+
def visit(node: str) -> bool:
|
| 82 |
+
state[node] = 1
|
| 83 |
+
for nxt in graph.get(node, []):
|
| 84 |
+
if state.get(nxt) == 1:
|
| 85 |
+
return True
|
| 86 |
+
if state.get(nxt, 0) == 0 and visit(nxt):
|
| 87 |
+
return True
|
| 88 |
+
state[node] = 2
|
| 89 |
+
return False
|
| 90 |
+
|
| 91 |
+
return any(state.get(node, 0) == 0 and visit(node) for node in nodes)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def validate_solution(family: Family | str, payload: dict, solution: Solution | dict) -> ValidationReport:
|
| 95 |
+
family = Family(family)
|
| 96 |
+
schema_report = validate_schema(family, payload)
|
| 97 |
+
if not schema_report.ok:
|
| 98 |
+
return schema_report
|
| 99 |
+
instance = parse_instance(family, payload)
|
| 100 |
+
if not isinstance(solution, Solution):
|
| 101 |
+
solution = Solution.model_validate(solution)
|
| 102 |
+
if family == Family.INVENTORY:
|
| 103 |
+
return _validate_inventory(instance, solution)
|
| 104 |
+
if family == Family.ASSIGNMENT:
|
| 105 |
+
return _validate_assignment(instance, solution)
|
| 106 |
+
return _validate_schedule(instance, solution)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _validate_inventory(instance: InventoryInstance, solution: Solution) -> ValidationReport:
|
| 110 |
+
issues: list[ValidationIssue] = []
|
| 111 |
+
checked = ["pack", "budget", "balance", "capacity", "cover", "objective"]
|
| 112 |
+
qty = {(row.sku_id, int(row.period)): int(row.qty) for row in solution.orders}
|
| 113 |
+
spend = 0
|
| 114 |
+
hold_cost = 0
|
| 115 |
+
short_cost = 0
|
| 116 |
+
stock = {sku.sku_id: sku.initial_stock for sku in instance.skus}
|
| 117 |
+
for t in range(1, instance.periods + 1):
|
| 118 |
+
ending = 0
|
| 119 |
+
for sku in instance.skus:
|
| 120 |
+
order = int(qty.get((sku.sku_id, t), 0))
|
| 121 |
+
if order < 0:
|
| 122 |
+
issues.append(_issue("values", f"negative order {sku.sku_id}@{t}", sku.sku_id))
|
| 123 |
+
if sku.pack_size and order % sku.pack_size != 0:
|
| 124 |
+
issues.append(_issue("pack", f"{sku.sku_id}@{t} qty {order} is not a multiple of pack {sku.pack_size}", sku.sku_id))
|
| 125 |
+
spend += order * sku.unit_cost
|
| 126 |
+
demand = int(sku.demand[t - 1])
|
| 127 |
+
available = stock[sku.sku_id] + order
|
| 128 |
+
sold = min(available, demand)
|
| 129 |
+
short = demand - sold
|
| 130 |
+
stock[sku.sku_id] = available - sold
|
| 131 |
+
if stock[sku.sku_id] < 0:
|
| 132 |
+
issues.append(_issue("balance", f"negative inventory {sku.sku_id}@{t}", sku.sku_id))
|
| 133 |
+
if instance.cover_required and short:
|
| 134 |
+
issues.append(_issue("cover", f"{sku.sku_id}@{t} shortage {short} while cover is required", sku.sku_id))
|
| 135 |
+
ending += stock[sku.sku_id]
|
| 136 |
+
hold_cost += stock[sku.sku_id] * sku.holding_cost
|
| 137 |
+
short_cost += short * sku.shortage_cost
|
| 138 |
+
if ending > instance.warehouse_capacity:
|
| 139 |
+
issues.append(_issue("capacity", f"period {t} inventory {ending} exceeds capacity {instance.warehouse_capacity}"))
|
| 140 |
+
if spend > instance.budget:
|
| 141 |
+
issues.append(_issue("budget", f"purchase {spend} exceeds budget {instance.budget}"))
|
| 142 |
+
objective = float(spend + hold_cost + short_cost)
|
| 143 |
+
return ValidationReport(ok=not issues, issues=issues, checked=checked, recomputed_objective=objective)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _validate_assignment(instance: AssignmentInstance, solution: Solution) -> ValidationReport:
|
| 147 |
+
issues: list[ValidationIssue] = []
|
| 148 |
+
checked = ["unique", "eligible", "capacity", "required", "objective"]
|
| 149 |
+
seen_tasks: set[str] = set()
|
| 150 |
+
load: dict[str, int] = defaultdict(int)
|
| 151 |
+
cost_map = instance.cost_map()
|
| 152 |
+
agents = {agent.agent_id: agent for agent in instance.agents}
|
| 153 |
+
tasks = {task.task_id: task for task in instance.tasks}
|
| 154 |
+
spend = 0
|
| 155 |
+
for row in solution.assignments:
|
| 156 |
+
if row.task_id in seen_tasks:
|
| 157 |
+
issues.append(_issue("unique", f"task {row.task_id} assigned more than once", row.task_id))
|
| 158 |
+
seen_tasks.add(row.task_id)
|
| 159 |
+
task = tasks.get(row.task_id)
|
| 160 |
+
agent = agents.get(row.agent_id)
|
| 161 |
+
if task is None or agent is None:
|
| 162 |
+
issues.append(_issue("references", f"unknown pair {row.task_id}/{row.agent_id}", row.task_id))
|
| 163 |
+
continue
|
| 164 |
+
if not instance.eligible(task, agent):
|
| 165 |
+
issues.append(_issue("eligible", f"{row.task_id} is not eligible for {row.agent_id}", row.task_id))
|
| 166 |
+
if (row.task_id, row.agent_id) not in cost_map:
|
| 167 |
+
issues.append(_issue("references", f"no cost for {row.task_id}/{row.agent_id}", row.task_id))
|
| 168 |
+
else:
|
| 169 |
+
spend += cost_map[(row.task_id, row.agent_id)]
|
| 170 |
+
load[row.agent_id] += task.size
|
| 171 |
+
for agent in instance.agents:
|
| 172 |
+
if load[agent.agent_id] > agent.capacity:
|
| 173 |
+
issues.append(_issue("capacity", f"{agent.agent_id} load {load[agent.agent_id]} exceeds {agent.capacity}", agent.agent_id))
|
| 174 |
+
leftover = set(solution.unassigned)
|
| 175 |
+
for task in instance.tasks:
|
| 176 |
+
assigned = task.task_id in seen_tasks
|
| 177 |
+
if task.required and not assigned:
|
| 178 |
+
issues.append(_issue("required", f"required task {task.task_id} is unassigned", task.task_id))
|
| 179 |
+
if not assigned:
|
| 180 |
+
leftover.add(task.task_id)
|
| 181 |
+
spend += task.penalty
|
| 182 |
+
if assigned and task.task_id in leftover:
|
| 183 |
+
leftover.discard(task.task_id)
|
| 184 |
+
return ValidationReport(ok=not issues, issues=issues, checked=checked, recomputed_objective=float(spend))
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _validate_schedule(instance: ScheduleInstance, solution: Solution) -> ValidationReport:
|
| 188 |
+
issues: list[ValidationIssue] = []
|
| 189 |
+
checked = ["unique", "eligible", "release", "overlap", "precedence", "hard_due", "duration", "objective"]
|
| 190 |
+
jobs = {job.job_id: job for job in instance.jobs}
|
| 191 |
+
seen: set[str] = set()
|
| 192 |
+
by_machine: dict[str, list[tuple[int, int, str]]] = defaultdict(list)
|
| 193 |
+
ends: dict[str, int] = {}
|
| 194 |
+
starts: dict[str, int] = {}
|
| 195 |
+
tardy = 0
|
| 196 |
+
for row in solution.starts:
|
| 197 |
+
if row.job_id in seen:
|
| 198 |
+
issues.append(_issue("unique", f"job {row.job_id} starts more than once", row.job_id))
|
| 199 |
+
seen.add(row.job_id)
|
| 200 |
+
job = jobs.get(row.job_id)
|
| 201 |
+
if job is None:
|
| 202 |
+
issues.append(_issue("references", f"unknown job {row.job_id}", row.job_id))
|
| 203 |
+
continue
|
| 204 |
+
if row.machine_id not in instance.machines:
|
| 205 |
+
issues.append(_issue("references", f"unknown machine {row.machine_id}", row.job_id))
|
| 206 |
+
if job.machine_eligible and row.machine_id not in set(job.machine_eligible):
|
| 207 |
+
issues.append(_issue("eligible", f"{row.job_id} cannot use {row.machine_id}", row.job_id))
|
| 208 |
+
if row.start < job.release:
|
| 209 |
+
issues.append(_issue("release", f"{row.job_id} starts at {row.start} before release {job.release}", row.job_id))
|
| 210 |
+
if row.end - row.start != job.duration:
|
| 211 |
+
issues.append(_issue("duration", f"{row.job_id} duration {row.end - row.start} != {job.duration}", row.job_id))
|
| 212 |
+
if job.hard_due and row.end > job.due:
|
| 213 |
+
issues.append(_issue("hard_due", f"{row.job_id} ends at {row.end} after hard due {job.due}", row.job_id))
|
| 214 |
+
by_machine[row.machine_id].append((row.start, row.end, row.job_id))
|
| 215 |
+
ends[row.job_id] = row.end
|
| 216 |
+
starts[row.job_id] = row.start
|
| 217 |
+
tardy += job.weight * max(0, row.end - job.due)
|
| 218 |
+
for job in instance.jobs:
|
| 219 |
+
if job.job_id not in seen:
|
| 220 |
+
issues.append(_issue("cover", f"job {job.job_id} has no start", job.job_id))
|
| 221 |
+
for machine, blocks in by_machine.items():
|
| 222 |
+
ordered = sorted(blocks)
|
| 223 |
+
for prev, cur in zip(ordered, ordered[1:]):
|
| 224 |
+
if prev[1] > cur[0]:
|
| 225 |
+
issues.append(_issue("overlap", f"{machine} overlap {prev[2]} and {cur[2]}", machine))
|
| 226 |
+
for edge in instance.precedences:
|
| 227 |
+
if edge.before in ends and edge.after in starts and ends[edge.before] > starts[edge.after]:
|
| 228 |
+
issues.append(_issue("precedence", f"{edge.before} must finish before {edge.after}", edge.after))
|
| 229 |
+
return ValidationReport(ok=not issues, issues=issues, checked=checked, recomputed_objective=float(tardy))
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def format_input_error(report: ValidationReport) -> str:
|
| 233 |
+
if report.ok:
|
| 234 |
+
return ""
|
| 235 |
+
return " | ".join(f"{item.code}: {item.message}" for item in report.issues[:8])
|
demo/tests/__pycache__/conftest.cpython-312-pytest-8.3.4.pyc
ADDED
|
Binary file (667 Bytes). View file
|
|
|
demo/tests/__pycache__/test_pipeline.cpython-312-pytest-8.3.4.pyc
ADDED
|
Binary file (54.7 kB). View file
|
|
|
demo/tests/conftest.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 5 |
+
if str(ROOT) not in sys.path:
|
| 6 |
+
sys.path.insert(0, str(ROOT))
|