#!/usr/bin/env python3 """Rules A9 and A12 of swarma_rules.txt: how much does the scoring recipe matter on these labels? Baselines with no learning, scored plainly and with point adjustment (Kim et al. 2022), under three threshold recipes: (i) best threshold, which uses the labels (upper bound); (ii) threshold chosen on half the test samples, scored on the other half, 100 splits; (iii) the recipe in the public Time-Series-Library code of TimesNet (exp_anomaly_detection.py): threshold at the (100 - r) percentile of the score over train and test together, r in 0.5, 1, 2, 5, 9, no labels used. Whether Wen et al. use this recipe is unknown. Rule A12 adds a finer grid of r, the band of r that reaches the authors' figure, and random numbers over 40 seeds. Also: which flag values carry labels; simple burst rates by set and by side of the orbit; labelled share against geomagnetic latitude with a bootstrap over samples; and which half-orbits each set holds. Run: python3 -I swarma_pa_recipe.py """ import bisect import csv import io import json import math import random import statistics import sys import zipfile from datetime import datetime from pathlib import Path sys.stdout.reconfigure(encoding="utf-8", errors="replace") LEN = 1573 SEED = 20261102 POLE = (80.37, -72.62) def unit(lat, lon): a, b = math.radians(lat), math.radians(lon) return (math.cos(a) * math.cos(b), math.cos(a) * math.sin(b), math.sin(a)) PU = unit(*POLE) def mlat(lat, lon): u = unit(lat, lon) return math.degrees(math.asin(max(-1.0, min(1.0, PU[0] * u[0] + PU[1] * u[1] + PU[2] * u[2])))) def read_csv(zf, name): with zf.open(name) as raw: r = csv.reader(io.TextIOWrapper(raw, encoding="utf-8", newline="")) header = next(r) cols = [[] for _ in header] for row in r: for c, v in zip(cols, row): c.append(float(v)) return dict(zip(header, cols)) def segments(y): segs = [] i = 0 n = len(y) while i < n: if y[i]: j = i + 1 while j < n and y[j] and j % LEN != 0: j += 1 segs.append((i, j)) i = j else: i += 1 return segs def f1(tp, fp, fn): return 2 * tp / (2 * tp + fp + fn) if tp + fp + fn else 0.0 def plain_counts(score, y, thr): tp = fp = fn = 0 for s, l in zip(score, y): if s >= thr: if l: tp += 1 else: fp += 1 elif l: fn += 1 return tp, fp, fn def pa_counts(score, y, thr, segs): tp = fp = fn = 0 for a, b in segs: if max(score[a:b]) >= thr: tp += b - a else: fn += b - a fp = sum(1 for s, l in zip(score, y) if s >= thr and not l) return tp, fp, fn def rolling_rms(x, w): half = w // 2 n = len(x) cum = [0.0] for v in x: cum.append(cum[-1] + v * v) return [math.sqrt((cum[min(n, i + half + 1)] - cum[max(0, i - half)]) / (min(n, i + half + 1) - max(0, i - half))) for i in range(n)] def per_sample(v, fn): out = [] for s in range(len(v) // LEN): out.extend(fn(v[s * LEN : (s + 1) * LEN])) return out class Curves: """Plain and point-adjusted counts per sample at a grid of thresholds, for fast split scoring.""" def __init__(self, score, y, ns, segs, nthr=120): s = sorted(score) self.thr = sorted({s[int(len(s) * (1 - 10 ** (-3.2 * k / nthr)))] for k in range(1, nthr)} | {s[int(len(s) * k / nthr)] for k in range(1, nthr)}) nt = len(self.thr) self.pl = [[(0, 0, 0)] * nt for _ in range(ns)] self.pa = [[(0, 0, 0)] * nt for _ in range(ns)] for sm in range(ns): a, b = sm * LEN, (sm + 1) * LEN seg = [(x, z) for x, z in segs if a <= x < b] pos = sorted(score[i] for i in range(a, b) if y[i]) neg = sorted(score[i] for i in range(a, b) if not y[i]) maxs = [(max(score[x:z]), z - x) for x, z in seg] P = len(pos) for k, t in enumerate(self.thr): tp = len(pos) - bisect.bisect_left(pos, t) fp = len(neg) - bisect.bisect_left(neg, t) self.pl[sm][k] = (tp, fp, P - tp) tpa = sum(L for m, L in maxs if m >= t) self.pa[sm][k] = (tpa, fp, P - tpa) def f1s(self, table, group): nt = len(self.thr) res = [] for k in range(nt): tp = fp = fn = 0 for s in group: a, b, c = table[s][k] tp += a fp += b fn += c res.append(f1(tp, fp, fn)) return res def main(): zpath, outdir = sys.argv[1], Path(sys.argv[2]) with zipfile.ZipFile(zpath) as zf: tr = read_csv(zf, "SwarmA-MagSet/train.csv") te = read_csv(zf, "SwarmA-MagSet/test.csv") y = [int(v) for v in read_csv(zf, "SwarmA-MagSet/label.csv")["Label"]] N = len(y) ns = N // LEN segs = segments(y) rng = random.Random(SEED) out = {} scale = {ch: statistics.median(abs(x) for x in tr["diff_res_" + ch]) for ch in ("BX", "BY", "BZ", "F")} def score_set(d): n = len(d["diff_res_BY"]) return { "|diff_res_BY|": [abs(x) for x in d["diff_res_BY"]], "|diff_res_BX|+|diff_res_BY|+|diff_res_BZ|": [abs(d["diff_res_BX"][i]) + abs(d["diff_res_BY"][i]) + abs(d["diff_res_BZ"][i]) for i in range(n)], "scaled sum of |diff_res| over 4 channels": [sum(abs(d["diff_res_" + ch][i]) / scale[ch] for ch in scale) for i in range(n)], "rolling rms of diff_res_BY over 31 rows": per_sample(d["diff_res_BY"], lambda s: rolling_rms(s, 31)), } st_te = score_set(te) st_tr = score_set(tr) rand_te = {"uniform random %d" % k: [rng.random() for _ in range(N)] for k in range(5)} rand_tr = {"uniform random %d" % k: [rng.random() for _ in range(len(tr["Kp"]))] for k in range(5)} all_te = dict(st_te) all_te.update(rand_te) all_tr = dict(st_tr) all_tr.update(rand_tr) res = {} for name, score in all_te.items(): c = Curves(score, y, ns, segs) ids = list(range(ns)) f_pl = c.f1s(c.pl, ids) f_pa = c.f1s(c.pa, ids) row = {"best_plain": round(max(f_pl), 4), "best_pa": round(max(f_pa), 4)} # Half and half. pls, pas = [], [] for _ in range(100): rng.shuffle(ids) a, b = ids[: ns // 2], ids[ns // 2 :] k = max(range(len(c.thr)), key=c.f1s(c.pl, a).__getitem__) pls.append(c.f1s(c.pl, b)[k]) k = max(range(len(c.thr)), key=c.f1s(c.pa, a).__getitem__) pas.append(c.f1s(c.pa, b)[k]) row["half_half_plain_mean_sd"] = [round(statistics.fmean(pls), 4), round(statistics.pstdev(pls), 4)] row["half_half_pa_mean_sd"] = [round(statistics.fmean(pas), 4), round(statistics.pstdev(pas), 4)] # The Time-Series-Library recipe. comb = sorted(all_tr[name] + score) row["library_recipe"] = {} for r in (0.5, 1, 2, 5, 9): thr = comb[int(len(comb) * (1 - r / 100))] pl = plain_counts(score, y, thr) pa = pa_counts(score, y, thr, segs) row["library_recipe"][str(r)] = {"flagged_share_test": round(sum(1 for s in score if s >= thr) / N, 4), "f1_plain": round(f1(*pl), 4), "f1_pa": round(f1(*pa), 4)} res[name] = row print(name, json.dumps(row), flush=True) out["scores"] = res # Rule A12: the same recipe on a finer grid of ratios. TimesNet's public scripts use 0.5 (SMD) and 1 (MSL, SMAP, SWaT, PSM) and run.py defaults to 0.25; 8.95 is this file's # labelled share. Random numbers come from their own generator, so nothing above changes. ratios = (0.25, 0.5, 1, 2, 3, 4, 5, 6, 7, 8, 8.95, 9, 10) P = sum(y) def recipe_f1(comb_sorted, seg_max, neg_sorted, pos_sorted, r): thr = comb_sorted[int(len(comb_sorted) * (1 - r / 100))] tp_pa = sum(L for m, L in seg_max if m >= thr) fp = len(neg_sorted) - bisect.bisect_left(neg_sorted, thr) tp = len(pos_sorted) - bisect.bisect_left(pos_sorted, thr) return f1(tp, fp, P - tp), f1(tp_pa, fp, P - tp_pa) def recipe_parts(score_te, score_tr): comb_sorted = sorted(score_tr + score_te) seg_max = [(max(score_te[a:b]), b - a) for a, b in segs] neg_sorted = sorted(s for s, l in zip(score_te, y) if not l) pos_sorted = sorted(s for s, l in zip(score_te, y) if l) return comb_sorted, seg_max, neg_sorted, pos_sorted parts = recipe_parts(st_te["|diff_res_BY|"], st_tr["|diff_res_BY|"]) sweep = {"ratios_pct": list(ratios), "diff_res_BY": {}} for r in ratios: pl, pa = recipe_f1(*parts, r) sweep["diff_res_BY"][str(r)] = {"f1_plain": round(pl, 6), "f1_pa": round(pa, 6)} scan = [(k * 0.05, recipe_f1(*parts, k * 0.05)[1]) for k in range(5, 241)] above = [round(r, 2) for r, v in scan if v >= 0.927] best = max(scan, key=lambda x: x[1]) sweep["diff_res_BY_scan"] = {"step_pct": 0.05, "ratios_from_pct": 0.25, "ratios_to_pct": 12.0, "ratio_band_reaching_92_70": [min(above), max(above)], "best_ratio_pct": round(best[0], 2), "best_f1_pa": round(best[1], 6)} rng2 = random.Random(SEED + 12) draws = {str(r): [] for r in ratios} for _ in range(40): s_te = [rng2.random() for _ in range(N)] s_tr = [rng2.random() for _ in range(len(tr["Kp"]))] parts_r = recipe_parts(s_te, s_tr) for r in ratios: draws[str(r)].append(recipe_f1(*parts_r, r)[1]) sweep["uniform_random_40_seeds_f1_pa"] = {k: {"mean": round(statistics.fmean(v), 4), "min": round(min(v), 4), "max": round(max(v), 4)} for k, v in draws.items()} out["recipe_sweep"] = sweep print(json.dumps(sweep), flush=True) # Flags and labels. flags = {} for name in ("Flags_B", "Flags_F"): vals = te[name] tab = {} for v, l in zip(vals, y): k = str(int(v)) a = tab.setdefault(k, [0, 0]) a[0] += 1 a[1] += l flags[name] = {k: {"points": a[0], "labelled": a[1], "share": round(a[1] / a[0], 4)} for k, a in sorted(tab.items(), key=lambda kv: int(kv[0]))} # Non-nominal rows: Flags_F not 0 or 1, or Flags_B not 0, and within 5 rows of them. bad = [i for i in range(N) if te["Flags_F"][i] not in (0.0, 1.0) or te["Flags_B"][i] != 0.0] nearbad = set() for i in bad: for j in range(max(0, i - 5), min(N, i + 6)): if j // LEN == i // LEN: nearbad.add(j) # Rule A12: the same count for the training set, whose scalar flags the first version didn't report. bad_tr = sum(1 for a, b in zip(tr["Flags_F"], tr["Flags_B"]) if a not in (0.0, 1.0) or b != 0.0) tab_tr = {} for v in tr["Flags_F"]: k = str(int(v)) tab_tr[k] = tab_tr.get(k, 0) + 1 flags["Flags_F_train_rows"] = dict(sorted(tab_tr.items(), key=lambda kv: int(kv[0]))) flags["rows_non_nominal_train"] = bad_tr flags["share_non_nominal_train"] = round(bad_tr / len(tr["Flags_F"]), 4) flags["share_non_nominal_test"] = round(len(bad) / N, 4) flags["rows_non_nominal"] = len(bad) flags["labelled_at_non_nominal_rows"] = sum(y[i] for i in bad) flags["rows_within_5_of_non_nominal"] = len(nearbad) flags["labelled_within_5_of_non_nominal"] = sum(y[i] for i in nearbad) flags["share_of_all_labels_within_5_of_non_nominal"] = round(sum(y[i] for i in nearbad) / sum(y), 4) flags["label_share_within_5_of_non_nominal"] = round(sum(y[i] for i in nearbad) / len(nearbad), 4) flags["label_share_elsewhere"] = round((sum(y) - sum(y[i] for i in nearbad)) / (N - len(nearbad)), 4) # Row gaps: every latitude step within a sample. gaps = {} for name, d in (("train", tr), ("test", te)): worst = max(abs(d["Latitude"][i + 1] - d["Latitude"][i]) for i in range(len(d["Latitude"]) - 1) if (i + 1) % LEN != 0) best = min(abs(d["Latitude"][i + 1] - d["Latitude"][i]) for i in range(len(d["Latitude"]) - 1) if (i + 1) % LEN != 0) gaps[name] = [best, worst] flags["abs_latitude_step_range_within_samples_deg"] = gaps out["flags"] = flags print(json.dumps(flags), flush=True) # Geomagnetic latitude, with bootstrap over samples of the contrast between the crest belts and the magnetic equator. ml = [mlat(a, b) for a, b in zip(te["Latitude"], te["Longitude"])] desc = [te["Latitude"][s * LEN + LEN - 1] < te["Latitude"][s * LEN] for s in range(ns)] per = [] for s in range(ns): if not desc[s]: continue a = b = c = d = 0 for i in range(s * LEN, (s + 1) * LEN): m = abs(ml[i]) if 10 <= m < 15: a += y[i] b += 1 elif m < 5: c += y[i] d += 1 per.append((a, b, c, d)) ratio = sum(p[0] for p in per) / sum(p[1] for p in per) / (sum(p[2] for p in per) / sum(p[3] for p in per)) boots = [] for _ in range(2000): a = b = c = d = 0 for _ in range(len(per)): p = per[rng.randrange(len(per))] a += p[0] b += p[1] c += p[2] d += p[3] if c: boots.append(a / b / (c / d)) boots.sort() out["mlat_contrast_evening"] = { "share_10_15": round(sum(p[0] for p in per) / sum(p[1] for p in per), 4), "share_0_5": round(sum(p[2] for p in per) / sum(p[3] for p in per), 4), "ratio": round(ratio, 2), "ci95": [round(boots[int(0.025 * len(boots))], 2), round(boots[int(0.975 * len(boots))], 2)], } print(out["mlat_contrast_evening"], flush=True) # How much would a burst rule flag in the "stable" training set? Threshold: best plain F1 of the rolling rms on the test labels. score = st_te["rolling rms of diff_res_BY over 31 rows"] c = Curves(score, y, ns, segs) fs = c.f1s(c.pl, list(range(ns))) k = max(range(len(c.thr)), key=fs.__getitem__) thr = c.thr[k] rtr = st_tr["rolling rms of diff_res_BY over 31 rows"] ntr = len(rtr) // LEN dtr = [tr["Latitude"][s * LEN + LEN - 1] < tr["Latitude"][s * LEN] for s in range(ntr)] def shares(sc, dirs, n): res = {} for lab, want in (("evening passes", True), ("morning passes", False)): ids = [s for s in range(n) if dirs[s] == want] if not ids: continue flagged = [sum(1 for i in range(s * LEN, (s + 1) * LEN) if sc[i] >= thr) for s in ids] res[lab] = {"samples": len(ids), "flagged_share": round(sum(flagged) / (len(ids) * LEN), 4), "median_flagged_points_per_pass": statistics.median(flagged), "passes_with_any": sum(1 for x in flagged if x > 0)} return res out["burst_rule"] = {"threshold_nT_per_s": round(thr, 4), "test": shares(score, desc, ns), "train": shares(rtr, dtr, ntr)} print(json.dumps(out["burst_rule"]), flush=True) # Which half-orbits does each set hold? dated = list(csv.DictReader(open(outdir / "swarma_samples_dated.csv", encoding="utf-8", newline=""))) t = [datetime.strptime(r["t_first_row_utc"], "%Y-%m-%dT%H:%M:%S") for r in dated] half = 5659.0 / 2 hold = {} for name in ("train", "test"): idx = [i for i, r in enumerate(dated) if r["set"] == name] tt = sorted(t[i] for i in idx) gaps_h = [round((b - a).total_seconds() / half) for a, b in zip(tt, tt[1:])] hist = {} for g in gaps_h: hist[g] = hist.get(g, 0) + 1 hold[name] = {"first": str(tt[0]), "last": str(tt[-1]), "span_days": round((tt[-1] - tt[0]).total_seconds() / 86400, 2), "half_orbits_in_span": round((tt[-1] - tt[0]).total_seconds() / half) + 1, "samples": len(idx), "gap_in_half_orbits_histogram": sorted(hist.items())} # Test without its last eight. idx = [i for i, r in enumerate(dated) if r["set"] == "test" and t[i] < datetime(2023, 8, 13)] tt = sorted(t[i] for i in idx) hold["test_6_to_12_aug"] = {"first": str(tt[0]), "last": str(tt[-1]), "span_days": round((tt[-1] - tt[0]).total_seconds() / 86400, 2), "samples": len(idx), "half_orbits_in_span": round((tt[-1] - tt[0]).total_seconds() / half) + 1} out["holdings"] = hold print(json.dumps(hold), flush=True) lts = {} for r in dated: k = (r["set"], r["direction"]) lts.setdefault(k, []).append(float(r["lt_equator_h"])) out["lt_at_equator"] = {"%s %s" % k: {"n": len(v), "min": min(v), "max": max(v), "median": statistics.median(v)} for k, v in lts.items()} print(out["lt_at_equator"], flush=True) with open(outdir / "swarma_pa_recipe.json", "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, ensure_ascii=False, indent=1, default=str) if __name__ == "__main__": main()