#!/usr/bin/env python3 """Stages 3 and 4 of swarma_rules.txt, with additions A1-A7: do the labels of SwarmA-MagSet track simple things? Describes a public dataset. It does not reproduce or rate the authors' network. The rules were written before this ran. Run: python3 -I swarma_baselines.py It reads out/swarma_samples_dated.csv from the out folder and writes out/swarma_baselines.json. """ import bisect import csv import glob import io import json import math import os import random import statistics import sys import zipfile from datetime import datetime, timedelta, timezone from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import cdf3_min # noqa: E402 sys.stdout.reconfigure(encoding="utf-8", errors="replace") LEN = 1573 UTC = timezone.utc POLE = (80.37, -72.62) CH = ("BX", "BY", "BZ", "F") SEED = 20261102 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 per_sample(v, fn): out = [] for s in range(len(v) // LEN): out.extend(fn(v[s * LEN : (s + 1) * LEN])) return out def rolling_median_resid(x, w): half = w // 2 res = [] win = [] lo = 0 hi = -1 n = len(x) for i in range(n): new_hi = min(n - 1, i + half) new_lo = max(0, i - half) while hi < new_hi: hi += 1 bisect.insort(win, x[hi]) while lo < new_lo: del win[bisect.bisect_left(win, x[lo])] lo += 1 m = len(win) med = win[m // 2] if m % 2 else 0.5 * (win[m // 2 - 1] + win[m // 2]) res.append(abs(x[i] - med)) return res def rolling_mean(x, w): half = w // 2 n = len(x) cum = [0.0] for v in x: cum.append(cum[-1] + v) return [(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 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 amplitude_features(d, scales=None): f = {} for ch in CH: res, dif = d["res_" + ch], d["diff_res_" + ch] f["|res_%s|" % ch] = [abs(x) for x in res] f["|diff_res_%s|" % ch] = [abs(x) for x in dif] for w in (31, 111): f["rollrms%d(diff_res_%s)" % (w, ch)] = per_sample(dif, lambda s: rolling_rms(s, w)) for w in (31, 61, 121): f["|res_%s-med%d|" % (ch, w)] = per_sample(res, lambda s: rolling_median_resid(s, w)) f["|res_%s-mean61|" % ch] = per_sample(res, lambda s: [abs(a - b) for a, b in zip(s, rolling_mean(s, 61))]) n = len(d["res_BX"]) f["sum|diff_res_XYZ|"] = [abs(d["diff_res_BX"][i]) + abs(d["diff_res_BY"][i]) + abs(d["diff_res_BZ"][i]) for i in range(n)] if scales is None: scales = {} for ch in CH: scales["diff_" + ch] = statistics.median(f["|diff_res_%s|" % ch]) # The median is zero here: on a locally monotonic stretch a rolling median equals the value itself. So use the mean. scales["med61_" + ch] = statistics.fmean(f["|res_%s-med61|" % ch]) sdiff = [sum(f["|diff_res_%s|" % ch][i] / scales["diff_" + ch] for ch in CH) for i in range(n)] smed = [sum(f["|res_%s-med61|" % ch][i] / scales["med61_" + ch] for ch in CH) for i in range(n)] f["S_diff"] = sdiff f["S_med61"] = smed for w in (5, 15, 31, 61): f["mean%d(S_diff)" % w] = per_sample(sdiff, lambda s: rolling_mean(s, w)) f["mean%d(S_med61)" % w] = per_sample(smed, lambda s: rolling_mean(s, w)) return f, scales def auc_ap_f1(score, y): """AUC with midranks; AP; best F1 with its threshold, precision and recall (high score = flagged).""" n = len(y) order = sorted(range(n), key=score.__getitem__, reverse=True) P = sum(y) N = n - P tp = fp = 0 best = (0.0, None, 0.0, 0.0) ap = 0.0 prev_recall = 0.0 auc = 0.0 i = 0 while i < n: j = i s = score[order[i]] tp0, fp0 = tp, fp while j < n and score[order[j]] == s: if y[order[j]]: tp += 1 else: fp += 1 j += 1 # AUC by trapezoid in (fp, tp). auc += (fp - fp0) * (tp + tp0) / 2.0 prec = tp / (tp + fp) rec = tp / P if P else 0.0 ap += (rec - prev_recall) * prec prev_recall = rec f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0 if f1 > best[0]: best = (f1, s, prec, rec) i = j return auc / (P * N), ap, best def f1_at(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 p = tp / (tp + fp) if tp + fp else 0.0 r = tp / (tp + fn) if tp + fn else 0.0 return (2 * p * r / (p + r) if p + r else 0.0), p, r, (tp + fp) / len(y) def quantile_threshold(sorted_vals, q): i = min(len(sorted_vals) - 1, max(0, int(q * len(sorted_vals)))) return sorted_vals[i] def segments(y): segs = [] i = 0 n = len(y) while i < n: if y[i]: j = i while j < n and y[j] and j % LEN != 0 or j == i: j += 1 segs.append((i, j)) i = j else: i += 1 return segs def pa_best(score, y, segs): """Best F1 after point adjustment (Kim et al. 2022).""" neg = sorted(s for s, l in zip(score, y) if not l) P = sum(y) seg = sorted(((max(score[a:b]), b - a) for a, b in segs), reverse=True) best = (0.0, None, 0.0, 0.0) tp = 0 k = 0 # Candidate thresholds: every segment maximum, plus 200 quantiles of the negatives. cands = sorted({m for m, _ in seg} | {neg[int(len(neg) * q / 200)] for q in range(200)}, reverse=True) for thr in cands: while k < len(seg) and seg[k][0] >= thr: tp += seg[k][1] k += 1 fp = len(neg) - bisect.bisect_left(neg, thr) if tp + fp == 0: continue p = tp / (tp + fp) r = tp / P f1 = 2 * p * r / (p + r) if p + r else 0.0 if f1 > best[0]: best = (f1, thr, p, r) return best def binned(score, nbins=200): s = sorted(score) edges = [s[int(len(s) * k / nbins)] for k in range(1, nbins)] return [bisect.bisect_right(edges, v) for v in score], nbins def sample_hist(bins, nb, y, ns): hp = [[0] * nb for _ in range(ns)] hn = [[0] * nb for _ in range(ns)] for i, b in enumerate(bins): (hp if y[i] else hn)[i // LEN][b] += 1 return hp, hn def auc_from_hist(hp, hn): tp = fp = 0 area = 0.0 P, N = sum(hp), sum(hn) for b in range(len(hp) - 1, -1, -1): area += hn[b] * (tp + tp + hp[b]) / 2.0 tp += hp[b] fp += hn[b] return area / (P * N) if P and N else float("nan") def boot_auc(score, y, ns, rng, reps=300): bins, nb = binned(score) hp, hn = sample_hist(bins, nb, y, ns) vals = [] for _ in range(reps): cp = [0] * nb cn = [0] * nb for _ in range(ns): s = rng.randrange(ns) a, b = hp[s], hn[s] for k in range(nb): cp[k] += a[k] cn[k] += b[k] vals.append(auc_from_hist(cp, cn)) vals.sort() return vals[int(0.025 * reps)], vals[int(0.975 * reps)] def cv_f1(score, y, ns, rng, splits=100): """Threshold chosen on half of the samples, F1 scored on the other half.""" bins, nb = binned(score, 100) hp, hn = sample_hist(bins, nb, y, ns) out = [] ids = list(range(ns)) def add(group): cp = [0] * nb cn = [0] * nb for s in group: a, b = hp[s], hn[s] for k in range(nb): cp[k] += a[k] cn[k] += b[k] return cp, cn def f1_curve(cp, cn): P = sum(cp) tp = fp = 0 res = [0.0] * nb for b in range(nb - 1, -1, -1): tp += cp[b] fp += cn[b] res[b] = 2 * tp / (tp + fp + P) if tp + fp + P else 0.0 return res for _ in range(splits): rng.shuffle(ids) a, b = ids[: ns // 2], ids[ns // 2 :] curve = f1_curve(*add(a)) k = max(range(nb), key=curve.__getitem__) out.append(f1_curve(*add(b))[k]) return statistics.fmean(out), statistics.pstdev(out) def main(): zpath, ibidir, outdir = sys.argv[1], sys.argv[2], Path(sys.argv[3]) with zipfile.ZipFile(zpath) as zf: tr = read_csv(zf, "SwarmA-MagSet/train.csv") te = read_csv(zf, "SwarmA-MagSet/test.csv") la = read_csv(zf, "SwarmA-MagSet/label.csv")["Label"] y = [int(x) for x in la] N = len(y) ns = N // LEN p = sum(y) / N out = {"prevalence": p, "flag_everything_f1": 2 * p / (1 + p), "points": N, "labelled": sum(y)} print("prevalence", round(p, 5), "flag-everything F1", round(out["flag_everything_f1"], 4), flush=True) dated = list(csv.DictReader(open(outdir / "swarma_samples_dated.csv", encoding="utf-8", newline=""))) dtr = [r for r in dated if r["set"] == "train"] dte = [r for r in dated if r["set"] == "test"] t0te = [datetime.strptime(r["t_first_row_utc"], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=UTC) for r in dte] t0tr = [datetime.strptime(r["t_first_row_utc"], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=UTC) for r in dtr] # Per-point time, local time, geomagnetic latitude. lat, lon = te["Latitude"], te["Longitude"] ut = [] secs = [] for s, t0 in enumerate(t0te): base = t0.hour * 3600 + t0.minute * 60 + t0.second for r in range(LEN): ut.append(((base + r) % 86400) / 3600) secs.append((t0 + timedelta(seconds=r))) lt = [(u + lo / 15) % 24 for u, lo in zip(ut, lon)] ml = [mlat(a, b) for a, b in zip(lat, lon)] desc = [1 if lat[s * LEN + LEN - 1] < lat[s * LEN] else 0 for s in range(ns) for _ in range(LEN)] # ESA bubble index. ibi = {} for f in sorted(glob.glob(os.path.join(ibidir, "SW_OPER_IBIATMS_2F_*.ZIP"))): z = zipfile.ZipFile(f) name = [i.filename for i in z.infolist() if i.filename.lower().endswith(".cdf")][0] c = cdf3_min.CDF(z.read(name)) ts = c.read("Timestamp") bi = c.read("Bubble_Index") bp = c.read("Bubble_Probability") fb = c.read("Flags_Bubble") la_ = c.read("Latitude") lo_ = c.read("Longitude") for k in range(len(ts)): ibi[int(round(ts[k] / 1000))] = (bi[k], bp[k], fb[k], la_[k], lo_[k]) # CDF_EPOCH: milliseconds since 0000-01-01. Build the offset from a known time. epoch0 = 62167219200 # seconds from year 0 to 1970, CDF convention match = bad = 0 bub = [None] * N prob = [None] * N fbub = [None] * N dl = [] for i, t in enumerate(secs): key = int(t.timestamp()) + epoch0 v = ibi.get(key) if v is None: continue bub[i], prob[i], fbub[i] = v[0], v[1], v[2] dl.append(abs(v[3] - lat[i]) + abs(((v[4] - lon[i] + 180) % 360) - 180)) match += 1 print("IBI rows matched by time:", match, "of", N, "| median |dlat|+|dlon| at those times:", statistics.median(dl), "max", max(dl), flush=True) out["ibi_time_match"] = {"matched": match, "of": N, "median_abs_lat_plus_lon_deg": statistics.median(dl), "max_abs_lat_plus_lon_deg": max(dl)} # Labels against local time and bubbles. out["by_direction_lt"] = {} for name, cond in (("descending (evening side)", lambda i: desc[i] == 1), ("ascending (morning side)", lambda i: desc[i] == 0)): idx = [i for i in range(N) if cond(i)] lts = [lt[i] for i in idx] lab = sum(y[i] for i in idx) out["by_direction_lt"][name] = {"points": len(idx), "labelled": lab, "share": lab / len(idx), "lt_min": min(lts), "lt_max": max(lts), "lt_median": statistics.median(lts)} # By date. bydate = {} for s, t0 in enumerate(t0te): k = t0.strftime("%Y-%m-%d") b = bydate.setdefault(k, {"samples": 0, "labelled": 0, "desc": 0}) b["samples"] += 1 b["labelled"] += sum(y[s * LEN : (s + 1) * LEN]) b["desc"] += desc[s * LEN] out["by_date"] = bydate # By geomagnetic latitude and day-night. edges = list(range(-60, 61, 5)) tab = [] for a, b in zip(edges[:-1], edges[1:]): idx = [i for i in range(N) if a <= ml[i] < b and desc[i] == 1] if idx: tab.append({"mlat": "%d to %d" % (a, b), "points": len(idx), "labelled": sum(y[i] for i in idx), "share": round(sum(y[i] for i in idx) / len(idx), 4)}) out["by_mlat_5deg_evening_passes"] = tab # By longitude of the magnetic-latitude band. lonedges = list(range(-180, 181, 30)) lt_tab = [] for a, b in zip(lonedges[:-1], lonedges[1:]): idx = [i for i in range(N) if a <= lon[i] < b and desc[i] == 1] lt_tab.append({"lon": "%d to %d" % (a, b), "points": len(idx), "labelled": sum(y[i] for i in idx), "share": round(sum(y[i] for i in idx) / len(idx), 4) if idx else None}) out["by_longitude_evening_passes"] = lt_tab # Bubble flag. an = [i for i in range(N) if bub[i] is not None] known = [i for i in an if bub[i] >= 0] bubble = [1 if bub[i] == 1 else 0 for i in an] out["ibi"] = { "index_counts_at_test_points": {str(k): sum(1 for i in an if bub[i] == k) for k in (-1, 0, 1)}, "labelled_points_by_index": {str(k): sum(y[i] for i in an if bub[i] == k) for k in (-1, 0, 1)}, } b1 = [i for i in an if bub[i] == 1] b0 = [i for i in an if bub[i] == 0] bm = [i for i in an if bub[i] == -1] out["ibi"]["label_share_where_bubble_1"] = sum(y[i] for i in b1) / max(len(b1), 1) out["ibi"]["label_share_where_bubble_0"] = sum(y[i] for i in b0) / max(len(b0), 1) out["ibi"]["label_share_where_not_analysed"] = sum(y[i] for i in bm) / max(len(bm), 1) tp = sum(y[i] for i in b1) fp = len(b1) - tp fn = sum(y[i] for i in an) - tp prec = tp / max(tp + fp, 1) rec = tp / max(tp + fn, 1) out["ibi"]["bubble_flag_as_detector"] = {"precision": prec, "recall": rec, "f1": 2 * prec * rec / (prec + rec) if prec + rec else 0} # Samples: labelled counts against bubble counts. out["ibi"]["samples_with_any_bubble_flag"] = sum(1 for s in range(ns) if any(bub[i] == 1 for i in range(s * LEN, (s + 1) * LEN))) print(json.dumps(out["ibi"], indent=1), flush=True) print(json.dumps(out["by_direction_lt"], indent=1), flush=True) print(json.dumps(out["by_date"]), flush=True) print(json.dumps(out["by_mlat_5deg_evening_passes"]), flush=True) print(json.dumps(out["by_longitude_evening_passes"]), flush=True) # Features. feats_tr, scales = amplitude_features(tr) feats_te, _ = amplitude_features(te, scales) print("features built", len(feats_te), flush=True) out["scales_from_train"] = scales env = { "Kp": te["Kp"], "Dst": te["Dst"], "|Dst|": [abs(x) for x in te["Dst"]], "|latitude|": [abs(x) for x in lat], "|geomagnetic latitude|": [abs(x) for x in ml], "radius": te["Radius"], "Flags_B": te["Flags_B"], "Flags_F": te["Flags_F"], "hours from local midnight": [min(x, 24 - x) for x in lt], "descending pass (0/1)": [float(x) for x in desc], "evening, |mlat| 10-25 (0/1)": [1.0 if desc[i] and 10 <= abs(ml[i]) <= 25 else 0.0 for i in range(N)], "ESA Bubble_Index = 1 (0/1)": [1.0 if bub[i] == 1 else 0.0 for i in range(N)], "ESA Bubble_Probability": [prob[i] if prob[i] is not None and prob[i] > 0 else 0.0 for i in range(N)], } rng = random.Random(SEED) for k in range(5): env["random %d" % k] = [rng.random() for _ in range(N)] segs = segments(y) out["n_segments"] = len(segs) print("segments", len(segs), "labelled in segments", sum(b - a for a, b in segs), flush=True) table = [] allf = dict(env) allf.update(feats_te) for name, score in allf.items(): a, ap, best = auc_ap_f1(score, y) flip = a < 0.5 s2 = [-v for v in score] if flip else score if flip: a, ap, best = auc_ap_f1(s2, y) ss = sorted(s2) thr_q = quantile_threshold(ss, 1 - p) fq = f1_at(s2, y, thr_q) pa = pa_best(s2, y, segs) row = { "feature": name, "direction": "low = flagged" if flip else "high = flagged", "auc": round(a, 4), "ap": round(ap, 4), "best_f1": round(best[0], 4), "best_f1_precision": round(best[2], 4), "best_f1_recall": round(best[3], 4), "top_q_f1": round(fq[0], 4), "pa_best_f1": round(pa[0], 4), "pa_precision": round(pa[2], 4), "pa_recall": round(pa[3], 4), } if name in feats_tr: trs = sorted(feats_tr[name]) for q in (0.99, 0.995, 0.999): thr = quantile_threshold(trs, q) f = f1_at(score, y, thr) row["f1_train_q%s" % q] = round(f[0], 4) row["flagged_share_train_q%s" % q] = round(f[3], 4) table.append(row) table.sort(key=lambda r: -r["best_f1"]) out["table"] = table print("\nfeature | AUC | AP | best F1 (P,R) | top-q F1 | PA best F1 (P,R)", flush=True) for r in table: print(r["feature"].ljust(32), r["auc"], r["ap"], r["best_f1"], (r["best_f1_precision"], r["best_f1_recall"]), r["top_q_f1"], r["pa_best_f1"], (r["pa_precision"], r["pa_recall"]), r.get("f1_train_q0.99", ""), r.get("f1_train_q0.995", ""), r.get("f1_train_q0.999", ""), r["direction"][:4], flush=True) # Cross-validated F1 and bootstrap on the shortlist. amp_names = [r["feature"] for r in table if r["feature"] in feats_te] top_amp = amp_names[:8] best_auc_amp = max((r for r in table if r["feature"] in feats_te), key=lambda r: r["auc"])["feature"] short = ["Kp", "Dst", "|Dst|", "|latitude|", "|geomagnetic latitude|", "hours from local midnight", "Flags_B", "Flags_F", "descending pass (0/1)", "ESA Bubble_Probability", best_auc_amp] rngb = random.Random(SEED + 1) out["bootstrap_auc_95"] = {} for name in short: score = allf[name] a, _, _ = auc_ap_f1(score, y) s2 = [-v for v in score] if a < 0.5 else score out["bootstrap_auc_95"][name] = boot_auc(s2, y, ns, rngb) print("bootstrap", json.dumps(out["bootstrap_auc_95"]), flush=True) rngc = random.Random(SEED + 2) out["cv_f1_by_sample"] = {} for name in sorted(set(top_amp + short)): score = allf[name] a, _, _ = auc_ap_f1(score, y) s2 = [-v for v in score] if a < 0.5 else score m, sd = cv_f1(s2, y, ns, rngc) out["cv_f1_by_sample"][name] = {"mean": round(m, 4), "sd": round(sd, 4)} print("cv", json.dumps(out["cv_f1_by_sample"]), flush=True) # Stage 4: rule families. rules = [] def score_flags(flag, label): tp = sum(1 for a, b in zip(flag, y) if a and b) fp = sum(1 for a, b in zip(flag, y) if a and not b) fn = sum(1 for a, b in zip(flag, y) if not a and b) pr = tp / (tp + fp) if tp + fp else 0.0 re = tp / (tp + fn) if tp + fn else 0.0 rules.append({"rule": label, "f1": round(2 * pr * re / (pr + re), 4) if pr + re else 0.0, "precision": round(pr, 4), "recall": round(re, 4), "iou": round(tp / (tp + fp + fn), 4) if tp + fp + fn else 0.0, "flagged_share": round((tp + fp) / N, 4)}) # (a) De Santis-style windows. for ch in CH: dif = te["diff_res_" + ch] win_rms = [] for s in range(ns): seg = dif[s * LEN : (s + 1) * LEN] tot = math.sqrt(sum(v * v for v in seg) / LEN) ws = [] for st in range(0, LEN - 110 + 1, 22): w = seg[st : st + 110] ws.append((st, math.sqrt(sum(v * v for v in w) / 110) / tot)) win_rms.append(ws) for kt in (1.5, 2, 2.5, 3, 3.5, 4, 5): fl = [0] * N for s, ws in enumerate(win_rms): for st, r in ws: if r > kt: for i in range(s * LEN + st, s * LEN + st + 110): fl[i] = 1 score_flags(fl, "windows 110/22 on diff_res_%s, rms > %s x sample rms" % (ch, kt)) # (b) point thresholds; (c) any-of-channels. per_flags = {} for prefix in ("res_", "diff_res_"): for ch in CH: v = te[prefix + ch] # For res_, use deviation from the sample's mean. stats = [] for s in range(ns): seg = v[s * LEN : (s + 1) * LEN] if prefix == "res_": md = statistics.median(seg) seg2 = [x - md for x in seg] else: seg2 = seg rm = math.sqrt(sum(x * x for x in seg2) / LEN) mad = 1.4826 * statistics.median(abs(x) for x in seg2) stats.append((seg2, rm, mad)) for k in (2, 3, 4, 5, 6, 8): for kind in ("rms", "MAD"): fl = [] for seg2, rm, mad in stats: lim = k * (rm if kind == "rms" else mad) fl.extend(1 if abs(x) > lim else 0 for x in seg2) per_flags[(prefix, ch, k, kind)] = fl score_flags(fl, "|%s%s| > %d x sample %s" % (prefix, ch, k, kind)) for prefix in ("res_", "diff_res_"): for k in (2, 3, 4, 5, 6, 8): for kind in ("rms", "MAD"): for group, chs in (("BX,BY,BZ", ("BX", "BY", "BZ")), ("BX,BY,BZ,F", CH)): fl = [1 if any(per_flags[(prefix, ch, k, kind)][i] for ch in chs) else 0 for i in range(N)] score_flags(fl, "any of %s%s > %d x sample %s" % (prefix, group, k, kind)) rules.sort(key=lambda r: -r["f1"]) out["rule_families_top"] = rules[:25] print("\nStage 4, top rules:", flush=True) for r in rules[:15]: print(r, flush=True) # Inside versus outside labelled runs. desc_runs = [] for a, b in segs: s = a // LEN desc_runs.append( { "sample": s, "start_row": a - s * LEN, "length": b - a, "mlat_mid": round(ml[(a + b) // 2], 1), "lat_mid": round(lat[(a + b) // 2], 1), "lon_mid": round(lon[(a + b) // 2], 1), "lt_mid": round(lt[(a + b) // 2], 2), "t_mid": secs[(a + b) // 2].strftime("%Y-%m-%dT%H:%M:%S"), "max_abs_diff_BY": round(max(abs(x) for x in te["diff_res_BY"][a:b]), 3), "max_abs_diff_BX": round(max(abs(x) for x in te["diff_res_BX"][a:b]), 3), "bubble_points": sum(1 for i in range(a, b) if bub[i] == 1), } ) with open(outdir / "swarma_label_runs.csv", "w", encoding="utf-8", newline="\n") as f: w = csv.DictWriter(f, fieldnames=list(desc_runs[0].keys()), lineterminator="\n") w.writeheader() w.writerows(desc_runs) out["runs_with_any_bubble_point"] = sum(1 for r in desc_runs if r["bubble_points"] > 0) out["runs_total"] = len(desc_runs) for ch in CH: inside = [abs(te["diff_res_" + ch][i]) for i in range(N) if y[i]] outside = [abs(te["diff_res_" + ch][i]) for i in range(N) if not y[i]] out["median_abs_diff_%s_inside_outside" % ch] = [statistics.median(inside), statistics.median(outside)] print({k: v for k, v in out.items() if k.startswith("median_abs") or k.startswith("runs_")}, flush=True) with open(outdir / "swarma_baselines.json", "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, ensure_ascii=False, indent=1, default=str) if __name__ == "__main__": main()