#!/usr/bin/env python3 """Summarize matched pretrained-versus-scratch deltas without pseudo-replication.""" from __future__ import annotations import argparse import csv import itertools import json import random import statistics from collections import defaultdict from pathlib import Path def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--results-dir", type=Path, required=True) parser.add_argument("--out-dir", type=Path, required=True) parser.add_argument("--name", required=True) parser.add_argument( "--methods", nargs="+", default=["timae", "lobgrid_timae", "simlob2026"], ) parser.add_argument("--targets", nargs="+") parser.add_argument("--exclude-targets", nargs="+", default=[]) parser.add_argument("--seeds", nargs="+", type=int) parser.add_argument("--label-budget", type=float, default=0.5) parser.add_argument("--allow-incomplete", action="store_true") return parser.parse_args() def percentile(values: list[float], probability: float) -> float: if not values: return float("nan") ordered = sorted(values) position = probability * (len(ordered) - 1) lower = int(position) upper = min(lower + 1, len(ordered) - 1) weight = position - lower return ordered[lower] * (1.0 - weight) + ordered[upper] * weight def bootstrap_mean_ci( values: list[float], *, seed: int, repetitions: int = 20_000, ) -> tuple[float, float]: rng = random.Random(seed) n = len(values) boot = sorted( statistics.fmean(values[rng.randrange(n)] for _ in range(n)) for _ in range(repetitions) ) return percentile(boot, 0.025), percentile(boot, 0.975) def sign_flip_p(values: list[float], *, seed: int) -> tuple[float, str]: observed = abs(statistics.fmean(values)) tolerance = 1e-15 if len(values) <= 20: null = ( abs(statistics.fmean(sign * value for sign, value in zip(signs, values))) for signs in itertools.product((-1.0, 1.0), repeat=len(values)) ) denominator = 2 ** len(values) extreme = sum(value >= observed - tolerance for value in null) return extreme / denominator, "exact" rng = random.Random(seed) repetitions = 100_000 extreme = 0 for _ in range(repetitions): candidate = abs( statistics.fmean( value if rng.random() < 0.5 else -value for value in values ) ) extreme += candidate >= observed - tolerance return (extreme + 1) / (repetitions + 1), "monte_carlo_100000" def write_csv(path: Path, rows: list[dict]) -> None: if not rows: return with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) def read_cases(args: argparse.Namespace) -> list[dict]: cases = [] for path in sorted(args.results_dir.glob("*.json")): if path.name.endswith(".pretrain.json"): continue data = json.loads(path.read_text(encoding="utf-8")) if "test" not in data or data.get("setting") not in { "from_scratch", "fine_tune", }: continue target = data["stock"] seed = int(data["seed"]) if data["method"] not in args.methods: continue if args.targets and target not in args.targets: continue if target in args.exclude_targets: continue if args.seeds and seed not in args.seeds: continue if abs(float(data["label_budget"]) - args.label_budget) > 1e-9: continue cases.append( { "target": target, "method": data["method"], "seed": seed, "setting": data["setting"], "macro_f1": float(data["test"]["macro_f1"]), "balanced_accuracy": float(data["test"]["balanced_accuracy"]), "accuracy": float(data["test"]["accuracy"]), "source_file": path.name, } ) return cases def main() -> None: args = parse_args() cases = read_cases(args) lookup = { (row["target"], row["method"], row["seed"], row["setting"]): row for row in cases } target_values = ( sorted(set(args.targets) - set(args.exclude_targets)) if args.targets else sorted({row["target"] for row in cases}) ) seed_values = ( sorted(set(args.seeds)) if args.seeds else sorted({row["seed"] for row in cases}) ) expected = { (target, method, seed, setting) for target in target_values for method in args.methods for seed in seed_values for setting in ("from_scratch", "fine_tune") } missing = sorted(expected - set(lookup)) if missing and not args.allow_incomplete: raise ValueError(f"Missing {len(missing)} matched cases; first: {missing[:5]}") paired_rows = [] for target in target_values: for method in args.methods: for seed in seed_values: scratch = lookup.get((target, method, seed, "from_scratch")) pretrained = lookup.get((target, method, seed, "fine_tune")) if not scratch or not pretrained: continue paired_rows.append( { "target": target, "method": method, "seed": seed, "scratch_macro_f1": scratch["macro_f1"], "pretrained_macro_f1": pretrained["macro_f1"], "paired_delta_macro_f1": pretrained["macro_f1"] - scratch["macro_f1"], "scratch_balanced_accuracy": scratch["balanced_accuracy"], "pretrained_balanced_accuracy": pretrained[ "balanced_accuracy" ], "paired_delta_balanced_accuracy": pretrained[ "balanced_accuracy" ] - scratch["balanced_accuracy"], } ) grouped: dict[tuple[str, str], list[dict]] = defaultdict(list) for row in paired_rows: grouped[(row["method"], row["target"])].append(row) target_rows = [] for (method, target), rows in sorted(grouped.items()): target_rows.append( { "method": method, "target": target, "n_seeds": len(rows), "scratch_macro_f1_mean": statistics.fmean( row["scratch_macro_f1"] for row in rows ), "pretrained_macro_f1_mean": statistics.fmean( row["pretrained_macro_f1"] for row in rows ), "paired_delta_macro_f1_mean": statistics.fmean( row["paired_delta_macro_f1"] for row in rows ), "paired_delta_macro_f1_seed_sd": statistics.stdev( row["paired_delta_macro_f1"] for row in rows ) if len(rows) > 1 else 0.0, } ) summary_rows = [] for method_index, method in enumerate(args.methods): per_target = [row for row in target_rows if row["method"] == method] if not per_target: continue if len(per_target) == 1 and per_target[0]["n_seeds"] > 1: uncertainty_unit = "seed" inferential_values = [ row["paired_delta_macro_f1"] for row in paired_rows if row["method"] == method ] else: uncertainty_unit = "target" inferential_values = [ row["paired_delta_macro_f1_mean"] for row in per_target ] ci_low, ci_high = bootstrap_mean_ci( inferential_values, seed=20260731 + method_index, ) randomization_p, p_kind = sign_flip_p( inferential_values, seed=20260831 + method_index, ) summary_rows.append( { "name": args.name, "method": method, "n_targets": len(per_target), "seeds_per_target_min": min(row["n_seeds"] for row in per_target), "seeds_per_target_max": max(row["n_seeds"] for row in per_target), "uncertainty_unit": uncertainty_unit, "mean_paired_delta_macro_f1": statistics.fmean(inferential_values), "median_paired_delta_macro_f1": statistics.median( inferential_values ), "q1_paired_delta_macro_f1": percentile(inferential_values, 0.25), "q3_paired_delta_macro_f1": percentile(inferential_values, 0.75), "bootstrap_ci95_low": ci_low, "bootstrap_ci95_high": ci_high, "wins": sum(value > 0 for value in inferential_values), "ties": sum(value == 0 for value in inferential_values), "losses": sum(value < 0 for value in inferential_values), "sign_flip_p": randomization_p, "sign_flip_kind": p_kind, } ) args.out_dir.mkdir(parents=True, exist_ok=True) write_csv(args.out_dir / "paired_seed_cases.csv", paired_rows) write_csv(args.out_dir / "paired_target_summary.csv", target_rows) write_csv(args.out_dir / "paired_aggregate_summary.csv", summary_rows) lines = [ f"# {args.name}", "", f"Completeness: {len(set(lookup))}/{len(expected)} expected arm files.", "", "Seeds are paired within target. When multiple targets are available, seeds " "are averaged inside target before cross-target summaries; therefore target–seed " "runs are not treated as independent markets.", "", "| method | targets | uncertainty unit | mean delta (95% bootstrap CI) | median | IQR | wins | sign-flip p |", "|---|---:|---|---:|---:|---:|---:|---:|", ] for row in summary_rows: denominator = ( row["n_targets"] if row["uncertainty_unit"] == "target" else row["seeds_per_target_max"] ) lines.append( f"| {row['method']} | {row['n_targets']} | {row['uncertainty_unit']} | " f"{row['mean_paired_delta_macro_f1']:+.4f} " f"[{row['bootstrap_ci95_low']:+.4f}, {row['bootstrap_ci95_high']:+.4f}] | " f"{row['median_paired_delta_macro_f1']:+.4f} | " f"[{row['q1_paired_delta_macro_f1']:+.4f}, " f"{row['q3_paired_delta_macro_f1']:+.4f}] | " f"{row['wins']}/{denominator} | {row['sign_flip_p']:.4f} " f"({row['sign_flip_kind']}) |" ) if missing: lines.extend(["", "## Missing cases", "", *[f"- `{row}`" for row in missing]]) (args.out_dir / "summary.md").write_text("\n".join(lines) + "\n", encoding="utf-8") print( f"wrote {args.name} to {args.out_dir}; " f"completeness {len(set(lookup))}/{len(expected)}" ) if __name__ == "__main__": main()