"""Regenerate or verify the CHRONO-SHEAF III Hugging Face Dataset Viewer tables. Uses only the Python standard library. Pass the archived results/ directory and the dataset repository root. Use --verify to compare without writing. """ import argparse from collections import Counter, defaultdict import csv import gzip import hashlib import json import math from pathlib import Path import statistics SWEEPS = (("initial", ""), ("repeat", "repeat")) CONDITION = {"B": "baseline", "A": "hook"} SPLITS = {True: "paced", False: "unpaced"} CONFIGS = { "runs": {"observed": "data/runs.jsonl"}, "input_events": {split: f"data/input_events_{split}.jsonl" for split in SPLITS.values()}, "frame_timings": {split: f"data/frame_timings_{split}.jsonl" for split in SPLITS.values()}, } RAW_FIELDS = ["run", "mode", "paced", "kind", "id", "frame", "t0_us", "t1_us", "application_return_us"] def require(check, context): if not check: raise ValueError(context) def nearest_rank(numbers, quantile): return sorted(numbers)[math.ceil(quantile * len(numbers)) - 1] def matches(actual, reference, context): for key, value in actual.items(): expected = reference[key] if isinstance(value, float): equal = math.isclose(value, expected, rel_tol=0, abs_tol=1e-10) else: equal = value == expected require(equal, f"{context}: {key}: calculated {value!r}, archived {expected!r}") def tagged_run(sweep, info): return { "sweep": sweep, "run_key": f"{sweep}:{info['run']:02d}", "run_index": info["run"], "condition": CONDITION[info["mode"]], "paced": info["paced"], } def parse_run(sweep, info, rows, warmup): tags = tagged_run(sweep, info) details = dict(field.split("=", 1) for field in info["details"].split()) require(details["driver"] == "dummy", f"{tags['run_key']}: expected SDL dummy driver") total_frames = int(details["frames"]) total_events = int(details["consumed"]) require(int(details["warmup"]) == warmup, f"{tags['run_key']}: warm-up mismatch") valid_symbols = {"F", "E"} require({row["kind"] for row in rows} <= valid_symbols, f"{tags['run_key']}: unknown row kind") expected_paced = "1" if info["paced"] else "0" for row in rows: require(row["mode"] == info["mode"] and row["paced"] == expected_paced, f"{tags['run_key']}: archived run labels mismatch") frame_rows = sorted( (row for row in rows if row["kind"] == "F"), key=lambda row: int(row["frame"]) ) event_rows = sorted( (row for row in rows if row["kind"] == "E"), key=lambda row: int(row["id"]) ) require(len(frame_rows) == total_frames and len(event_rows) == total_events, f"{tags['run_key']}: run totals mismatch") require(all(int(row["frame"]) == index for index, row in enumerate(frame_rows)), f"{tags['run_key']}: invalid frame indices") frames = [] prev_return = 0 prev_consumed = 0 for row in frame_rows: frame = int(row["frame"]) consumed = int(row["id"]) archived_previous = int(row["t0_us"]) present = int(row["t1_us"]) application = int(row["application_return_us"]) require(archived_previous == prev_return < present <= application, f"{tags['run_key']} frame {frame}: invalid present sequence") require(prev_consumed <= consumed, f"{tags['run_key']} frame {frame}: reversed counter") frames.append({ **tags, "frame_index": frame, "scored": frame >= warmup, "events_consumed_total": consumed, "events_consumed_this_frame": consumed - prev_consumed, "previous_present_return_us": prev_return or None, "present_return_us": present, "application_return_us": application, "present_return_interval_us": present - prev_return if prev_return else None, "post_present_return_us": application - present, }) prev_return = present prev_consumed = consumed events = [] for event_id, row in enumerate(event_rows, 1): frame_index = int(row["frame"]) require(int(row["id"]) == event_id and 0 <= frame_index < total_frames, f"{tags['run_key']} event {event_id}: invalid identifiers") frame = frames[frame_index] before = frame["events_consumed_total"] - frame["events_consumed_this_frame"] require(before < event_id <= frame["events_consumed_total"], f"{tags['run_key']} event {event_id}: conflicting consumption history") created = int(row["t0_us"]) present = int(row["t1_us"]) require(0 < created <= present == frame["present_return_us"], f"{tags['run_key']} event {event_id}: clock or frame join mismatch") require(int(row["application_return_us"]) == 0, f"{tags['run_key']} event {event_id}: expected event-only sentinel") events.append({ **tags, "event_id": event_id, "frame_index": frame_index, "scored": frame["scored"], "event_created_us": created, "present_return_us": present, "latency_us": present - created, }) require(prev_consumed == total_events, f"{tags['run_key']}: final counter mismatch") scored_frames = [row for row in frames if row["scored"]] scored_events = [row for row in events if row["scored"]] intervals = [row["present_return_interval_us"] / 1000 for row in scored_frames] post = [row["post_present_return_us"] / 1000 for row in scored_frames] latencies = [row["latency_us"] / 1000 for row in scored_events] measure = { "events": len(scored_events), "frames": len(scored_frames), "mean_ms": statistics.mean(latencies), "p50_ms": nearest_rank(latencies, 0.50), "p95_ms": nearest_rank(latencies, 0.95), "p99_ms": nearest_rank(latencies, 0.99), "mean_cadence_ms": statistics.mean(intervals), "post_delay_over_500us": sum(value > 0.5 for value in post), "median_post_delay_ms": nearest_rank(post, 0.50), } matches(measure, info, tags["run_key"]) run = { **tags, "matched_pair": info["run"] // 2 + 1, "seed": info["seed"], "base_work_us": info["work_us"], "video_driver": details["driver"], "warmup_frames": warmup, "total_frames": total_frames, "events_consumed_total": total_events, "events_trailing_unconsumed": int(details["trailing"]), "scored_frames": measure["frames"], "scored_events": measure["events"], "mean_event_to_present_return_ms": measure["mean_ms"], "p50_event_to_present_return_ms": measure["p50_ms"], "p95_event_to_present_return_ms": measure["p95_ms"], "p99_event_to_present_return_ms": measure["p99_ms"], "mean_present_return_interval_ms": measure["mean_cadence_ms"], "scored_frames_post_present_over_500us": measure["post_delay_over_500us"], "p50_post_present_return_ms": measure["median_post_delay_ms"], } return run, frames, events, measure def paced_groups(details, source, sweep): groups = {} for code, condition in CONDITION.items(): rows = [metrics for run, metrics in details if run["condition"] == condition and run["paced"]] require(len(rows) == 4, f"{sweep} {condition}: expected four scored paced runs") values = { k: statistics.mean(row[k] for row in rows) for k in ("mean_ms", "mean_cadence_ms", "median_post_delay_ms") } values.update( events=sum(row["events"] for row in rows), frames=sum(row["frames"] for row in rows), delayed_frames=sum(row["post_delay_over_500us"] for row in rows), ) matches(values, source[code], f"{sweep} {condition}") groups[condition] = values gain = groups["baseline"]["mean_ms"] - groups["hook"]["mean_ms"] return {"conditions": groups, "equal_run_mean_difference_ms": gain} def as_jsonl(rows): return "".join(json.dumps(row, separators=(",", ":")) + "\n" for row in rows).encode() def checksum(blob): return hashlib.sha256(blob).hexdigest() def generate(results): tables = {path: [] for splits in CONFIGS.values() for path in splits.values()} manifest = { "version": 1, "primary_endpoint": "synthetic SDL event timestamp immediately before SDL_PushEvent to underlying SDL_RenderPresent return", "scope": "Linux SDL2 software renderer, dummy video driver, no physical click or photon measurement", "configurations": CONFIGS, "sweeps": {}, "sources": {}, "tables": {}, } for sweep, subdirectory in SWEEPS: raw_path = results / subdirectory / "sdl_raw.csv.gz" summary_path = results / subdirectory / "sdl_summary.json" for source in (raw_path, summary_path): manifest["sources"][source.relative_to(results).as_posix()] = checksum(source.read_bytes()) summary = json.loads(summary_path.read_text(encoding="utf-8")) with gzip.open(raw_path, "rt", encoding="utf-8", newline="") as handle: reader = csv.DictReader(handle) require(reader.fieldnames == RAW_FIELDS, f"{sweep}: raw CSV header mismatch") by_run = defaultdict(list) for row in reader: by_run[int(row["run"])].append(row) ordered_runs = summary["runs"] require([row["run"] for row in ordered_runs] == sorted(by_run) == list(range(10)), f"{sweep}: missing or unordered runs") combination = "".join(row["mode"] for row in ordered_runs if row["paced"]) require(combination == summary["order"] == "BAABABBA", f"{sweep}: paced order mismatch") require([(row["mode"], row["paced"]) for row in ordered_runs[8:]] == [("B", False), ("A", False)], f"{sweep}: unpaced controls mismatch") details = [] for run_info in ordered_runs: split = SPLITS[run_info["paced"]] run, frames, events, metrics = parse_run(sweep, run_info, by_run[run_info["run"]], summary["warmup_frames"]) tables[CONFIGS["runs"]["observed"]].append(run) tables[CONFIGS["frame_timings"][split]].extend(frames) tables[CONFIGS["input_events"][split]].extend(events) details.append((run, metrics)) manifest["sweeps"][sweep] = { "paced_order": combination, **paced_groups(details, summary["groups"], sweep), } payloads = {} for path, rows in tables.items(): payload = as_jsonl(rows) payloads[path] = payload tally = Counter(row.get("scored") for row in rows) record = {"rows": len(rows), "sha256": checksum(payload)} if True in tally or False in tally: record.update(scored_rows=tally[True], warmup_rows=tally[False]) manifest["tables"][path] = record require(manifest["tables"][CONFIGS["input_events"]["paced"]]["scored_rows"] == 7781, "total scored paced events must match the published manuscript") payloads["DATA_MANIFEST.json"] = (json.dumps(manifest, indent=2) + "\n").encode() return payloads, manifest def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--results", type=Path, required=True, help="directory containing archived SDL2 results") parser.add_argument("--output", type=Path, default=Path("."), help="destination dataset repository root") parser.add_argument("--verify", action="store_true", help="require expected bytes without writing") args = parser.parse_args() payloads, manifest = generate(args.results) for name, content in payloads.items(): target = args.output / name if args.verify: require(target.is_file() and target.read_bytes() == content, f"missing or changed output: {target}") else: target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(content) print("Viewer tables verified." if args.verify else "Viewer tables generated and archive metrics checked.") for name, table in manifest["tables"].items(): suffix = f", {table['scored_rows']:,} scored" if "scored_rows" in table else "" print(f"{name}: {table['rows']:,} rows{suffix}") for name, value in manifest["sweeps"].items(): print(f"{name} paced equal-run mean difference: {value['equal_run_mean_difference_ms']:.5f} ms") if __name__ == "__main__": main()