AntonioJun commited on
Commit
9c3f84d
·
verified ·
1 Parent(s): 2835c80

Replace analysis with local workspace contents

Browse files
analysis/A_reports.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate the high-level within-A report."""
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+ from analysis.letters_reports import generate_letter
6
+
7
+ LETTER = "A"
8
+
9
+
10
+ def generate(
11
+ results_dir,
12
+ protocols=(),
13
+ output_dir=None,
14
+ spatial_codes_dir=None,
15
+ profile_path=None,
16
+ ):
17
+ return generate_letter(
18
+ LETTER, results_dir, protocols, output_dir, spatial_codes_dir, profile_path
19
+ )
20
+
21
+
22
+ def main():
23
+ p = argparse.ArgumentParser(description="Generate the high-level within-A report.")
24
+ p.add_argument("--results-dir", default="/root/results/A")
25
+ p.add_argument("--protocol", action="append", default=[])
26
+ p.add_argument("--output-dir", default="/workspace/reports")
27
+ p.add_argument("--spatial-codes-dir", default=None)
28
+ a = p.parse_args()
29
+ result = generate(a.results_dir, a.protocol, a.output_dir, a.spatial_codes_dir)
30
+ print(f"wrote {result['path']}")
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main()
analysis/B_reports.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate the high-level within-B report."""
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+ from analysis.letters_reports import generate_letter
6
+
7
+ LETTER = "B"
8
+
9
+
10
+ def generate(
11
+ results_dir,
12
+ protocols=(),
13
+ output_dir=None,
14
+ spatial_codes_dir=None,
15
+ profile_path=None,
16
+ ):
17
+ return generate_letter(
18
+ LETTER, results_dir, protocols, output_dir, spatial_codes_dir, profile_path
19
+ )
20
+
21
+
22
+ def main():
23
+ p = argparse.ArgumentParser(description="Generate the high-level within-B report.")
24
+ p.add_argument("--results-dir", default="/root/results/B")
25
+ p.add_argument("--protocol", action="append", default=[])
26
+ p.add_argument("--output-dir", default="/workspace/reports")
27
+ p.add_argument("--spatial-codes-dir", default=None)
28
+ a = p.parse_args()
29
+ result = generate(a.results_dir, a.protocol, a.output_dir, a.spatial_codes_dir)
30
+ print(f"wrote {result['path']}")
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main()
analysis/C_reports.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate the high-level within-C report."""
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+ from analysis.letters_reports import generate_letter
6
+
7
+ LETTER = "C"
8
+
9
+
10
+ def generate(
11
+ results_dir,
12
+ protocols=(),
13
+ output_dir=None,
14
+ spatial_codes_dir=None,
15
+ profile_path=None,
16
+ ):
17
+ return generate_letter(
18
+ LETTER, results_dir, protocols, output_dir, spatial_codes_dir, profile_path
19
+ )
20
+
21
+
22
+ def main():
23
+ p = argparse.ArgumentParser(description="Generate the high-level within-C report.")
24
+ p.add_argument("--results-dir", default="/root/results/C")
25
+ p.add_argument("--protocol", action="append", default=[])
26
+ p.add_argument("--output-dir", default="/workspace/reports")
27
+ p.add_argument("--spatial-codes-dir", default=None)
28
+ a = p.parse_args()
29
+ result = generate(a.results_dir, a.protocol, a.output_dir, a.spatial_codes_dir)
30
+ print(f"wrote {result['path']}")
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main()
analysis/F_reports.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate the high-level within-F report."""
2
+
3
+ import argparse
4
+ from pathlib import Path
5
+ from analysis.letters_reports import generate_letter
6
+
7
+ LETTER = "F"
8
+
9
+
10
+ def generate(
11
+ results_dir,
12
+ protocols=(),
13
+ output_dir=None,
14
+ spatial_codes_dir=None,
15
+ profile_path=None,
16
+ ):
17
+ return generate_letter(
18
+ LETTER, results_dir, protocols, output_dir, spatial_codes_dir, profile_path
19
+ )
20
+
21
+
22
+ def main():
23
+ p = argparse.ArgumentParser(description="Generate the high-level within-F report.")
24
+ p.add_argument("--results-dir", default="/root/results/F")
25
+ p.add_argument("--protocol", action="append", default=[])
26
+ p.add_argument("--output-dir", default="/workspace/reports")
27
+ p.add_argument("--spatial-codes-dir", default=None)
28
+ a = p.parse_args()
29
+ result = generate(a.results_dir, a.protocol, a.output_dir, a.spatial_codes_dir)
30
+ print(f"wrote {result['path']}")
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main()
analysis/letters_reports.py ADDED
@@ -0,0 +1,1132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Comprehensive, matched A/B/C result analysis.
2
+
3
+ Reports coverage, score, question-type and dataset breakdowns, response/prompt/token
4
+ lengths, latency, limit/forced rates, spatial-code size for B/C, score relationships,
5
+ and pairwise deltas on exact question intersections. Stored per-question scores are
6
+ used directly; ``mean_score`` is not the category-weighted official VSI overall.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import math
15
+ import statistics
16
+ import random
17
+ from collections import Counter, defaultdict
18
+ from itertools import combinations
19
+ from pathlib import Path
20
+
21
+ ROOT = Path(__file__).resolve().parent.parent
22
+ DEFAULT_DIRS = {h: Path("/root/results") / h for h in "ABCE"}
23
+ NUMERIC_FIELDS = (
24
+ "input_token_count",
25
+ "output_token_count",
26
+ "reasoning_token_count",
27
+ "generation_seconds",
28
+ "forced_input_token_count",
29
+ )
30
+ TEXT_FIELDS = (
31
+ "answer_given",
32
+ "answer_raw",
33
+ "reasoning_text",
34
+ "full_prompt",
35
+ "rendered_prompt",
36
+ )
37
+
38
+
39
+ def iter_records(directory):
40
+ root = Path(directory)
41
+ if not root.is_dir():
42
+ return
43
+ for path in sorted(root.rglob("*.json")):
44
+ try:
45
+ with path.open(encoding="utf-8") as stream:
46
+ record = json.load(stream)
47
+ except (OSError, json.JSONDecodeError):
48
+ continue
49
+ if (
50
+ isinstance(record, dict)
51
+ and "question_id" in record
52
+ and "condition" in record
53
+ ):
54
+ yield record
55
+
56
+
57
+ def protocol_selected(protocol, selectors):
58
+ if protocol is None:
59
+ return not selectors
60
+ return not selectors or any(
61
+ protocol == item or ("/" not in item and protocol.startswith(item + "/"))
62
+ for item in selectors
63
+ )
64
+
65
+
66
+ def cell_identity(harness, record):
67
+ protocol = record.get("protocol") or record["condition"].split(":", 1)[0]
68
+ selection = record.get("frame_selection", record.get("input_selection"))
69
+ common = {
70
+ "harness": harness,
71
+ "model": record.get("model"),
72
+ "protocol": protocol,
73
+ "selection": selection,
74
+ "frames": str(record.get("frame_count")),
75
+ }
76
+ if harness in ("B", "C"):
77
+ common.update(
78
+ {
79
+ "format": record.get("spatial_code_format"),
80
+ "depth": record.get("depth"),
81
+ "tracking": record.get("tracking"),
82
+ }
83
+ )
84
+ return tuple(sorted(common.items()))
85
+
86
+
87
+ def identity_dict(identity):
88
+ return dict(identity)
89
+
90
+
91
+ def cell_label(identity):
92
+ d = identity_dict(identity)
93
+ parts = [
94
+ d["harness"],
95
+ d.get("model"),
96
+ d.get("protocol"),
97
+ d.get("selection"),
98
+ d.get("frames"),
99
+ ]
100
+ if d["harness"] in ("B", "C"):
101
+ parts += [d.get("format"), d.get("depth"), d.get("tracking")]
102
+ return "/".join("?" if value is None else str(value) for value in parts)
103
+
104
+
105
+ def comparison_key(identity):
106
+ d = identity_dict(identity)
107
+ return d.get("model"), d.get("protocol"), d.get("selection"), d.get("frames")
108
+
109
+
110
+ def _numbers(records, getter):
111
+ out = []
112
+ for record in records:
113
+ value = getter(record)
114
+ if (
115
+ isinstance(value, (int, float))
116
+ and not isinstance(value, bool)
117
+ and math.isfinite(value)
118
+ ):
119
+ out.append(float(value))
120
+ return out
121
+
122
+
123
+ def numeric_summary(values):
124
+ values = sorted(values)
125
+ if not values:
126
+ return None
127
+
128
+ def percentile(p):
129
+ position = (len(values) - 1) * p
130
+ low, high = math.floor(position), math.ceil(position)
131
+ if low == high:
132
+ return values[low]
133
+ return values[low] + (values[high] - values[low]) * (position - low)
134
+
135
+ return {
136
+ "n": len(values),
137
+ "mean": statistics.mean(values),
138
+ "median": statistics.median(values),
139
+ "min": values[0],
140
+ "p25": percentile(0.25),
141
+ "p75": percentile(0.75),
142
+ "max": values[-1],
143
+ "stdev": statistics.stdev(values) if len(values) > 1 else 0.0,
144
+ }
145
+
146
+
147
+ def pearson(xs, ys):
148
+ pairs = [
149
+ (float(x), float(y))
150
+ for x, y in zip(xs, ys)
151
+ if isinstance(x, (int, float))
152
+ and isinstance(y, (int, float))
153
+ and not isinstance(x, bool)
154
+ and not isinstance(y, bool)
155
+ and math.isfinite(x)
156
+ and math.isfinite(y)
157
+ ]
158
+ if len(pairs) < 2:
159
+ return None
160
+ x, y = zip(*pairs)
161
+ mx, my = statistics.mean(x), statistics.mean(y)
162
+ dx, dy = [v - mx for v in x], [v - my for v in y]
163
+ denom = math.sqrt(sum(v * v for v in dx) * sum(v * v for v in dy))
164
+ return sum(a * b for a, b in zip(dx, dy)) / denom if denom else None
165
+
166
+
167
+ def spatial_code_bytes(record, cache):
168
+ path = record.get("spatial_code_path")
169
+ if not path:
170
+ return None
171
+ if path not in cache:
172
+ try:
173
+ cache[path] = Path(path).stat().st_size
174
+ except OSError:
175
+ cache[path] = None
176
+ return cache[path]
177
+
178
+
179
+ def breakdown(records, field):
180
+ groups = defaultdict(list)
181
+ for record in records:
182
+ groups[str(record.get(field) or "<missing>")].append(record)
183
+ return {
184
+ name: {
185
+ "count": len(group),
186
+ "mean_score": (
187
+ numeric_summary(_numbers(group, lambda r: r.get("score")))["mean"]
188
+ if _numbers(group, lambda r: r.get("score"))
189
+ else None
190
+ ),
191
+ "scenes": len({r.get("scene") for r in group}),
192
+ }
193
+ for name, group in sorted(groups.items())
194
+ }
195
+
196
+
197
+ def summarize_cell(records, code_cache):
198
+ scores = _numbers(records, lambda r: r.get("score"))
199
+ numeric = {
200
+ field: numeric_summary(_numbers(records, lambda r, f=field: r.get(f)))
201
+ for field in NUMERIC_FIELDS
202
+ }
203
+ text = {
204
+ field
205
+ + "_chars": numeric_summary(
206
+ _numbers(
207
+ records,
208
+ lambda r, f=field: len(r[f]) if isinstance(r.get(f), str) else None,
209
+ )
210
+ )
211
+ for field in TEXT_FIELDS
212
+ }
213
+ code_sizes = _numbers(records, lambda r: spatial_code_bytes(r, code_cache))
214
+ relationships = {}
215
+ measures = {
216
+ **{field: lambda r, f=field: r.get(f) for field in NUMERIC_FIELDS},
217
+ **{
218
+ field
219
+ + "_chars": lambda r, f=field: (
220
+ len(r[f]) if isinstance(r.get(f), str) else None
221
+ )
222
+ for field in TEXT_FIELDS
223
+ },
224
+ "spatial_code_bytes": lambda r: spatial_code_bytes(r, code_cache),
225
+ }
226
+ for name, getter in measures.items():
227
+ pairs = [(r.get("score"), getter(r)) for r in records]
228
+ relationships["score_vs_" + name] = pearson(
229
+ [p[1] for p in pairs], [p[0] for p in pairs]
230
+ )
231
+ return {
232
+ "questions": len(records),
233
+ "unique_question_ids": len({r["question_id"] for r in records}),
234
+ "scenes": len({r.get("scene") for r in records}),
235
+ "mean_score": statistics.mean(scores) if scores else None,
236
+ "score_distribution": numeric_summary(scores),
237
+ "question_types": breakdown(records, "question_type"),
238
+ "datasets": breakdown(records, "dataset"),
239
+ "numeric": numeric,
240
+ "text_lengths": text,
241
+ "rates": {
242
+ "hit_token_limit": (
243
+ statistics.mean(bool(r.get("hit_token_limit")) for r in records)
244
+ if records
245
+ else None
246
+ ),
247
+ "reasoning_hit_limit": (
248
+ statistics.mean(bool(r.get("reasoning_hit_limit")) for r in records)
249
+ if records
250
+ else None
251
+ ),
252
+ "reasoning_present": (
253
+ statistics.mean(
254
+ bool(r.get("reasoning_text") or r.get("reasoning_raw"))
255
+ for r in records
256
+ )
257
+ if records
258
+ else None
259
+ ),
260
+ "forced": (
261
+ statistics.mean(bool(r.get("forced")) for r in records)
262
+ if records
263
+ else None
264
+ ),
265
+ "scored": len(scores) / len(records) if records else None,
266
+ },
267
+ "spatial_codes": {
268
+ "records_with_path": sum(bool(r.get("spatial_code_path")) for r in records),
269
+ "unique_paths": len(
270
+ {
271
+ r.get("spatial_code_path")
272
+ for r in records
273
+ if r.get("spatial_code_path")
274
+ }
275
+ ),
276
+ "readable_file_bytes": numeric_summary(code_sizes),
277
+ },
278
+ "relationships": relationships,
279
+ }
280
+
281
+
282
+ def paired_breakdown(x, y, common, field):
283
+ groups = defaultdict(list)
284
+ for qid in common:
285
+ name = str(x[qid].get(field) or y[qid].get(field) or "<missing>")
286
+ groups[name].append(y[qid].get("score") - x[qid].get("score"))
287
+ return {
288
+ name: {"count": len(vals), "mean_delta": statistics.mean(vals)}
289
+ for name, vals in sorted(groups.items())
290
+ if vals
291
+ }
292
+
293
+
294
+ def _scene_bootstrap(x, y, common, iterations=1000, seed=0):
295
+ by_scene = defaultdict(list)
296
+ for qid in common:
297
+ by_scene[str(x[qid].get("scene") or y[qid].get("scene") or "<missing>")].append(
298
+ y[qid]["score"] - x[qid]["score"]
299
+ )
300
+ if not by_scene:
301
+ return {
302
+ "scenes": 0,
303
+ "iterations": iterations,
304
+ "ci_low": None,
305
+ "ci_high": None,
306
+ "p_value": None,
307
+ }
308
+ scenes = sorted(by_scene)
309
+ rng = random.Random(seed)
310
+ draws = []
311
+ for _ in range(iterations):
312
+ values = []
313
+ for _ in scenes:
314
+ values.extend(by_scene[rng.choice(scenes)])
315
+ draws.append(statistics.mean(values))
316
+ draws.sort()
317
+ low = int(0.025 * iterations)
318
+ high = min(iterations - 1, int(0.975 * iterations))
319
+ below = sum(v <= 0 for v in draws) / iterations
320
+ above = sum(v >= 0 for v in draws) / iterations
321
+ return {
322
+ "scenes": len(scenes),
323
+ "iterations": iterations,
324
+ "seed": seed,
325
+ "confidence": 0.95,
326
+ "ci_low": draws[low],
327
+ "ci_high": draws[high],
328
+ "p_value": max(1 / iterations, min(1.0, 2 * min(below, above))),
329
+ }
330
+
331
+
332
+ def paired_report(x_records, y_records):
333
+ x = {
334
+ r["question_id"]: r
335
+ for r in x_records
336
+ if isinstance(r.get("score"), (int, float))
337
+ }
338
+ y = {
339
+ r["question_id"]: r
340
+ for r in y_records
341
+ if isinstance(r.get("score"), (int, float))
342
+ }
343
+ common = sorted(set(x) & set(y))
344
+ deltas = [y[q]["score"] - x[q]["score"] for q in common]
345
+ solved_x = {q for q in common if x[q]["score"] >= 1.0}
346
+ solved_y = {q for q in common if y[q]["score"] >= 1.0}
347
+ union = solved_x | solved_y
348
+ telemetry = {}
349
+ for field in NUMERIC_FIELDS:
350
+ vals = [
351
+ y[q].get(field) - x[q].get(field)
352
+ for q in common
353
+ if isinstance(x[q].get(field), (int, float))
354
+ and isinstance(y[q].get(field), (int, float))
355
+ ]
356
+ telemetry[field + "_delta"] = numeric_summary(vals)
357
+ return {
358
+ "common_questions": len(common),
359
+ "x_full_questions": len(x),
360
+ "y_full_questions": len(y),
361
+ "mean_score_delta_y_minus_x": statistics.mean(deltas) if deltas else None,
362
+ "score_delta_distribution": numeric_summary(deltas),
363
+ "wins_y": sum(d > 0 for d in deltas),
364
+ "ties": sum(d == 0 for d in deltas),
365
+ "wins_x": sum(d < 0 for d in deltas),
366
+ "scene_clustered_bootstrap": _scene_bootstrap(x, y, common),
367
+ "solved_overlap": {
368
+ "x": len(solved_x),
369
+ "y": len(solved_y),
370
+ "both": len(solved_x & solved_y),
371
+ "only_x": len(solved_x - solved_y),
372
+ "only_y": len(solved_y - solved_x),
373
+ "jaccard": len(solved_x & solved_y) / len(union) if union else None,
374
+ },
375
+ "by_question_type": paired_breakdown(x, y, common, "question_type"),
376
+ "by_dataset": paired_breakdown(x, y, common, "dataset"),
377
+ "telemetry_deltas": telemetry,
378
+ }
379
+
380
+
381
+ def analyze(directories=None, protocols=()):
382
+ directories = directories or DEFAULT_DIRS
383
+ cells = defaultdict(list)
384
+ for harness, directory in directories.items():
385
+ for record in iter_records(directory):
386
+ protocol = record.get("protocol") or record["condition"].split(":", 1)[0]
387
+ if protocol_selected(protocol, protocols):
388
+ cells[cell_identity(harness, record)].append(record)
389
+ code_cache = {}
390
+ report = {"cells": {}, "comparison_groups": {}}
391
+ for identity, records in cells.items():
392
+ report["cells"][cell_label(identity)] = {
393
+ "identity": identity_dict(identity),
394
+ "summary": summarize_cell(records, code_cache),
395
+ }
396
+ grouped = defaultdict(list)
397
+ for identity in cells:
398
+ grouped[comparison_key(identity)].append(identity)
399
+ for key, identities in grouped.items():
400
+ name = "/".join("?" if v is None else str(v) for v in key)
401
+ pairs = {}
402
+ for first, second in combinations(sorted(identities, key=cell_label), 2):
403
+ pairs[cell_label(first) + " -> " + cell_label(second)] = paired_report(
404
+ cells[first], cells[second]
405
+ )
406
+ id_sets = [{r["question_id"] for r in cells[i]} for i in identities]
407
+ report["comparison_groups"][name] = {
408
+ "cells": [cell_label(i) for i in identities],
409
+ "all_cell_common_questions": (
410
+ len(set.intersection(*id_sets)) if id_sets else 0
411
+ ),
412
+ "pairwise": pairs,
413
+ }
414
+ return report
415
+
416
+
417
+ def main():
418
+ parser = argparse.ArgumentParser()
419
+ for harness in "abc":
420
+ parser.add_argument(f"--{harness}-results-dir", default=None)
421
+ parser.add_argument(
422
+ "--protocol",
423
+ action="append",
424
+ default=[],
425
+ help="repeatable; select base or thinking protocol families",
426
+ )
427
+ parser.add_argument(
428
+ "--output-dir",
429
+ default=str(ROOT / "reports"),
430
+ help="report directory (default: workspace/reports)",
431
+ )
432
+ parser.add_argument(
433
+ "--json-out",
434
+ default=None,
435
+ help="override the JSON report path (default: <output-dir>/comprehensive.json)",
436
+ )
437
+ args = parser.parse_args()
438
+ dirs = {
439
+ h.upper(): Path(getattr(args, f"{h}_results_dir") or DEFAULT_DIRS[h.upper()])
440
+ for h in "abc"
441
+ }
442
+ report = analyze(dirs, args.protocol)
443
+ text = json.dumps(report, indent=1)
444
+ output_path = (
445
+ Path(args.json_out)
446
+ if args.json_out
447
+ else Path(args.output_dir) / "comprehensive.json"
448
+ )
449
+ output_path.parent.mkdir(parents=True, exist_ok=True)
450
+ output_path.write_text(text + "\n", encoding="utf-8")
451
+ print(f"wrote {output_path}")
452
+
453
+
454
+ # --- Modular profile-driven interface (v2) ---
455
+
456
+ # Built-in, versioned harness profiles.
457
+ PROFILE_VERSION = 1
458
+ BUILTINS = {
459
+ "A": {
460
+ "letter": "A",
461
+ "kind": "vlm",
462
+ "input_source": "frames",
463
+ "axes": ["model", "protocol", "selection", "frames"],
464
+ "capabilities": ["tokens", "latency", "reasoning", "frames"],
465
+ },
466
+ "B": {
467
+ "letter": "B",
468
+ "kind": "vlm",
469
+ "input_source": "perceived",
470
+ "axes": [
471
+ "model",
472
+ "protocol",
473
+ "format",
474
+ "depth",
475
+ "tracking",
476
+ "selection",
477
+ "frames",
478
+ ],
479
+ "capabilities": ["tokens", "latency", "reasoning", "spatial_code"],
480
+ },
481
+ "C": {
482
+ "letter": "C",
483
+ "kind": "vlm",
484
+ "input_source": "frames_perceived",
485
+ "axes": [
486
+ "model",
487
+ "protocol",
488
+ "format",
489
+ "depth",
490
+ "tracking",
491
+ "selection",
492
+ "frames",
493
+ ],
494
+ "capabilities": ["tokens", "latency", "reasoning", "frames", "spatial_code"],
495
+ },
496
+ "F": {
497
+ "letter": "F",
498
+ "kind": "solver",
499
+ "input_source": "dynamic",
500
+ "axes": [
501
+ "source",
502
+ "depth",
503
+ "tracking",
504
+ "selection",
505
+ "frames",
506
+ "format",
507
+ "spatial_code_model",
508
+ ],
509
+ "capabilities": ["spatial_code", "solver"],
510
+ },
511
+ }
512
+
513
+
514
+ def validate_profile(profile):
515
+ p = dict(profile)
516
+ letter = str(p.get("letter", "")).upper()
517
+ if len(letter) != 1 or not letter.isalpha():
518
+ raise ValueError("profile letter must be one alphabetic character")
519
+ p["letter"] = letter
520
+ p.setdefault("kind", "generic")
521
+ p.setdefault("input_source", "unknown")
522
+ p.setdefault("axes", ["model", "protocol"])
523
+ p.setdefault("capabilities", [])
524
+ p["profile_version"] = PROFILE_VERSION
525
+ return p
526
+
527
+
528
+ def load_profile(letter, path=None):
529
+ letter = letter.upper()
530
+ if path:
531
+ p = json.loads(Path(path).read_text())
532
+ p.setdefault("letter", letter)
533
+ if p["letter"].upper() != letter:
534
+ raise ValueError(f"profile letter mismatch for {letter}")
535
+ return validate_profile(p)
536
+ return validate_profile(
537
+ BUILTINS.get(
538
+ letter,
539
+ {
540
+ "letter": letter,
541
+ "kind": "generic",
542
+ "input_source": "unknown",
543
+ "axes": [
544
+ "model",
545
+ "protocol",
546
+ "format",
547
+ "depth",
548
+ "tracking",
549
+ "selection",
550
+ "frames",
551
+ ],
552
+ },
553
+ )
554
+ )
555
+
556
+
557
+ ANALYSIS_VERSION = 2
558
+
559
+
560
+ def discover_records(letter, directory, profile, protocols=(), spatial_codes_dir=None):
561
+ root = Path(directory)
562
+ records = []
563
+ warnings = []
564
+ if not root.is_dir():
565
+ return records, [{"code": "missing_directory", "path": str(root)}]
566
+ for path in sorted(root.rglob("*.json")):
567
+ if path.name.startswith("_"):
568
+ continue
569
+ try:
570
+ record = json.loads(path.read_text(encoding="utf-8"))
571
+ except (OSError, json.JSONDecodeError) as exc:
572
+ warnings.append(
573
+ {"code": "unreadable_json", "path": str(path), "detail": str(exc)}
574
+ )
575
+ continue
576
+ if (
577
+ not isinstance(record, dict)
578
+ or record.get("question_id") is None
579
+ or record.get("score") is None
580
+ ):
581
+ warnings.append({"code": "not_question_record", "path": str(path)})
582
+ continue
583
+ record = dict(record)
584
+ record["_result_path"] = str(path)
585
+ record["_relative_path"] = path.relative_to(root).parts
586
+ record = _normalize_record(letter, record, profile)
587
+ code_path = record.get("spatial_code_path")
588
+ if code_path and not Path(code_path).is_file() and spatial_codes_dir:
589
+ marker = "spatial codes/"
590
+ suffix = (
591
+ str(code_path).split(marker, 1)[-1]
592
+ if marker in str(code_path)
593
+ else None
594
+ )
595
+ candidate = Path(spatial_codes_dir) / suffix if suffix else None
596
+ if candidate and candidate.is_file():
597
+ record["spatial_code_path"] = str(candidate)
598
+ else:
599
+ warnings.append(
600
+ {
601
+ "code": "unresolved_spatial_code_path",
602
+ "path": str(path),
603
+ "recorded_path": str(code_path),
604
+ }
605
+ )
606
+ if letter != "F" and not protocol_selected(record.get("protocol"), protocols):
607
+ continue
608
+ records.append(record)
609
+ return records, warnings
610
+
611
+
612
+ def _normalize_record(letter, r, profile):
613
+ r["format"] = r.get("spatial_code_format") or r.get("format")
614
+ r["selection"] = (
615
+ r.get("frame_selection") or r.get("input_selection") or r.get("input")
616
+ )
617
+ r["frames"] = r.get("frame_count") or r.get("number_of_frames")
618
+ if not r.get("protocol") and r.get("condition") and letter != "F":
619
+ r["protocol"] = r["condition"].split(":", 1)[0]
620
+ if letter == "F":
621
+ parts = list(r.get("_relative_path", ()))
622
+ top = parts[0].lower() if parts else ""
623
+ r["source"] = "perceived"
624
+ offset = 1
625
+ if top == "perceived":
626
+ r["depth"] = r.get("depth") or (parts[1] if len(parts) > 1 else None)
627
+ offset = 2
628
+ elif top in ("metric", "relative"):
629
+ r["depth"] = r.get("depth") or top
630
+ r["tracking"] = r.get("tracking") or (
631
+ parts[offset] if len(parts) > offset else None
632
+ )
633
+ r["selection"] = r.get("selection") or (
634
+ parts[offset + 1] if len(parts) > offset + 1 else None
635
+ )
636
+ r["frames"] = r.get("frames") or (
637
+ parts[offset + 2] if len(parts) > offset + 2 else None
638
+ )
639
+ candidate = parts[offset + 3] if len(parts) > offset + 3 else None
640
+ if candidate and not candidate.startswith("scene") and len(candidate) != 10:
641
+ r["format"] = r.get("format") or candidate
642
+ r["spatial_code_model"] = r.get("spatial_code_model")
643
+ r["protocol"] = None
644
+ return r
645
+
646
+
647
+ def modular_identity(letter, record, profile):
648
+ values = {"harness": letter}
649
+ for axis in profile["axes"]:
650
+ values[axis] = str(record.get(axis)) if record.get(axis) is not None else None
651
+ return tuple(sorted(values.items()))
652
+
653
+
654
+ def modular_label(identity):
655
+ d = dict(identity)
656
+ return "/".join(
657
+ [d.pop("harness")] + [f"{k}={v or '?'}" for k, v in sorted(d.items())]
658
+ )
659
+
660
+
661
+ def _controlled(first, second, profile):
662
+ a, b = dict(first), dict(second)
663
+ diffs = [axis for axis in profile["axes"] if a.get(axis) != b.get(axis)]
664
+ return len(diffs) == 1, diffs
665
+
666
+
667
+ def _compatible(a, b, profiles):
668
+ x, y = dict(a), dict(b)
669
+ lx, ly = x["harness"], y["harness"]
670
+ warnings = []
671
+ if lx == ly:
672
+ return False, [], ["same_harness"]
673
+ # F source semantics.
674
+ f = x if lx == "F" else y if ly == "F" else None
675
+ other = y if lx == "F" else x
676
+ if f:
677
+ expected = "perceived" if other["harness"] in ("B", "C") else None
678
+ if expected and f.get("source") != expected:
679
+ return False, [], ["incompatible_F_source"]
680
+ shared = []
681
+ for axis in ("model", "format", "depth", "tracking", "selection", "frames"):
682
+ av, bv = x.get(axis), y.get(axis)
683
+ if axis == "model" and f:
684
+ continue
685
+ if av is not None and bv is not None:
686
+ if av != bv:
687
+ return False, [], [f"conflicting_{axis}"]
688
+ shared.append(axis)
689
+ else:
690
+ warnings.append(f"unmatched_{axis}")
691
+ if not f and x.get("protocol") is not None and y.get("protocol") is not None:
692
+ if x["protocol"] != y["protocol"]:
693
+ return False, [], ["conflicting_protocol"]
694
+ shared.append("protocol")
695
+ return True, shared, warnings
696
+
697
+
698
+ def _generated_at():
699
+ return os.environ.get("VSI_ANALYSIS_GENERATED_AT", "reproducible")
700
+
701
+
702
+ def analyze_modular(
703
+ cells, profiles, protocols=(), requested_pairs=(), spatial_codes_dir=None
704
+ ):
705
+ all_cells = defaultdict(list)
706
+ warnings = {}
707
+ sources = {}
708
+ for letter, directory in cells.items():
709
+ recs, warns = discover_records(
710
+ letter, directory, profiles[letter], protocols, spatial_codes_dir
711
+ )
712
+ warnings[letter] = warns
713
+ sources[letter] = str(directory)
714
+ for r in recs:
715
+ all_cells[modular_identity(letter, r, profiles[letter])].append(r)
716
+ cache = {}
717
+ per = {
718
+ letter: {
719
+ "manifest": {
720
+ "analysis_version": ANALYSIS_VERSION,
721
+ "profile_version": PROFILE_VERSION,
722
+ "generated_at": _generated_at(),
723
+ "letter": letter,
724
+ "profile": profiles[letter],
725
+ "source": sources[letter],
726
+ "protocols": list(protocols),
727
+ },
728
+ "cells": {},
729
+ "within_harness_comparisons": {},
730
+ "integrity_warnings": warnings[letter],
731
+ }
732
+ for letter in cells
733
+ }
734
+ for ident, recs in all_cells.items():
735
+ per[dict(ident)["harness"]]["cells"][modular_label(ident)] = {
736
+ "identity": dict(ident),
737
+ "summary": summarize_cell(recs, cache),
738
+ }
739
+ for letter in cells:
740
+ ids = [i for i in all_cells if dict(i)["harness"] == letter]
741
+ for a, b in combinations(ids, 2):
742
+ ok, diffs = _controlled(a, b, profiles[letter])
743
+ if ok:
744
+ per[letter]["within_harness_comparisons"][
745
+ modular_label(a) + " -> " + modular_label(b)
746
+ ] = {
747
+ "varied_axis": diffs[0],
748
+ **paired_report(all_cells[a], all_cells[b]),
749
+ }
750
+ allowed = {tuple(sorted(p)) for p in requested_pairs}
751
+ cross = {}
752
+ ids = list(all_cells)
753
+ for a, b in combinations(ids, 2):
754
+ letters = tuple(sorted((dict(a)["harness"], dict(b)["harness"])))
755
+ if letters[0] == letters[1] or (allowed and letters not in allowed):
756
+ continue
757
+ ok, shared, warns = _compatible(a, b, profiles)
758
+ if ok:
759
+ cross[modular_label(a) + " -> " + modular_label(b)] = {
760
+ "letters": letters,
761
+ "shared_axes": shared,
762
+ "alignment_warnings": warns,
763
+ **paired_report(all_cells[a], all_cells[b]),
764
+ }
765
+ manifest = {
766
+ "analysis_version": ANALYSIS_VERSION,
767
+ "profile_version": PROFILE_VERSION,
768
+ "generated_at": _generated_at(),
769
+ "letters": sorted(cells),
770
+ "sources": sources,
771
+ "protocols": list(protocols),
772
+ "requested_pairs": [":".join(p) for p in requested_pairs],
773
+ }
774
+ return per, {
775
+ "manifest": manifest,
776
+ "cross_harness_comparisons": cross,
777
+ "harness_summaries": {
778
+ l: {
779
+ "cell_count": len(per[l]["cells"]),
780
+ "warning_count": len(per[l]["integrity_warnings"]),
781
+ }
782
+ for l in per
783
+ },
784
+ }
785
+
786
+
787
+ def parse_assignment(value, option):
788
+ if "=" not in value:
789
+ raise argparse.ArgumentTypeError(f"{option} must be LETTER=PATH")
790
+ letter, path = value.split("=", 1)
791
+ letter = letter.upper()
792
+ if len(letter) != 1 or not letter.isalpha() or letter == "D":
793
+ raise argparse.ArgumentTypeError(
794
+ "letter must be one alphabetic character other than D"
795
+ )
796
+ return letter, path
797
+
798
+
799
+ def export_reports(per, combined, output_dir):
800
+ out = Path(output_dir)
801
+ out.mkdir(parents=True, exist_ok=True)
802
+ paths = []
803
+ for letter, report in sorted(per.items()):
804
+ path = out / f"{letter}_report.json"
805
+ path.write_text(json.dumps(report, indent=1) + "\n")
806
+ paths.append(path)
807
+ if len(per) > 1:
808
+ name = "".join(sorted(per)) + "_report.json"
809
+ path = out / name
810
+ path.write_text(json.dumps(combined, indent=1) + "\n")
811
+ paths.append(path)
812
+ return paths
813
+
814
+
815
+ def main():
816
+ parser = argparse.ArgumentParser()
817
+ parser.add_argument(
818
+ "--cell",
819
+ action="append",
820
+ default=[],
821
+ help="repeatable LETTER=PATH; D is removed",
822
+ )
823
+ parser.add_argument(
824
+ "--profile", action="append", default=[], help="optional LETTER=profile.json"
825
+ )
826
+ parser.add_argument(
827
+ "--compare",
828
+ action="append",
829
+ default=[],
830
+ help="optional pair restriction, e.g. A:B",
831
+ )
832
+ parser.add_argument(
833
+ "--protocol",
834
+ action="append",
835
+ default=[],
836
+ help="repeatable; select base or thinking protocol families",
837
+ )
838
+ parser.add_argument("--output-dir", default=str(ROOT / "reports"))
839
+ parser.add_argument(
840
+ "--spatial-codes-dir",
841
+ default=None,
842
+ help="optional local root used to rebase stale recorded code paths",
843
+ )
844
+ for h in "abce":
845
+ parser.add_argument(f"--{h}-results-dir", default=None, help=argparse.SUPPRESS)
846
+ args = parser.parse_args()
847
+ cells = dict(parse_assignment(v, "--cell") for v in args.cell)
848
+ for h in "abce":
849
+ value = getattr(args, f"{h}_results_dir")
850
+ if value:
851
+ cells[h.upper()] = value
852
+ if not cells:
853
+ parser.error("provide at least one --cell LETTER=PATH")
854
+ profile_paths = dict(parse_assignment(v, "--profile") for v in args.profile)
855
+ profiles = {
856
+ letter: load_profile(letter, profile_paths.get(letter)) for letter in cells
857
+ }
858
+ pairs = []
859
+ for value in args.compare:
860
+ bits = [x.upper() for x in value.split(":")]
861
+ if len(bits) != 2 or any(x not in cells for x in bits):
862
+ parser.error(f"invalid --compare {value}")
863
+ pairs.append(tuple(bits))
864
+ per, combined = analyze_modular(
865
+ cells, profiles, args.protocol, pairs, args.spatial_codes_dir
866
+ )
867
+ for path in export_reports(per, combined, args.output_dir):
868
+ print(f"wrote {path}")
869
+
870
+
871
+ # Consolidated analysis helpers formerly split across stats/solvability/sufficiency/audits.
872
+ def _official_scores(records):
873
+ records = list(records)
874
+ try:
875
+ import importlib.util, os
876
+
877
+ path = os.environ.get(
878
+ "HARNESS_OFFICIAL_EVAL",
879
+ "/root/data/thinking-in-space/lmms_eval/tasks/vsibench/utils.py",
880
+ )
881
+ spec = importlib.util.spec_from_file_location(
882
+ "analysis_vsi_official_eval", path
883
+ )
884
+ module = importlib.util.module_from_spec(spec)
885
+ spec.loader.exec_module(module)
886
+ docs = [
887
+ {
888
+ "question_type": r["question_type"],
889
+ "ground_truth": r.get("answer_expected"),
890
+ r["metric"]: r["score"],
891
+ }
892
+ for r in records
893
+ ]
894
+ return module.vsibench_aggregate_results(docs)
895
+ except (OSError, ImportError, AttributeError, TypeError):
896
+ scores = [
897
+ r.get("score") for r in records if isinstance(r.get("score"), (int, float))
898
+ ]
899
+ return {
900
+ "overall": statistics.mean(scores) * 100 if scores else None,
901
+ "scoring_mode": "stored_per_question_mean_fallback",
902
+ }
903
+
904
+
905
+ def holm_bonferroni(p_values):
906
+ ordered = sorted(p_values.items(), key=lambda item: item[1])
907
+ total = len(ordered)
908
+ out = {}
909
+ running = 0.0
910
+ for rank, (name, p) in enumerate(ordered):
911
+ running = max(running, min(1.0, (total - rank) * p))
912
+ out[name] = running
913
+ return out
914
+
915
+
916
+ def solved_set_overlap(cells, threshold=1.0):
917
+ maps = {
918
+ name: {r["question_id"]: r.get("score") for r in records}
919
+ for name, records in cells.items()
920
+ }
921
+ common = set.intersection(*(set(m) for m in maps.values())) if maps else set()
922
+ solved = {
923
+ n: {q for q in common if v[q] is not None and v[q] >= threshold}
924
+ for n, v in maps.items()
925
+ }
926
+ pairs = {}
927
+ for a, b in combinations(sorted(solved), 2):
928
+ union = solved[a] | solved[b]
929
+ pairs[f"{a}|{b}"] = {
930
+ "jaccard": len(solved[a] & solved[b]) / len(union) if union else None,
931
+ "both": len(solved[a] & solved[b]),
932
+ f"only_{a}": len(solved[a] - solved[b]),
933
+ f"only_{b}": len(solved[b] - solved[a]),
934
+ }
935
+ return {
936
+ "questions": len(common),
937
+ "solved": {n: len(v) for n, v in solved.items()},
938
+ "pairs": pairs,
939
+ }
940
+
941
+
942
+ def sufficiency_decomposition(vlm_records, solver_records, threshold=1.0, exclude=()):
943
+ cert = {
944
+ r["question_id"]: r.get("score") is not None and r["score"] >= threshold
945
+ for r in solver_records
946
+ }
947
+ buckets = {"certified": [], "uncertified": []}
948
+ for r in vlm_records:
949
+ if r.get("question_type") in set(exclude) or r.get("question_id") not in cert:
950
+ continue
951
+ buckets["certified" if cert[r["question_id"]] else "uncertified"].append(
952
+ r.get("score")
953
+ )
954
+
955
+ def summary(vals):
956
+ valid = [v for v in vals if isinstance(v, (int, float))]
957
+ correct = sum(v >= threshold for v in valid)
958
+ return {
959
+ "count": len(vals),
960
+ "mean_score": statistics.mean(valid) if valid else None,
961
+ "vlm_correct": correct,
962
+ "vlm_wrong": len(vals) - correct,
963
+ }
964
+
965
+ return {name: summary(vals) for name, vals in buckets.items()}
966
+
967
+
968
+ def solver_depth_table(records):
969
+ try:
970
+ from symbolic import adapters, solver
971
+ except ImportError:
972
+ return {
973
+ "status": "unavailable",
974
+ "reason": "symbolic solver imports unavailable",
975
+ }
976
+ cache = {}
977
+ buckets = defaultdict(list)
978
+ for r in records:
979
+ path = r.get("spatial_code_path")
980
+ if not path:
981
+ continue
982
+ try:
983
+ if path not in cache:
984
+ cache[path] = adapters.adapt_spatial_code(
985
+ json.loads(Path(path).read_text())
986
+ )
987
+ solver.answer(
988
+ r["question_type"], r["question"], r.get("options"), cache[path]
989
+ )
990
+ depth = solver.LAST_ANSWER_OPS.get("total")
991
+ except (OSError, KeyError, ValueError):
992
+ continue
993
+ if depth is not None and isinstance(r.get("score"), (int, float)):
994
+ buckets[
995
+ (
996
+ "0-2"
997
+ if depth <= 2
998
+ else "3-8" if depth <= 8 else "9-20" if depth <= 20 else "21-inf"
999
+ )
1000
+ ].append((depth, r["score"]))
1001
+ return {
1002
+ k: {
1003
+ "count": len(v),
1004
+ "mean_depth": statistics.mean(x for x, _ in v),
1005
+ "mean_score": statistics.mean(y for _, y in v),
1006
+ }
1007
+ for k, v in buckets.items()
1008
+ }
1009
+
1010
+
1011
+ _NUMBER_RE = __import__("re").compile(r"[-+]?\d+(?:\.\d+)?")
1012
+
1013
+
1014
+ def deterministic_cot_audit(records, tolerance=0.01):
1015
+ def nums(value):
1016
+ return [float(x) for x in _NUMBER_RE.findall(str(value or ""))]
1017
+
1018
+ audits = []
1019
+ cache = {}
1020
+ for r in records:
1021
+ reasoning = r.get("reasoning_text")
1022
+ path = r.get("spatial_code_path")
1023
+ if not reasoning or not path:
1024
+ continue
1025
+ try:
1026
+ if path not in cache:
1027
+ cache[path] = nums(Path(path).read_text())
1028
+ except OSError:
1029
+ continue
1030
+ sources = (
1031
+ cache[path]
1032
+ + nums(r.get("question"))
1033
+ + sum((nums(x) for x in r.get("options") or []), [])
1034
+ )
1035
+ cited = nums(reasoning)
1036
+ fabricated = [
1037
+ v
1038
+ for v in cited
1039
+ if not (abs(v) <= 12 and v.is_integer())
1040
+ and not any(abs(v - x) <= tolerance * max(1, abs(x)) for x in sources)
1041
+ ]
1042
+ audits.append(
1043
+ {
1044
+ "question_id": r["question_id"],
1045
+ "score": r.get("score"),
1046
+ "cited": len(cited),
1047
+ "fabricated": len(fabricated),
1048
+ }
1049
+ )
1050
+ wrong = [a for a in audits if a["score"] is not None and a["score"] < 1]
1051
+ bad = [a for a in wrong if a["fabricated"]]
1052
+ return {
1053
+ "audited": len(audits),
1054
+ "wrong": len(wrong),
1055
+ "wrong_with_fabrication": len(bad),
1056
+ "fabrication_share_of_wrong": len(bad) / len(wrong) if wrong else None,
1057
+ }
1058
+
1059
+
1060
+ def generate_letter(
1061
+ letter,
1062
+ results_dir,
1063
+ protocols=(),
1064
+ output_dir=None,
1065
+ spatial_codes_dir=None,
1066
+ profile_path=None,
1067
+ ):
1068
+ letter = letter.upper()
1069
+ profile = load_profile(letter, profile_path)
1070
+ per, combined = analyze_modular(
1071
+ {letter: Path(results_dir)}, {letter: profile}, protocols, (), spatial_codes_dir
1072
+ )
1073
+ paths = export_reports(per, combined, output_dir or ROOT / "reports")
1074
+ return {"report": per[letter], "path": paths[0]}
1075
+
1076
+
1077
+ def generate(
1078
+ cells,
1079
+ protocols=(),
1080
+ comparisons=(),
1081
+ output_dir=None,
1082
+ profile_paths=None,
1083
+ spatial_codes_dir=None,
1084
+ ):
1085
+ normalized = {str(k).upper(): Path(v) for k, v in cells.items()}
1086
+ profile_paths = {str(k).upper(): v for k, v in (profile_paths or {}).items()}
1087
+ profiles = {l: load_profile(l, profile_paths.get(l)) for l in normalized}
1088
+ pairs = []
1089
+ for pair in comparisons:
1090
+ pair = tuple(
1091
+ x.upper() for x in (pair.split(":") if isinstance(pair, str) else pair)
1092
+ )
1093
+ if len(pair) != 2 or any(x not in normalized for x in pair):
1094
+ raise ValueError(f"invalid comparison {pair}")
1095
+ pairs.append(pair)
1096
+ per, combined = analyze_modular(
1097
+ normalized, profiles, protocols, pairs, spatial_codes_dir
1098
+ )
1099
+ paths = export_reports(per, combined, output_dir or ROOT / "reports")
1100
+ return {"letter_reports": per, "combined_report": combined, "paths": paths}
1101
+
1102
+
1103
+ def main():
1104
+ parser = argparse.ArgumentParser(
1105
+ description="Generate arbitrary mixed letter reports; D is removed."
1106
+ )
1107
+ parser.add_argument("--cell", action="append", required=True)
1108
+ parser.add_argument("--profile", action="append", default=[])
1109
+ parser.add_argument("--compare", action="append", default=[])
1110
+ parser.add_argument("--protocol", action="append", default=[])
1111
+ parser.add_argument("--output-dir", default=str(ROOT / "reports"))
1112
+ parser.add_argument("--spatial-codes-dir", default=None)
1113
+ args = parser.parse_args()
1114
+ cells = dict(parse_assignment(v, "--cell") for v in args.cell)
1115
+ profiles = dict(parse_assignment(v, "--profile") for v in args.profile)
1116
+ try:
1117
+ result = generate(
1118
+ cells,
1119
+ args.protocol,
1120
+ args.compare,
1121
+ args.output_dir,
1122
+ profiles,
1123
+ args.spatial_codes_dir,
1124
+ )
1125
+ except ValueError as exc:
1126
+ parser.error(str(exc))
1127
+ for path in result["paths"]:
1128
+ print(f"wrote {path}")
1129
+
1130
+
1131
+ if __name__ == "__main__":
1132
+ main()