#!/usr/bin/env python3 """Rule A10 of swarma_rules.txt: the exact best point-adjusted F1, every threshold, and a wider range for random numbers. swarma_baselines.py gives 0.9485 for |diff_res_BY| and swarma_pa_recipe.py, on a coarser grid of thresholds, 0.9476. An independent check got 94.9%. So this script sweeps every threshold exactly and tries both ways of drawing a labelled run: split at the join between samples (the 500 runs we report) and merged across that join (what TimesNet's adjustment does when it walks the concatenated series). For a fixed set of detected runs, F1 is highest at the highest threshold that keeps them, so the maxima of the runs are the only thresholds that need testing. Random numbers: 5 seeds were the rule; here 200, each a fresh uniform number per point, scored at its own best threshold. Run: python3 -I swarma_pa_check.py Writes swarma_pa_check.json in the out folder. No network, no other inputs. """ import bisect import csv import io import json import random import statistics import sys import zipfile from pathlib import Path sys.stdout.reconfigure(encoding="utf-8", errors="replace") LEN = 1573 SEED = 20261102 RAND_SEEDS = 200 def read_csv(zf, name, cols=None): with zf.open(name) as raw: r = csv.reader(io.TextIOWrapper(raw, encoding="utf-8", newline="")) header = next(r) idx = [(header.index(c), c) for c in (cols or header)] out = {c: [] for _, c in idx} for row in r: for i, c in idx: out[c].append(float(row[i])) return out def runs(y, split_at_samples): segs = [] i = 0 n = len(y) while i < n: if y[i]: j = i + 1 while j < n and y[j] and not (split_at_samples and j % LEN == 0): j += 1 segs.append((i, j)) i = j else: i += 1 return segs def sweep(score, y, segs): """Exact best point-adjusted F1 over every threshold, flagging score >= threshold.""" neg = sorted(s for s, l in zip(score, y) if not l) nn = len(neg) P = sum(y) seg = sorted(((max(score[a:b]), b - a) for a, b in segs), reverse=True) best = (0.0, None, 0, 0) tp = 0 k = 0 while k < len(seg): thr = seg[k][0] while k < len(seg) and seg[k][0] == thr: tp += seg[k][1] k += 1 fp = nn - bisect.bisect_left(neg, thr) f1 = 2 * tp / (tp + fp + P) if f1 > best[0]: best = (f1, thr, tp, fp) f1, thr, tp, fp = best return {"f1": f1, "threshold": thr, "tp": tp, "fp": fp, "fn": P - tp, "precision": tp / (tp + fp), "recall": tp / P, "flagged_share": (sum(1 for s in score if s >= thr)) / len(score)} def main(): zpath, outdir = sys.argv[1], Path(sys.argv[2]) with zipfile.ZipFile(zpath) as zf: te = read_csv(zf, "SwarmA-MagSet/test.csv", ("diff_res_BX", "diff_res_BY", "diff_res_BZ")) y = [int(v) for v in read_csv(zf, "SwarmA-MagSet/label.csv")["Label"]] split = runs(y, True) merged = runs(y, False) out = {"points": len(y), "labelled": sum(y), "runs_split_at_sample_joins": len(split), "runs_merged_across_joins": len(merged)} scores = { "|diff_res_BY|": [abs(v) for v in te["diff_res_BY"]], "sum |diff_res| X, Y, Z": [abs(a) + abs(b) + abs(c) for a, b, c in zip(te["diff_res_BX"], te["diff_res_BY"], te["diff_res_BZ"])], } out["best_pa"] = {} for name, sc in scores.items(): out["best_pa"][name] = {"runs_split": sweep(sc, y, split), "runs_merged": sweep(sc, y, merged)} print(name, json.dumps(out["best_pa"][name]), flush=True) ties = len(sc) - len(set(sc)) print(" tied values:", ties, flush=True) rng = random.Random(SEED) vals_split, vals_merged = [], [] n = len(y) for s in range(RAND_SEEDS): sc = [rng.random() for _ in range(n)] vals_split.append(sweep(sc, y, split)["f1"]) vals_merged.append(sweep(sc, y, merged)["f1"]) out["random_best_threshold_pa"] = { "seeds": RAND_SEEDS, "runs_split": {"min": min(vals_split), "max": max(vals_split), "mean": statistics.fmean(vals_split), "sd": statistics.pstdev(vals_split)}, "runs_merged": {"min": min(vals_merged), "max": max(vals_merged), "mean": statistics.fmean(vals_merged), "sd": statistics.pstdev(vals_merged)}, } print(json.dumps(out["random_best_threshold_pa"], indent=1), flush=True) with open(outdir / "swarma_pa_check.json", "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, ensure_ascii=False, indent=1) f.write("\n") if __name__ == "__main__": main()