#!/usr/bin/env python3 """Stages 6 and 7 of swarma_rules.txt: SwarmA-MagSet against the USGS catalogue, and train against test. Describes a public dataset. Parameters are illustrative, from the open literature (Dobrovolsky radius, M >= 5.5, depth < 50 km). They are not the paper's: its sections on earthquakes could not be read. Run: python3 -I swarma_catalogue.py Reads out/swarma_samples_dated.csv. Writes out/swarma_catalogue.json. """ import csv import io import json import math import random import statistics import sys import zipfile from datetime import datetime, timedelta, timezone from pathlib import Path sys.stdout.reconfigure(encoding="utf-8", errors="replace") LEN = 1573 RE = 6371.0 SEED = 20261102 MAGS = (5.5, 6.0, 7.0) LEADS = (10, 30, 60, 90) REC0 = datetime(2014, 1, 1) REC1 = datetime(2026, 1, 1) 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)) def read_csv(zf, name, want): with zf.open(name) as raw: r = csv.reader(io.TextIOWrapper(raw, encoding="utf-8", newline="")) h = next(r) ii = [h.index(w) for w in want] cols = [[] for _ in want] for row in r: for c, i in zip(cols, ii): c.append(float(row[i])) return dict(zip(want, cols)) def load_events(folder): ev = [] seen = set() for p in sorted(Path(folder).glob("usgs-m5-*.csv")): for r in csv.DictReader(open(p, encoding="utf-8", newline="")): if r["type"] != "earthquake" or r["id"] in seen: continue seen.add(r["id"]) m, dep = float(r["mag"]), float(r["depth"] or 0) if m < 5.5 or dep >= 50: continue t = datetime.strptime(r["time"][:19], "%Y-%m-%dT%H:%M:%S") la, lo = float(r["latitude"]), float(r["longitude"]) ev.append({"t": t, "lat": la, "lon": lon_fix(lo), "m": m, "dep": dep, "place": r["place"], "id": r["id"], "u": unit(la, lo), "cr": math.cos(min(10 ** (0.43 * m) / RE, math.pi))}) ev.sort(key=lambda e: e["t"]) return ev def lon_fix(x): return ((x + 180) % 360) - 180 def main(): zpath, usgs, outdir = sys.argv[1], sys.argv[2], Path(sys.argv[3]) want = ["Latitude", "Longitude", "Radius", "Dst", "Kp", "diff_res_BX", "diff_res_BY", "diff_res_BZ", "diff_res_F", "res_BX", "res_BY", "res_BZ", "res_F", "Flags_B", "Flags_F"] with zipfile.ZipFile(zpath) as zf: tr = read_csv(zf, "SwarmA-MagSet/train.csv", want) te = read_csv(zf, "SwarmA-MagSet/test.csv", want) la = read_csv(zf, "SwarmA-MagSet/label.csv", ["Label"])["Label"] y = [int(v) for v in la] dated = list(csv.DictReader(open(outdir / "swarma_samples_dated.csv", encoding="utf-8", newline=""))) for r in dated: r["t0"] = datetime.strptime(r["t_first_row_utc"], "%Y-%m-%dT%H:%M:%S") dtr = [r for r in dated if r["set"] == "train"] dte = [r for r in dated if r["set"] == "test"] ntr, nte = len(dtr), len(dte) ev = load_events(usgs) print("events M5.5+ shallow 2014-2025:", len(ev), flush=True) span0 = min(r["t0"] for r in dated) span1 = max(r["t0"] for r in dated) + timedelta(days=91) near = [e for e in ev if span0 <= e["t"] <= span1] print("events in the window of the dataset + 90 days:", len(near), flush=True) out = {"n_events_window": len(near)} # Stage 6.1, per pass. def pass_hits(d, sets, step=10): res = [] for s, r in enumerate(sets): a = s * LEN pts = [unit(d["Latitude"][a + i], d["Longitude"][a + i]) for i in range(0, LEN, step)] t0 = r["t0"] hits = [] for e in near: dt = (e["t"] - t0).total_seconds() / 86400 if dt <= 0 or dt > 90: continue ex, ey, ez = e["u"] if any(p[0] * ex + p[1] * ey + p[2] * ez >= e["cr"] for p in pts): hits.append((dt, e)) res.append(hits) return res h_tr = pass_hits(tr, dtr) h_te = pass_hits(te, dte) tab = {} for name, hits in (("train", h_tr), ("test", h_te)): tab[name] = {} for m in MAGS: tab[name]["M%s" % m] = {str(T): round(100 * sum(1 for h in hits if any(dt <= T and e["m"] >= m for dt, e in h)) / len(hits), 1) for T in LEADS} out["share_of_passes_touching_a_zone_pct"] = tab print(json.dumps(tab, indent=1), flush=True) # Stage 6.3, which earthquakes. def tally(hits): cnt = {} for h in hits: big = [x for x in h if x[1]["m"] >= 6.0] if not big: continue dt, e = max(big, key=lambda x: x[1]["m"]) k = "%s M%.1f %s" % (e["t"].strftime("%Y-%m-%d"), e["m"], e["place"]) cnt[k] = cnt.get(k, 0) + 1 return sorted(cnt.items(), key=lambda kv: -kv[1]) out["largest_event_due_within_90d_train"] = tally(h_tr)[:15] out["largest_event_due_within_90d_test"] = tally(h_te)[:15] print("train:", out["largest_event_due_within_90d_train"][:10], flush=True) print("test:", out["largest_event_due_within_90d_test"][:10], flush=True) m7 = [e for e in near if e["m"] >= 6.5] out["events_M6.5_plus_shallow_in_window"] = ["%s M%.1f %s" % (e["t"].strftime("%Y-%m-%d"), e["m"], e["place"]) for e in m7] print("M6.5+:", out["events_M6.5_plus_shallow_in_window"], flush=True) # Stage 6.1 for points, and 6.2 against chance. N = len(y) lat, lon = te["Latitude"], te["Longitude"] pts_idx = list(range(0, N, 5)) # every 5th row is plenty for zones of hundreds of km t_of = lambda i: dte[i // LEN]["t0"] + timedelta(seconds=i % LEN) uv = {i: unit(lat[i], lon[i]) for i in pts_idx} in_zone = {} for i in pts_idx: t = t_of(i) ux, uy, uz = uv[i] best = {} for e in near: dt = (e["t"] - t).total_seconds() / 86400 if dt <= 0 or dt > 90: continue ex, ey, ez = e["u"] if ux * ex + uy * ey + uz * ez >= e["cr"]: for m in MAGS: if e["m"] >= m and dt < best.get(m, 1e9): best[m] = dt in_zone[i] = best res = {} for m in MAGS: res["M%s" % m] = {} for T in LEADS: lab = [1 if in_zone[i].get(m, 1e9) <= T else 0 for i in pts_idx if y[i]] unl = [1 if in_zone[i].get(m, 1e9) <= T else 0 for i in pts_idx if not y[i]] res["M%s" % m][str(T)] = {"labelled_pct": round(100 * sum(lab) / len(lab), 2), "unlabelled_pct": round(100 * sum(unl) / len(unl), 2)} out["share_of_points_in_a_zone_pct"] = res print(json.dumps(res), flush=True) # Bootstrap over test samples of labelled minus unlabelled, M >= 5.5. rng = random.Random(SEED) per_sample = {} for T in LEADS: rows = [] for s in range(nte): ids = [i for i in pts_idx if i // LEN == s] l = [1 if in_zone[i].get(5.5, 1e9) <= T else 0 for i in ids if y[i]] u = [1 if in_zone[i].get(5.5, 1e9) <= T else 0 for i in ids if not y[i]] rows.append((sum(l), len(l), sum(u), len(u))) diffs = [] for _ in range(2000): a = b = c = d = 0 for _ in range(nte): r = rows[rng.randrange(nte)] a += r[0] b += r[1] c += r[2] d += r[3] diffs.append(a / max(b, 1) - c / max(d, 1)) diffs.sort() per_sample[str(T)] = {"labelled_minus_unlabelled_pct": round(100 * (sum(r[0] for r in rows) / sum(r[1] for r in rows) - sum(r[2] for r in rows) / sum(r[3] for r in rows)), 2), "ci95_pct": [round(100 * diffs[50], 2), round(100 * diffs[1949], 2)]} out["labelled_minus_unlabelled_M5.5_bootstrap_by_sample"] = per_sample print(json.dumps(per_sample), flush=True) # 6.2: the same places at all other times. days_total = (REC1 - REC0).days ev_day = [((e["t"] - REC0).days, e) for e in ev] def base_rate(u, T, mmin): hit_days = [] for d, e in ev_day: if e["m"] < mmin: continue if u[0] * e["u"][0] + u[1] * e["u"][1] + u[2] * e["u"][2] >= e["cr"]: hit_days.append(d) last = days_total - T - 1 total = 0 end = -1 for d in sorted(hit_days): a, b = max(d - T, 0), min(d - 1, last) if b < a: continue if a <= end: a = end + 1 if b >= a: total += b - a + 1 end = b return total / (last + 1) # One point every 50 rows is enough for the place-based rate over the test set. sparse = list(range(0, N, 50)) uvs = {i: unit(lat[i], lon[i]) for i in sparse} chance = {} for T in LEADS: rl = [base_rate(uvs[i], T, 5.5) for i in sparse if y[i]] ru = [base_rate(uvs[i], T, 5.5) for i in sparse if not y[i]] chance[str(T)] = {"labelled_places_base_rate_pct": round(100 * statistics.fmean(rl), 2), "unlabelled_places_base_rate_pct": round(100 * statistics.fmean(ru), 2), "n_labelled_sample_points": len(rl), "n_unlabelled_sample_points": len(ru)} out["base_rate_same_places_all_days_M5.5_pct"] = chance print(json.dumps(chance), flush=True) # 6.4: days to the next qualifying event (M >= 5.5, within 90 days, else censored). lab_dt = [in_zone[i].get(5.5) for i in pts_idx if y[i]] unl_dt = [in_zone[i].get(5.5) for i in pts_idx if not y[i]] out["days_to_next_M5.5_labelled"] = {"share_with_event_within_90d": sum(1 for x in lab_dt if x is not None) / len(lab_dt), "median_days_if_any": statistics.median(x for x in lab_dt if x is not None) if any(x is not None for x in lab_dt) else None} out["days_to_next_M5.5_unlabelled"] = {"share_with_event_within_90d": sum(1 for x in unl_dt if x is not None) / len(unl_dt), "median_days_if_any": statistics.median(x for x in unl_dt if x is not None)} print(out["days_to_next_M5.5_labelled"], out["days_to_next_M5.5_unlabelled"], flush=True) # Stage 7, train against test. tt = [r["t0"] for r in dtr] te_t = [r["t0"] for r in dte] out["dates"] = {"train_first": str(min(tt)), "train_last": str(max(tt)), "test_first": str(min(te_t)), "test_last": str(max(te_t))} gap = min(abs((a - b).total_seconds()) for a in tt for b in te_t) out["smallest_gap_any_train_any_test_hours"] = gap / 3600 days_tr = sorted({t.date() for t in tt}) days_te = sorted({t.date() for t in te_t}) out["days_with_train"] = [str(d) for d in days_tr] out["days_with_test"] = [str(d) for d in days_te] out["days_shared"] = [str(d) for d in days_tr if d in days_te] # Exact duplicates between files: first-row positions. def key(d, s): a = s * LEN return (d["Latitude"][a], d["Longitude"][a], d["Radius"][a]) ktr = {key(tr, s) for s in range(ntr)} kte = {key(te, s) for s in range(nte)} out["duplicate_samples_between_files"] = len(ktr & kte) out["duplicate_samples_within_train"] = ntr - len(ktr) out["duplicate_samples_within_test"] = nte - len(kte) # Regions. def near_train(rte, days, dlon): c = 0 for r in dte: ok = False for q in dtr: if q["direction"] != r["direction"]: continue dd = abs((r["t0"] - q["t0"]).total_seconds()) / 86400 dl = abs(((float(r["equator_lon"]) - float(q["equator_lon"]) + 180) % 360) - 180) if dd <= days and dl <= dlon: ok = True break c += ok return c out["test_passes_with_train_pass_same_direction_within_5deg_lon"] = {str(d): near_train(None, d, 5.0) for d in (1, 7, 30)} print({k: out[k] for k in ("dates", "smallest_gap_any_train_any_test_hours", "days_shared", "duplicate_samples_between_files", "test_passes_with_train_pass_same_direction_within_5deg_lon")}, flush=True) # Shift between the sets. def rms(v): return math.sqrt(sum(x * x for x in v) / len(v)) def persample(d, n, fn): return [fn(s * LEN, (s + 1) * LEN, d) for s in range(n)] stats = { "Kp max in sample": lambda a, b, d: max(d["Kp"][a:b]), "|Dst| max in sample": lambda a, b, d: max(abs(x) for x in d["Dst"][a:b]), "Dst min in sample": lambda a, b, d: min(d["Dst"][a:b]), "rms diff_res_BX": lambda a, b, d: rms(d["diff_res_BX"][a:b]), "rms diff_res_BY": lambda a, b, d: rms(d["diff_res_BY"][a:b]), "rms diff_res_BZ": lambda a, b, d: rms(d["diff_res_BZ"][a:b]), "rms diff_res_F": lambda a, b, d: rms(d["diff_res_F"][a:b]), "max |diff_res_BY|": lambda a, b, d: max(abs(x) for x in d["diff_res_BY"][a:b]), "mean radius": lambda a, b, d: statistics.fmean(d["Radius"][a:b]), } def auc(a, b): all_ = sorted([(v, 1) for v in b] + [(v, 0) for v in a]) rank = 0 i = 0 tot = 0.0 n = len(all_) while i < n: j = i while j < n and all_[j][0] == all_[i][0]: j += 1 mid = (i + j + 1) / 2 tot += sum(mid for k in range(i, j) if all_[k][1]) i = j return (tot - len(b) * (len(b) + 1) / 2) / (len(a) * len(b)) shift = {} for name, fn in stats.items(): a = persample(tr, ntr, fn) b = persample(te, nte, fn) v = auc(a, b) shift[name] = {"train_median": round(statistics.median(a), 3), "test_median": round(statistics.median(b), 3), "train_max": round(max(a), 3), "test_max": round(max(b), 3), "auc_test_higher": round(v, 3)} # Train and test, evening passes only, where they can be compared. ev_tr = [s for s, r in enumerate(dtr) if r["direction"] == "desc"] mo_tr = [s for s, r in enumerate(dtr) if r["direction"] == "asc"] ev_te = [s for s, r in enumerate(dte) if r["direction"] == "desc"] mo_te = [s for s, r in enumerate(dte) if r["direction"] == "asc"] for name in ("rms diff_res_BX", "rms diff_res_BY", "rms diff_res_BZ", "rms diff_res_F", "max |diff_res_BY|"): fn = stats[name] a = [fn(s * LEN, (s + 1) * LEN, tr) for s in ev_tr] b = [fn(s * LEN, (s + 1) * LEN, te) for s in ev_te] shift[name + " (evening passes only)"] = {"train_median": round(statistics.median(a), 3), "test_median": round(statistics.median(b), 3), "train_max": round(max(a), 3), "test_max": round(max(b), 3), "auc_test_higher": round(auc(a, b), 3)} a = [fn(s * LEN, (s + 1) * LEN, tr) for s in mo_tr] b = [fn(s * LEN, (s + 1) * LEN, te) for s in mo_te] shift[name + " (morning passes only)"] = {"train_median": round(statistics.median(a), 3), "test_median": round(statistics.median(b), 3), "train_max": round(max(a), 3), "test_max": round(max(b), 3), "auc_test_higher": round(auc(a, b), 3)} out["shift"] = shift for k, v in shift.items(): print(k, v, flush=True) # Quiet-time shares, by the De Santis rule and a Kp rule. def quiet(d, n): kp3 = sum(1 for s in range(n) if max(d["Kp"][s * LEN : (s + 1) * LEN]) <= 3) dst20 = sum(1 for s in range(n) if max(abs(x) for x in d["Dst"][s * LEN : (s + 1) * LEN]) <= 20) both = sum(1 for s in range(n) if max(d["Kp"][s * LEN : (s + 1) * LEN]) <= 3 and max(abs(x) for x in d["Dst"][s * LEN : (s + 1) * LEN]) <= 20) return {"Kp<=3": kp3, "|Dst|<=20": dst20, "both": both, "of": n} out["quiet_counts"] = {"train": quiet(tr, ntr), "test": quiet(te, nte)} print(out["quiet_counts"], flush=True) # Passes skipped: how many half orbits does each set cover and hold? out["train_span_hours"] = (max(tt) - min(tt)).total_seconds() / 3600 with open(outdir / "swarma_catalogue.json", "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, ensure_ascii=False, indent=1, default=str) if __name__ == "__main__": main()