#!/usr/bin/env python3 """Stage 5, final check: are the dates exact? Compare every row of both sets with ESA's Swarm A product, and the Dst and Kp columns with the public series. Inputs are read as data: the zip, ESA's IBIATMS_2F daily files (public, no account), OMNI2 2023, GFZ Kp. Run: python3 -I swarma_date_proof.py Writes out/swarma_date_proof.json. """ import csv import glob import io import json import os 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 EPOCH0 = 62167219200 # seconds from year 0 to 1970 in the CDF_EPOCH convention def read(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 main(): zpath, ibidir, idx, outdir = sys.argv[1], sys.argv[2], sys.argv[3], Path(sys.argv[4]) want = ["Latitude", "Longitude", "Radius", "Dst", "Kp"] with zipfile.ZipFile(zpath) as zf: data = {"train": read(zf, "SwarmA-MagSet/train.csv", want), "test": read(zf, "SwarmA-MagSet/test.csv", want)} dated = list(csv.DictReader(open(outdir / "swarma_samples_dated.csv", encoding="utf-8", newline=""))) 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, la, lo, ra, bi = c.read("Timestamp"), c.read("Latitude"), c.read("Longitude"), c.read("Radius"), c.read("Bubble_Index") for k in range(len(ts)): ibi[int(round(ts[k] / 1000))] = (la[k], lo[k], ra[k], bi[k]) # Public series. kp = {} for line in open(os.path.join(idx, "Kp_ap_since_1932.txt"), encoding="utf-8", errors="replace"): if line.startswith("#"): continue p = line.split() if len(p) >= 10 and int(p[0]) == 2023: kp[datetime(int(p[0]), int(p[1]), int(p[2]), int(float(p[3])), tzinfo=UTC)] = float(p[7]) dst = {} for line in open(os.path.join(idx, "omni2_2023.dat"), encoding="ascii", errors="replace"): p = line.split() dst[datetime(int(p[0]), 1, 1, int(p[2]), tzinfo=UTC) + timedelta(days=int(p[1]) - 1)] = float(p[40]) out = {} for name in ("train", "test"): d = data[name] rows = [r for r in dated if r["set"] == name] matched = 0 worst = 0.0 worst_r = 0.0 bub = {-1: 0, 0: 0, 1: 0} dst_errs = [] kp_bad = {str(s): 0 for s in (-3.0, -1.5, 0.0)} passes_with_bubble = 0 for s, r in enumerate(rows): t0 = datetime.strptime(r["t_first_row_utc"], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=UTC) any_b = False for row in range(LEN): t = t0 + timedelta(seconds=row) v = ibi.get(int(t.timestamp()) + EPOCH0) i = s * LEN + row if v is None: continue matched += 1 e = abs(v[0] - d["Latitude"][i]) + abs(((v[1] - d["Longitude"][i] + 180) % 360) - 180) worst = max(worst, e) worst_r = max(worst_r, abs(v[2] - d["Radius"][i])) bub[v[3]] = bub.get(v[3], 0) + 1 any_b = any_b or v[3] == 1 if row % 200 == 0: tm = t - timedelta(hours=0.5) h0 = tm.replace(minute=0, second=0, microsecond=0) f = (tm - h0).total_seconds() / 3600 a, b = dst.get(h0), dst.get(h0 + timedelta(hours=1)) dst_errs.append(abs(a + f * (b - a) - d["Dst"][i])) for sh in (-3.0, -1.5, 0.0): tk = t + timedelta(hours=sh) blk = tk.replace(hour=tk.hour - tk.hour % 3, minute=0, second=0, microsecond=0) if abs(kp.get(blk, -9) - d["Kp"][i]) > 0.01: kp_bad[str(sh)] += 1 passes_with_bubble += any_b out[name] = { "rows": len(d["Kp"]), "rows_matched_to_esa_swarm_a": matched, "worst_abs_lat_plus_lon_difference_deg": worst, "worst_abs_radius_difference_m": worst_r, "bubble_index_counts": {str(k): v for k, v in bub.items()}, "passes_with_a_bubble_flag": passes_with_bubble, "dst_checks": len(dst_errs), "dst_max_abs_error_omni_mid_hour_knots_nT": max(dst_errs), "dst_median_abs_error_nT": statistics.median(dst_errs), "kp_mismatches_by_shift_hours": kp_bad, } print(name, json.dumps(out[name]), flush=True) with open(outdir / "swarma_date_proof.json", "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=1) if __name__ == "__main__": main()