#!/usr/bin/env python3 """Stage 5 of swarma_rules.txt: date every sample of SwarmA-MagSet. How the date range was found (swarma_kp_search.py): the run of Kp values in the training set matches GFZ's 3-hourly Kp series at exactly one place, from 31 July 2023, 21 UT. Forty runs of Kp values in a row match there and nowhere else in 2013-2026. That left a search range. This script then dates each sample independently of Kp and Dst, from the satellite's position: 1. For each sample, find the times in NASA SSCWeb's Swarm A ephemeris (1-minute GEO positions, 31 Jul - 1 Sep 2023) when the satellite is within 1 degree of the sample's first row, moving the same way, and refine each to 1 s. Four or five such passes lie within a month, so the closest is kept and the count recorded. The rules asked for exactly one; that test could not be met, so swarma_date_proof.py settles the date row by row against ESA's Swarm A product (rule A11). 2. Check: positions at the middle and last rows, taking rows as 1 s apart. 3. The same search on Swarm B and Swarm C, to see whether they fit better or worse. 4. Check, independent of position: GFZ Kp and OMNI2 Dst at those times, against the sample's columns. The file's Dst runs between hourly values placed at mid-hour, and its Kp steps at the middle of each 3-hour block; swarma_date_proof.py found both. Run: python3 -I swarma_dating.py Writes out/swarma_samples_dated.csv and out/swarma_dating.json. """ import csv import io import json import math import re 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 UTC = timezone.utc RE = 6371.0 def read_columns(zf, name, want): with zf.open(name) as raw: r = csv.reader(io.TextIOWrapper(raw, encoding="utf-8", newline="")) header = next(r) idx = [header.index(w) for w in want] cols = [[] for _ in want] for row in r: for c, i in zip(cols, idx): c.append(float(row[i])) return dict(zip(want, cols)) def gfz_kp(path): out = {} for line in open(path, encoding="utf-8", errors="replace"): if line.startswith("#"): continue p = line.split() if len(p) < 10 or int(p[0]) != 2023: continue t = datetime(int(p[0]), int(p[1]), int(p[2]), int(float(p[3])), tzinfo=UTC) out[t] = float(p[7]) return out def omni_dst(path): out = {} for line in open(path, encoding="ascii", errors="replace"): p = line.split() t = datetime(int(p[0]), 1, 1, int(p[2]), tzinfo=UTC) + timedelta(days=int(p[1]) - 1) out[t] = float(p[40]) return out def parse_ssc(path): t = open(path, encoding="utf-8", errors="replace").read() times = re.findall(r"", t) xs = [float(x) for x in re.findall(r"([^<]+)", t)] ys = [float(x) for x in re.findall(r"([^<]+)", t)] zs = [float(x) for x in re.findall(r"([^<]+)", t)] t0 = datetime.fromisoformat(times[0].replace("Z", "+00:00")) step = (datetime.fromisoformat(times[1].replace("Z", "+00:00")) - t0).total_seconds() return {"t0": t0, "step": step, "x": xs, "y": ys, "z": zs} def pos_at(eph, sec): """GEO position by Hermite-free linear interpolation of a near-circular orbit at 60 s, renormalised for radius by neighbours.""" x = sec / eph["step"] i = int(math.floor(x)) if i < 0 or i + 1 >= len(eph["x"]): return None f = x - i # Interpolate on the unit sphere: chord interpolation shrinks radius slightly, so restore it from the end points. X = eph["x"][i] + f * (eph["x"][i + 1] - eph["x"][i]) Y = eph["y"][i] + f * (eph["y"][i + 1] - eph["y"][i]) Z = eph["z"][i] + f * (eph["z"][i + 1] - eph["z"][i]) r = math.sqrt(X * X + Y * Y + Z * Z) r0 = math.sqrt(eph["x"][i] ** 2 + eph["y"][i] ** 2 + eph["z"][i] ** 2) r1 = math.sqrt(eph["x"][i + 1] ** 2 + eph["y"][i + 1] ** 2 + eph["z"][i + 1] ** 2) R = r0 + f * (r1 - r0) return (X / r, Y / r, Z / r, R) 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 angle_deg(u, v): c = u[0] * v[0] + u[1] * v[1] + u[2] * v[2] return math.degrees(math.acos(max(-1.0, min(1.0, c)))) def find_passes(eph, lat0, lon0, north, thresh_deg=1.0): """All passes within thresh of (lat0, lon0) moving in the given direction. Returns seconds since eph t0.""" u = unit(lat0, lon0) n = len(eph["x"]) ux, uy, uz = u xs, ys, zs = eph["x"], eph["y"], eph["z"] # Fast scan at 60 s: within 3 degrees (the satellite moves 3.8 degrees a minute). cand = [] cos6 = math.cos(math.radians(4.0)) for i in range(n): r = math.sqrt(xs[i] * xs[i] + ys[i] * ys[i] + zs[i] * zs[i]) if (xs[i] * ux + ys[i] * uy + zs[i] * uz) / r >= cos6: cand.append(i) # Group and refine. out = [] used = set() for i in cand: if i in used: continue grp = [j for j in cand if abs(j - i) <= 3] used.update(grp) a = (min(grp) - 1) * eph["step"] b = (max(grp) + 1) * eph["step"] best = (999.0, None) s = a while s <= b: p = pos_at(eph, s) if p is not None: d = angle_deg(p[:3], u) if d < best[0]: best = (d, s) s += 1.0 if best[1] is None or best[0] > thresh_deg: continue p1 = pos_at(eph, best[1]) p2 = pos_at(eph, best[1] + 5) if p1 is None or p2 is None: continue going_north = p2[2] > p1[2] if going_north == north: out.append(best) return out def main(): zpath, idx, outdir = sys.argv[1], Path(sys.argv[2]), Path(sys.argv[3]) want = ["Latitude", "Longitude", "Radius", "Dst", "Kp"] with zipfile.ZipFile(zpath) as zf: tr = read_columns(zf, "SwarmA-MagSet/train.csv", want) te = read_columns(zf, "SwarmA-MagSet/test.csv", want) data = {k: tr[k] + te[k] for k in want} ntr, nte = len(tr["Kp"]) // LEN, len(te["Kp"]) // LEN n = ntr + nte kp_gfz = gfz_kp(str(idx / "Kp_ap_since_1932.txt")) dst_omni = omni_dst(str(idx / "omni2_2023.dat")) lat, lon, rad = data["Latitude"], data["Longitude"], data["Radius"] summary = {"sats": {}} rows = {} for sat in ("a", "c", "b"): eph = parse_ssc(str(idx / f"ssc-swarm{sat}.xml")) res = [] for s in range(n): a = s * LEN north = lat[a + LEN - 1] > lat[a] ps = find_passes(eph, lat[a], lon[a], north) res.append(ps) n_one = sum(1 for r in res if len(r) == 1) n_none = sum(1 for r in res if len(r) == 0) n_many = sum(1 for r in res if len(r) > 1) dist = [min(p[0] for p in r) for r in res if r] summary["sats"][sat] = { "samples_with_one_pass_within_1deg": n_one, "with_none": n_none, "with_several": n_many, "median_first_row_distance_deg": statistics.median(dist) if dist else None, "max_first_row_distance_deg": max(dist) if dist else None, } print("Swarm", sat.upper(), summary["sats"][sat], flush=True) if sat == "a": rows = {"res": res, "eph": eph} # Dates from Swarm A. eph = rows["eph"] res = rows["res"] t0_eph = eph["t0"] info = [] chk_mid, chk_last, chk_r = [], [], [] for s in range(n): a = s * LEN ps = res[s] if not ps: info.append(None) continue # Several passes within a degree in a month are possible: keep the closest, and record the count. d, sec = min(ps, key=lambda x: x[0]) for row, store in ((LEN // 2, chk_mid), (LEN - 1, chk_last)): p = pos_at(eph, sec + row) if p is not None: store.append(angle_deg(p[:3], unit(lat[a + row], lon[a + row]))) p = pos_at(eph, sec) if p is not None: chk_r.append(p[3] - rad[a] / 1000) t0 = t0_eph + timedelta(seconds=sec) info.append({"s": s, "sec": sec, "t0": t0, "dist": d, "n_passes": len(ps)}) summary["position_check"] = { "middle_row_median_deg": statistics.median(chk_mid), "middle_row_max_deg": max(chk_mid), "last_row_median_deg": statistics.median(chk_last), "last_row_max_deg": max(chk_last), "radius_ssc_minus_file_km_median": statistics.median(chk_r), "radius_ssc_minus_file_km_max_abs": max(abs(x) for x in chk_r), } print(json.dumps(summary["position_check"], indent=1), flush=True) # Kp and Dst at those times. def dst_at(t): # OMNI's hourly value stands at mid-hour in the file. t = t - timedelta(hours=0.5) h0 = t.replace(minute=0, second=0, microsecond=0) f = (t - h0).total_seconds() / 3600 x, y = dst_omni.get(h0), dst_omni.get(h0 + timedelta(hours=1)) return None if x is None or y is None else x + f * (y - x) def kp_at(t): # GFZ's 3-hour block steps at its middle in the file. t = t - timedelta(hours=1.5) return kp_gfz.get(t.replace(hour=t.hour - t.hour % 3, minute=0, second=0, microsecond=0)) out_rows = [] derr, kbad = [], 0 for s, d in enumerate(info): if d is None: continue a = s * LEN tm = d["t0"] + timedelta(seconds=LEN // 2) k_file = data["Kp"][a + LEN // 2] k_pub = kp_at(tm) if k_pub is None or abs(k_file - k_pub) > 0.01: kbad += 1 dpub = dst_at(tm) derr.append(dpub - data["Dst"][a + LEN // 2]) # Equator crossing, from the sample. la = lat[a : a + LEN] lo = lon[a : a + LEN] eq_row, eq_lon = None, None for i in range(1, LEN): if (la[i - 1] <= 0 < la[i]) or (la[i - 1] >= 0 > la[i]): f = la[i - 1] / (la[i - 1] - la[i]) eq_row = i - 1 + f eq_lon = lo[i - 1] + f * (((lo[i] - lo[i - 1] + 180) % 360) - 180) break tq = d["t0"] + timedelta(seconds=eq_row) ut = tq.hour + tq.minute / 60 + tq.second / 3600 lt = (ut + eq_lon / 15) % 24 out_rows.append( [ "train" if s < ntr else "test", s if s < ntr else s - ntr, s, "asc" if la[-1] > la[0] else "desc", d["t0"].strftime("%Y-%m-%dT%H:%M:%S"), tq.strftime("%Y-%m-%dT%H:%M:%S"), round(eq_lon, 3), round(lt, 3), round(d["dist"], 4), d["n_passes"], k_file, k_pub, round(data["Dst"][a + LEN // 2], 3), None if dpub is None else round(dpub, 3), ] ) summary["kp_mid_pass_disagreements_with_gfz"] = kbad summary["dst_mid_pass_file_vs_omni"] = { "median_abs_nT": statistics.median(abs(x) for x in derr), "max_abs_nT": max(abs(x) for x in derr), "within_1_nT": sum(abs(x) <= 1 for x in derr), "n": len(derr), } good = [d for d in info if d] summary["n_dated"] = len(good) summary["first_train"] = info[0]["t0"].isoformat() summary["last_train"] = info[ntr - 1]["t0"].isoformat() summary["first_test"] = info[ntr]["t0"].isoformat() summary["last_test"] = info[n - 1]["t0"].isoformat() print(json.dumps({k: summary[k] for k in summary if k != "sats"}, indent=1, default=str), flush=True) with open(outdir / "swarma_samples_dated.csv", "w", encoding="utf-8", newline="\n") as f: w = csv.writer(f, lineterminator="\n") w.writerow(["set", "sample", "file_index", "direction", "t_first_row_utc", "t_equator_utc", "equator_lon", "lt_equator_h", "first_row_dist_to_swarm_a_deg", "passes_within_1deg_in_month", "kp_file_mid", "kp_gfz_mid", "dst_file_mid", "dst_omni_mid"]) w.writerows(out_rows) with open(outdir / "swarma_dating.json", "w", encoding="utf-8", newline="\n") as f: json.dump(summary, f, ensure_ascii=False, indent=1, default=str) if __name__ == "__main__": main()