minimal-core-benchmark / build_hf.py
dipankarsarkar's picture
Publish minimal-core-benchmark from ds-hf
aea2afd verified
Raw History Blame Contribute Delete
4.42 kB
#!/usr/bin/env python3
"""Build the HuggingFace dataset package from the GitHub release.
Usage:
python3 build_hf.py <path/to/minimal-core-benchmark checkout> [out_dir]
Source: https://github.com/sarkar-dipankar/minimal-core-benchmark (commit 330d980).
Stdlib only and deterministic: instance files are read in sorted order, nested
values are re-serialised compactly with their original key order, and every
column keeps one type across all rows (the HF viewer rejects mixed-type columns).
Outputs (under out_dir, default: the directory holding this script):
data/instances.jsonl one row per benchmark/problems/<id>.json
raw/benchmark/ exact copy of benchmark/ (minus __pycache__)
raw/savanty/ exact copy of savanty/ (asp_runtime.py, the clingo wrapper)
raw/LICENSE, raw/CITATION.cff, raw/requirements.txt
"""
import json
import os
import shutil
import sys
# `domains` and `_reference_witness` are dicts keyed by variable name (hundreds of
# distinct keys across the set) and `constraints` mixes several key sets. As nested
# structs they would explode or conflict in the viewer schema, so they ship as JSON
# strings. Parse them with json.loads.
JSON_STRING_FIELDS = ("domains", "constraints", "objective", "_reference_witness")
RENAME = {"_reference_witness": "reference_witness"}
EXPECTED_KEYS = {
"id", "domain", "size", "variant", "nl_description", "variables",
"domains", "constraints", "objective", "feasible", "optimal_value",
"_reference_witness",
}
ROOT_FILES = ("LICENSE", "CITATION.cff", "requirements.txt")
def jstr(obj):
"""Compact, deterministic JSON string for nested values. None stays None."""
if obj is None:
return None
return json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
def write_jsonl(path, rows):
with open(path, "w", encoding="utf-8", newline="\n") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
return len(rows)
def build_instances(src):
pdir = os.path.join(src, "benchmark", "problems")
rows = []
for name in sorted(os.listdir(pdir)):
if not name.endswith(".json"):
continue
with open(os.path.join(pdir, name), encoding="utf-8") as f:
s = json.load(f)
if set(s) != EXPECTED_KEYS:
sys.exit(f"{name}: unexpected keys {sorted(set(s) ^ EXPECTED_KEYS)}")
if s["id"] + ".json" != name:
sys.exit(f"{name}: id {s['id']!r} does not match file name")
obj = s["objective"]
opt = s["optimal_value"]
row = {
"id": s["id"],
"domain": s["domain"],
"variant": s["variant"],
"size": int(s["size"]),
"feasible": bool(s["feasible"]),
"optimal_value": float(opt) if opt is not None else None,
"has_objective": obj is not None,
"objective_sense": obj["sense"] if obj else None,
"n_variables": len(s["variables"]),
"n_constraints": len(s["constraints"]),
"constraint_types": sorted({c["type"] for c in s["constraints"]}),
"nl_description": s["nl_description"],
"variables": [str(v) for v in s["variables"]],
}
for k in JSON_STRING_FIELDS:
row[RENAME.get(k, k)] = jstr(s[k])
row["file"] = f"benchmark/problems/{name}"
rows.append(row)
return rows
def copy_raw(src, out):
raw = os.path.join(out, "raw")
if os.path.exists(raw):
shutil.rmtree(raw)
ignore = shutil.ignore_patterns("__pycache__", "*.pyc")
for sub in ("benchmark", "savanty"):
shutil.copytree(os.path.join(src, sub), os.path.join(raw, sub), ignore=ignore)
for name in ROOT_FILES:
shutil.copy2(os.path.join(src, name), os.path.join(raw, name))
def main():
if len(sys.argv) < 2:
sys.exit(__doc__)
src = os.path.abspath(sys.argv[1])
out = os.path.abspath(sys.argv[2]) if len(sys.argv) > 2 else os.path.dirname(os.path.abspath(__file__))
data = os.path.join(out, "data")
os.makedirs(data, exist_ok=True)
n = write_jsonl(os.path.join(data, "instances.jsonl"), build_instances(src))
print(f"data/instances.jsonl: {n} rows from benchmark/problems/*.json")
copy_raw(src, out)
print("raw/: benchmark/, savanty/, LICENSE, CITATION.cff, requirements.txt copied")
if __name__ == "__main__":
main()