"""Summarise check_against_saved_results.py outputs (all paper cells).
python benchmarks/summarize_saved_check.py --runs
--out benchmarks/results/saved_results_check.csv \
--markdown benchmarks/results/saved_results_check.md
Exact rows: count of cells whose four metrics equal the saved row (|difference| <= 1e-15, the
decimal text of the CSV). Fast rows: macro-F1 change against the saved paper result, per data
stream (mean over the 15 fold x seed cells) and as the paper's nine-view average.
"""
from __future__ import annotations
import argparse
import glob
import json
from pathlib import Path
import pandas as pd
METRICS = ("macro_f1", "accuracy", "balanced_accuracy", "worst_class_f1")
NINE_CHANNEL = ("mhealth_right_lower_arm_v1", "pamap2_hand_imu_v1")
HARMES = {"harmes_left_wrist_accel_v1": "harmes", "harmes_right_wrist_accel_v1": "harmes"}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--runs", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--markdown")
a = ap.parse_args()
rows, errors = [], []
for f in sorted(glob.glob(str(Path(a.runs) / "*.json"))):
r = json.load(open(f))
if "error" in r:
errors.append(r)
continue
row = {k: r[k] for k in ("dataset", "fold", "seed", "recipe", "decoder", "speed", "paper_id", "seconds",
"fit_seconds", "has_paper_results")}
for m in METRICS:
row[f"observed_{m}"] = r["observed"][m]
row[f"expected_{m}"] = None if r["expected"] is None else r["expected"][m]
row[f"diff_{m}"] = None if r["diff"] is None else r["diff"][m]
row["max_abs_diff"] = None if r["diff"] is None else max(abs(v) for v in r["diff"].values())
rows.append(row)
d = pd.DataFrame(rows)
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
d.to_csv(a.out, index=False)
ex = d[d.speed == "exact"]
summary = ex.groupby(["recipe", "decoder"]).agg(cells=("dataset", "size"),
identical=("max_abs_diff", lambda s: int((s <= 1e-15).sum())),
max_abs_diff=("max_abs_diff", "max")).reset_index()
print(summary.to_string())
print("exact cells:", len(ex), "identical:", int((ex.max_abs_diff <= 1e-15).sum()), "errors:", len(errors))
if not a.markdown:
return
lines = ["| Recipe | Decoder | Cells | Metrics identical to the saved row | Max abs metric difference |",
"|---|---|---:|---:|---:|"]
for _, r in summary.iterrows():
lines.append(f"| `{r.recipe}` | {r.decoder} | {r.cells} | {r.identical} | {r.max_abs_diff:.3g} |")
if errors:
lines += ["", "Cells that could not be fitted:", ""]
for e in errors:
lines.append(f"* {e['dataset']}, fold {e['fold']}, seed {e['seed']}, `{e['recipe']}` ({e['decoder']}, "
f"speed={e['speed']}): `{e['error']}`")
fast = d[(d.speed == "fast")].copy()
if not fast.empty:
fast["view"] = fast.dataset.replace(HARMES)
per = fast.groupby(["recipe", "decoder", "dataset"]).agg(cells=("fold", "size"),
delta=("diff_macro_f1", "mean"),
worst=("diff_macro_f1", "min"),
best=("diff_macro_f1", "max")).reset_index()
lines += ["", "| Recipe | Decoder | Data stream | Cells | Mean macro-F1 change (points) | Range over cells |",
"|---|---|---|---:|---:|---|"]
for _, r in per.iterrows():
lines.append(f"| `{r.recipe}` | {r.decoder} | {r.dataset} | {r.cells} | {100 * r.delta:+.2f} | "
f"{100 * r.worst:+.2f} to {100 * r.best:+.2f} |")
prim = fast[~fast.dataset.isin(NINE_CHANNEL)]
view = prim.groupby(["recipe", "decoder", "view"])[["observed_macro_f1", "expected_macro_f1"]].mean() \
.groupby(["recipe", "decoder"]).mean() * 100
lines += ["", "| Recipe | Decoder | Paper average macro-F1, exact | Same, fast | Change |", "|---|---|---:|---:|---:|"]
for (rec, dec), r in view.iterrows():
lines.append(f"| `{rec}` | {dec} | {r.expected_macro_f1:.2f} | {r.observed_macro_f1:.2f} | "
f"{r.observed_macro_f1 - r.expected_macro_f1:+.2f} |")
Path(a.markdown).write_text("\n".join(lines) + "\n")
if __name__ == "__main__":
main()