benchtruthai 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ """benchtruthai: score optimization modeling predictions against audited ground truth.
2
+
3
+ Wraps the cleaned release of the benchmark ground-truth audit by
4
+ Rangaraju (2026), "A Third of the Ground Truth Is Wrong: A 127-Instance
5
+ Audit of Optimization-Modeling Benchmarks", published as a public record
6
+ (preprint and reproduction package) on GitHub (2026); an earlier Zenodo
7
+ deposit was removed by the repository in November 2026. A journal
8
+ manuscript has been retargeted to JAIR and has not been published in a
9
+ journal: 109 released instances from NL4Opt, MAMO, and IndustryOR with
10
+ shipped optima, optima audited with a solver (dev split), verdicts, and
11
+ a full audit trail for each instance.
12
+
13
+ Author: Prabhu Rangaraju
14
+ License: MIT (code and release tooling; audit annotations MIT except
15
+ the MAMO slice, CC-BY-SA-4.0; IndustryOR records under CC-BY-NC-4.0;
16
+ upstream problem texts and shipped optima remain under their original
17
+ terms, see NOTICES.md). Bundle form: open source scoring software
18
+ plus a dataset under mixed licenses, not a single license.
19
+ """
20
+
21
+ from .data import Record, load_records, DATASET_VERSION
22
+ from .scoring import matches, score_predictions, ScoreReport
23
+ from .bands import wilson_interval, sensitivity_band, error_rates
24
+
25
+ __version__ = "0.1.0"
26
+
27
+ __all__ = [
28
+ "Record",
29
+ "load_records",
30
+ "DATASET_VERSION",
31
+ "matches",
32
+ "score_predictions",
33
+ "ScoreReport",
34
+ "wilson_interval",
35
+ "sensitivity_band",
36
+ "error_rates",
37
+ "__version__",
38
+ ]
benchtruthai/bands.py ADDED
@@ -0,0 +1,95 @@
1
+ """Ground truth error rates and analytic sensitivity bands.
2
+
3
+ The bands computed here are a sensitivity (bounds) analysis, not
4
+ corrected scores: they bound how far a published accuracy could move
5
+ under an audited error rate; no method is scored again.
6
+
7
+ From the audit paper (§5.3): each wrong ground truth can flip at most
8
+ one instance's verdict, so for any published accuracy A on a benchmark
9
+ whose ground-truth error rate is e,
10
+
11
+ |text-faithful accuracy - A| <= e
12
+
13
+ The central band is A ± e at the point estimate; the conservative band
14
+ is A ± e_hi, where e_hi is the upper bound of the Wilson 95% interval
15
+ on e. Bands are clipped to [0, 100]. They are nominal/illustrative, not
16
+ inferential, exactly as the paper states. Interpreting a band as a
17
+ bound on an accuracy measured on a different evaluation set than the
18
+ audited slice requires assuming the audited error rate applies to
19
+ that set; the audit does not establish that assumption.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import math
25
+
26
+ from .data import Record, load_records
27
+
28
+
29
+ def wilson_interval(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
30
+ """Wilson 95% score interval for k successes in n trials.
31
+
32
+ Raises ValueError for counts outside 0 <= k <= n (previously a
33
+ count out of range fell through to a math domain error from
34
+ ``math.sqrt``). Endpoints are clamped to [0, 1]: the interval lies
35
+ in that range mathematically, and the unclamped arithmetic can
36
+ return a lower endpoint a few ulps below 0.0 (observed: -2e-17
37
+ for k=0, n=10). Found by the 2026-11-22 release gate property
38
+ tests; no result in range changes beyond that clamping.
39
+ """
40
+ if n < 0 or k < 0 or k > n:
41
+ raise ValueError(f"wilson_interval needs 0 <= k <= n, got k={k}, n={n}")
42
+ if n == 0:
43
+ return (0.0, 1.0)
44
+ p = k / n
45
+ # Wilson score interval in its standard form: the z^2 terms shrink
46
+ # the center toward 1/2, and center and half width are computed on
47
+ # the unnormalized scale, then divided by (1 + z^2 / n).
48
+ denom = 1 + z * z / n
49
+ center = p + z * z / (2 * n)
50
+ half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
51
+ return (max(0.0, (center - half) / denom), min(1.0, (center + half) / denom))
52
+
53
+
54
+ def error_rates(records: list[Record] | None = None) -> dict[str, dict]:
55
+ """Material error rates per family and per slice over the full release.
56
+
57
+ Rates are computed over all 109 records in this release (dev + test):
58
+ verdicts are public for every record even though test optima are
59
+ withheld. Keys: 'nl4opt', 'mamo', 'mamo-easy', 'mamo-complex',
60
+ 'industryor', 'all'.
61
+ """
62
+ if records is None:
63
+ records = load_records()
64
+ groups: dict[str, list[Record]] = {"all": list(records)}
65
+ for r in records:
66
+ groups.setdefault(r.family, []).append(r)
67
+ if r.slice != r.family:
68
+ groups.setdefault(r.slice, []).append(r)
69
+ out: dict[str, dict] = {}
70
+ for key, recs in sorted(groups.items()):
71
+ k = sum(1 for r in recs if r.verdict == "material_error")
72
+ n = len(recs)
73
+ lo, hi = wilson_interval(k, n)
74
+ out[key] = {"errors": k, "n": n, "rate": k / n, "wilson_lo": lo, "wilson_hi": hi}
75
+ return out
76
+
77
+
78
+ def sensitivity_band(accuracy_pct: float, rate: float, wilson_hi: float) -> dict:
79
+ """Central and conservative bands (percentage points) for a published accuracy."""
80
+
81
+ def clip(lo: float, hi: float) -> tuple[float, float]:
82
+ """Clip a band to the [0, 100] percentage point range."""
83
+ return (max(0.0, lo), min(100.0, hi))
84
+
85
+ # Both bands are A +/- 100e in percentage points: the central band
86
+ # uses the point estimate of e; the conservative band uses e_hi,
87
+ # the conservative sensitivity bound as defined in the module
88
+ # docstring (the conservative band is A +/- e_hi; the
89
+ # |A' - A| <= e bound belongs to the point estimate and the
90
+ # central band).
91
+ return {
92
+ "published": accuracy_pct,
93
+ "central": clip(accuracy_pct - 100 * rate, accuracy_pct + 100 * rate),
94
+ "conservative": clip(accuracy_pct - 100 * wilson_hi, accuracy_pct + 100 * wilson_hi),
95
+ }
benchtruthai/cli.py ADDED
@@ -0,0 +1,207 @@
1
+ """benchtruthai command line.
2
+
3
+ Subcommands:
4
+ info dataset summary (counts, error rates)
5
+ verify recheck the release's headline numbers from the shipped data
6
+ score score a predictions file (JSONL: one {"uid", "predicted_optimum"}
7
+ object per line) against shipped vs audited ground truth
8
+ personas the paper's solver persona demonstration, on the public dev split
9
+ bands analytic sensitivity bands for published accuracies (paper §5.3),
10
+ a bounds analysis, not corrected scores;
11
+ CSV input with method,benchmark,published_accuracy columns
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import csv
18
+ import json
19
+ import sys
20
+
21
+ from . import __version__
22
+ from .bands import error_rates, sensitivity_band
23
+ from .data import DATASET_VERSION, load_records
24
+ from .scoring import score_predictions
25
+ from .verify import run_checks
26
+
27
+ # Rows of published accuracies name a benchmark slice; map it to a release group.
28
+ BENCHMARK_GROUPS = {
29
+ "NL4Opt": "nl4opt",
30
+ "MAMO": "mamo",
31
+ "MAMO-Easy": "mamo-easy",
32
+ "MAMO-Complex": "mamo-complex",
33
+ "IndustryOR": "industryor",
34
+ }
35
+
36
+
37
+ def _fmt_band(band: tuple[float, float]) -> str:
38
+ """Render a (lo, hi) band as "[lo, hi]" at one decimal."""
39
+ return f"[{band[0]:.1f}, {band[1]:.1f}]"
40
+
41
+
42
+ def cmd_info(_args) -> int:
43
+ """Print the dataset summary (counts and error rates per family)."""
44
+ rates = error_rates()
45
+ print(f"benchtruthai {__version__}: cleaned release v{DATASET_VERSION} (109 instances)")
46
+ print("Source audit: Rangaraju (2026), 127 instances audited across NL4Opt,")
47
+ print("MAMO, IndustryOR, ComplexOR; 44 of 127 shipped answers materially")
48
+ print("wrong (34.6%, on the paper's v1.0.0 basis; 43 of 127 on the corrected")
49
+ print("v1.0.1 basis). This package ships the 109-instance main-audit release")
50
+ print("(ComplexOR extension instances are not redistributed).")
51
+ print()
52
+ for key in ("nl4opt", "mamo", "mamo-easy", "mamo-complex", "industryor", "all"):
53
+ r = rates[key]
54
+ print(
55
+ f"{key:14s} {r['errors']:3d}/{r['n']:3d} material errors "
56
+ f"({100 * r['rate']:.1f}%, Wilson 95% CI "
57
+ f"{100 * r['wilson_lo']:.1f}-{100 * r['wilson_hi']:.1f}%)"
58
+ )
59
+ return 0
60
+
61
+
62
+ def cmd_verify(_args) -> int:
63
+ """Recheck the release's headline numbers; exit 1 on any failure."""
64
+ passes, failures = run_checks()
65
+ for line in passes + failures:
66
+ print(line)
67
+ if failures:
68
+ print(f"\n{len(failures)} check(s) FAILED")
69
+ return 1
70
+ print("\nAll checks passed.")
71
+ return 0
72
+
73
+
74
+ def _read_predictions(path: str) -> dict[str, float | None]:
75
+ """Read a predictions JSONL file into {uid: predicted optimum}.
76
+
77
+ A record without a 'uid' is a hard error (SystemExit naming the
78
+ line); a missing 'predicted_optimum' reads as None (no prediction).
79
+ """
80
+ preds: dict[str, float | None] = {}
81
+ with open(path, encoding="utf-8") as fh:
82
+ for lineno, line in enumerate(fh, 1):
83
+ line = line.strip()
84
+ if not line:
85
+ continue
86
+ row = json.loads(line)
87
+ if "uid" not in row:
88
+ raise SystemExit(f"{path}:{lineno}: record has no 'uid'")
89
+ preds[row["uid"]] = row.get("predicted_optimum")
90
+ return preds
91
+
92
+
93
+ def cmd_score(args) -> int:
94
+ """Score a predictions file against both ground truths."""
95
+ records = load_records(family=args.family, split=args.split)
96
+ preds = _read_predictions(args.predictions)
97
+ try:
98
+ report = score_predictions(preds, records)
99
+ except KeyError as exc:
100
+ raise SystemExit(str(exc))
101
+ print(report.summary())
102
+ return 0
103
+
104
+
105
+ def cmd_personas(_args) -> int:
106
+ """Paper Table 2 demonstration, restricted to publicly checkable records.
107
+
108
+ The paper scores the two personas on all 40 NL4Opt instances; 12 of
109
+ those optima are withheld, so the full table cannot be recomputed
110
+ from public data. Here both personas are scored on the 28 NL4Opt dev
111
+ records whose audited optima are public. Every number printed for
112
+ those 28 records is checkable against the shipped release. The
113
+ Paper Table 2 line printed below is different in kind: its figures
114
+ are computed over all 40 NL4Opt instances, are cited from the
115
+ paper, and cannot be recomputed from the shipped release, because
116
+ the 12 test optima are withheld.
117
+ """
118
+ records = load_records(family="nl4opt", split="dev")
119
+ persona_a = {r.uid: r.audited_optimum for r in records} # faithful to the text
120
+ persona_b = {r.uid: r.shipped_optimum for r in records} # reproduces shipped GT
121
+ ra = score_predictions(persona_a, records)
122
+ rb = score_predictions(persona_b, records)
123
+ n = len(records)
124
+ flips = len(ra.flips)
125
+ print(f"Solver personas on the {n} NL4Opt dev instances (audited optima public):")
126
+ print(
127
+ f" A (answers the audited, text-faithful optimum): "
128
+ f"shipped GT {ra.shipped_correct}/{n} = {100 * ra.shipped_accuracy:.1f}%, "
129
+ f"audited GT {ra.cleaned_correct}/{n} = {100 * ra.cleaned_accuracy:.1f}%"
130
+ )
131
+ print(
132
+ f" B (answers the shipped optimum): "
133
+ f"shipped GT {rb.shipped_correct}/{n} = {100 * rb.shipped_accuracy:.1f}%, "
134
+ f"audited GT {rb.cleaned_correct}/{n} = {100 * rb.cleaned_accuracy:.1f}%"
135
+ )
136
+ print(
137
+ f" {flips} of {n} verdicts flip with the ground truth "
138
+ f"({100 * flips / n:.1f} points on this subset)."
139
+ )
140
+ print(
141
+ "Paper Table 2 (all 40 NL4Opt instances, incl. withheld test optima): "
142
+ "the same two personas score 72.5% vs 100%, a ±27.5-point swing. "
143
+ "Personas are constructed illustrations of the analytic bound, not "
144
+ "measurements of any published method."
145
+ )
146
+ return 0
147
+
148
+
149
+ def cmd_bands(args) -> int:
150
+ """Print sensitivity bands for each row of a CSV of published results."""
151
+ rates = error_rates()
152
+ with open(args.csv, newline="", encoding="utf-8") as fh:
153
+ rows = list(csv.DictReader(fh))
154
+ print(f"{'method':32s} {'benchmark':12s} {'published':>9s} {'central band':>15s} {'conservative':>15s}")
155
+ for row in rows:
156
+ bench = row["benchmark"]
157
+ if bench not in BENCHMARK_GROUPS:
158
+ raise SystemExit(
159
+ f"unknown benchmark {bench!r}; expected one of {sorted(BENCHMARK_GROUPS)}"
160
+ )
161
+ r = rates[BENCHMARK_GROUPS[bench]]
162
+ band = sensitivity_band(float(row["published_accuracy"]), r["rate"], r["wilson_hi"])
163
+ print(
164
+ f"{row['method']:32s} {bench:12s} {band['published']:8.2f}% "
165
+ f"{_fmt_band(band['central']):>15s} {_fmt_band(band['conservative']):>15s}"
166
+ )
167
+ print(
168
+ "\nBands per the audit paper §5.3: |text-faithful accuracy - published| <= e, "
169
+ "with e the ground-truth error rate of the benchmark slice (central: point "
170
+ "estimate; conservative: Wilson 95% upper bound), clipped to [0, 100]. "
171
+ "Nominal/illustrative, not inferential; they assume the audited error rate "
172
+ "generalizes to the published evaluation splits, an assumption this "
173
+ "audit does not establish."
174
+ )
175
+ return 0
176
+
177
+
178
+ def main(argv: list[str] | None = None) -> int:
179
+ """Parse arguments and dispatch to the subcommand; return its exit code."""
180
+ parser = argparse.ArgumentParser(
181
+ prog="benchtruthai",
182
+ description="Score optimization modeling predictions against audited ground truth.",
183
+ )
184
+ parser.add_argument("--version", action="version", version=f"benchtruthai {__version__}")
185
+ sub = parser.add_subparsers(dest="command", required=True)
186
+
187
+ sub.add_parser("info", help="dataset summary").set_defaults(fn=cmd_info)
188
+ sub.add_parser("verify", help="recheck release headline numbers").set_defaults(fn=cmd_verify)
189
+
190
+ p_score = sub.add_parser("score", help="score predictions (JSONL: uid, predicted_optimum)")
191
+ p_score.add_argument("predictions")
192
+ p_score.add_argument("--family", choices=["nl4opt", "mamo", "industryor"])
193
+ p_score.add_argument("--split", choices=["dev", "test"])
194
+ p_score.set_defaults(fn=cmd_score)
195
+
196
+ sub.add_parser("personas", help="paper persona demonstration (public dev split)").set_defaults(fn=cmd_personas)
197
+
198
+ p_bands = sub.add_parser("bands", help="sensitivity bands (bounds analysis, not corrected scores) for published accuracies (CSV)")
199
+ p_bands.add_argument("csv")
200
+ p_bands.set_defaults(fn=cmd_bands)
201
+
202
+ args = parser.parse_args(argv)
203
+ return args.fn(args)
204
+
205
+
206
+ if __name__ == "__main__":
207
+ sys.exit(main())
benchtruthai/data.py ADDED
@@ -0,0 +1,110 @@
1
+ """Dataset access for the bundled cleaned release (v1.0.1).
2
+
3
+ The v1.0.0 release file was copied verbatim from the public reproduction
4
+ package (github.com/pchi1606/benchmark-ground-truth-audit), sha256
5
+ 8aba71595a59d415445e3cc054a23e1e0aaeff43caeb894a0fd720415c56763d.
6
+ Dataset v1.0.1 differs from v1.0.0 in the root cause notes
7
+ of five test split records, which in v1.0.0 stated the recomputed value the
8
+ release withholds; v1.0.1 states the verdict and root cause without the
9
+ value. The only other difference is the embedded ``version`` field,
10
+ which reads 1.0.1 in every v1.0.1 record (1.0.0 in v1.0.0). No verdict,
11
+ label, optimum field, or commitment changed. The bundled v1.0.1 file's
12
+ sha256 is
13
+ 0f145f7e485f711cc8588b2feceda90dab6ea3b2b6a26675be44fd561ca6280b.
14
+
15
+ Each record carries a stable ID for each instance (`uid`, e.g.
16
+ ``nl4opt-prob_26``), the problem text, the benchmark's shipped optimum,
17
+ the optimum audited with a solver (dev split only; optima on the test
18
+ split are withheld under published sha256 commitments), the audit
19
+ verdict, error class, root cause category and note, the pinned upstream source, and a
20
+ contamination canary.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ from dataclasses import dataclass
27
+ from importlib import resources
28
+
29
+ DATASET_VERSION = "1.0.1"
30
+ _RELEASE_FILE = "cleaned_release_v1.0.1.jsonl"
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class Record:
35
+ """One released audit instance, as loaded from the release JSONL.
36
+
37
+ ``audited_optimum`` is None exactly on the test split, where the
38
+ audited value is withheld and only its sha256 commitment is public.
39
+ """
40
+
41
+ uid: str
42
+ family: str # 'nl4opt' | 'mamo' | 'industryor'
43
+ split: str # 'dev' | 'test'
44
+ problem_text: str
45
+ shipped_optimum: float | None
46
+ audited_optimum: float | None # None on the test split (withheld)
47
+ audited_status: str
48
+ verdict: str # 'clean' | 'material_error'
49
+ error_class: str | None
50
+ root_cause_category: str | None
51
+ root_cause_note: str | None
52
+ source: str
53
+ text_sha256: str
54
+ optimum_commitment_sha256: str | None
55
+ canary: str
56
+ version: str
57
+
58
+ @property
59
+ def slice(self) -> str:
60
+ """Finer slice: MAMO splits into easy/complex by uid prefix."""
61
+ if self.family == "mamo":
62
+ if self.uid.startswith("mamo-easy"):
63
+ return "mamo-easy"
64
+ if self.uid.startswith("mamo-complex"):
65
+ return "mamo-complex"
66
+ return self.family
67
+
68
+ @classmethod
69
+ def from_dict(cls, d: dict) -> "Record":
70
+ """Build a Record from one object in the release JSONL.
71
+
72
+ Required keys are read directly; optional audit fields default
73
+ to None or "" when absent, so partial rows stay loadable. One
74
+ exception: `version` defaults to the dataset version
75
+ (DATASET_VERSION, "1.0.1") when absent.
76
+ """
77
+ return cls(
78
+ uid=d["uid"],
79
+ family=d["family"],
80
+ split=d["split"],
81
+ problem_text=d["problem_text"],
82
+ shipped_optimum=d.get("shipped_optimum"),
83
+ audited_optimum=d.get("audited_optimum"),
84
+ audited_status=d.get("audited_status", ""),
85
+ verdict=d["verdict"],
86
+ error_class=d.get("error_class"),
87
+ root_cause_category=d.get("root_cause_category"),
88
+ root_cause_note=d.get("root_cause_note"),
89
+ source=d.get("source", ""),
90
+ text_sha256=d.get("text_sha256", ""),
91
+ optimum_commitment_sha256=d.get("optimum_commitment_sha256"),
92
+ canary=d.get("canary", ""),
93
+ version=d.get("version", DATASET_VERSION),
94
+ )
95
+
96
+
97
+ def load_records(family: str | None = None, split: str | None = None) -> list[Record]:
98
+ """Load release records, optionally filtered by family and/or split."""
99
+ path = resources.files("benchtruthai.datasets").joinpath(_RELEASE_FILE)
100
+ records = []
101
+ with path.open(encoding="utf-8") as fh:
102
+ for line in fh:
103
+ line = line.strip()
104
+ if line:
105
+ records.append(Record.from_dict(json.loads(line)))
106
+ if family is not None:
107
+ records = [r for r in records if r.family == family]
108
+ if split is not None:
109
+ records = [r for r in records if r.split == split]
110
+ return records
@@ -0,0 +1 @@
1
+ """Bundled dataset files for benchtruthai (release JSONL + commitments)."""