#!/usr/bin/env python3 """Our analysis: May 2024's GPS scintillation against other storms at the same CHAIN stations. Usage: python3 -I chain_compare.py RAW_DIR DST_CSV GFZ_TXT OUT_DIR RAW_DIR folders storm_YYYY-MM-DD/ and quiet_2024-04-09_15/ holding CHAIN's hourly .ismr.gz files, read as data DST_CSV Kyoto's hourly Dst from its HAPI server (time, value, version code) GFZ_TXT GFZ's Kp_ap_Ap_SN_F107_since_1932.txt OUT_DIR where chain_station_window.csv, chain_compare.json and chain_compare.txt go Rules: RULES_before_running.txt and RULES_addendum_1.txt to _3.txt beside this script, hashed in rules_sha256.txt. The first three before any file was opened; addendum 3 (M7, post hoc) after a parser test on two windows. Standard library only. Nothing from the raw files is written out except counts, percentages and times. CHAIN's terms bar redistribution of its data, so only these derived numbers may be hosted. """ import array import csv import datetime as dt import gzip import json import math import os import random import sys sys.stdout.reconfigure(encoding="utf-8", errors="replace") STATIONS = { # geographic latitude and east longitude, from CHAIN's station page "eur": (79.990, 274.098), "arc": (73.004, 274.974), "sac": (71.991, 234.739), "gjo": (68.633, 264.152), "kug": (67.818, 244.865), "rep": (66.524, 273.769), "daw": (64.050, 220.889), "ran": (62.825, 267.885), "fsi": (61.757, 238.772), "arv": (61.098, 265.929), "fsm": (60.026, 248.067), "chu": (58.759, 265.913), "rab": (58.227, 256.323), "mcm": (56.650, 248.780), "edm": (53.351, 247.026)} GROUPS = {"polar cap": ["eur", "arc", "sac"], "high": ["gjo", "kug", "rep"], "auroral": ["daw", "ran", "fsi", "arv", "fsm", "chu", "rab"], "sub-auroral": ["mcm", "edm"]} ANCHORS = {"2015-03-17": "2015-03-17 22", "2015-06-23": "2015-06-23 04", "2015-12-20": "2015-12-20 22", "2018-08-26": "2018-08-26 07", "2023-03-24": "2023-03-24 02", "2023-04-24": "2023-04-24 05", "2023-11-05": "2023-11-05 19", "2024-05-11": "2024-05-11 02", "2024-08-12": "2024-08-12 16", "2024-10-11": "2024-10-11 01", "2025-01-01": "2025-01-01 15", "2025-11-12": "2025-11-12 04", "2026-01-20": "2026-01-20 16"} MAY = "2024-05-11" GPS0 = dt.datetime(1980, 1, 6) SHOCK = dt.datetime(2024, 5, 10, 17, 5) SYMH_MIN = dt.datetime(2024, 5, 11, 2, 14) COUNT_KEYS = ["all", "lock60", "l2_valid", "lock60_l2", "nosig", "sig30", "sig30_01", "sig30_05", "sig60", "sig60_01", "sig60_02", "sig60_05", "s4", "s4_01", "s4_02", "s4_03", "s4_06"] def leap(t): if t < dt.datetime(2015, 7, 1): return 16 if t < dt.datetime(2017, 1, 1): return 17 return 18 def num(x): try: v = float(x) except ValueError: return float("nan") return v def new_counts(): return {k: 0 for k in COUNT_KEYS} def read_window(folder, want_minutes=False): """Return per-station data: hours seen, counts per hour per elevation cut, and values for percentiles.""" out = {} skipped = {"bad_gz": 0, "short_lines": 0, "duplicates": 0} minutes = {} for name in sorted(os.listdir(folder)): if not name.endswith(".ismr.gz"): continue st = name[:3] if st not in STATIONS: continue hour_tag = name[:-8][-4:] # DDD + hour letter path = os.path.join(folder, name) try: with gzip.open(path, "rt", errors="replace") as f: lines = f.read().splitlines() except (OSError, EOFError): skipped["bad_gz"] += 1 continue d = out.setdefault(st, {"hours": {}, "sig30_values": array.array("f"), "s4_values": array.array("f")}) h30 = new_counts() h20 = new_counts() seen = set() hour_sig = [] minute_sky = {} for line in lines: p = line.split(",") if len(p) < 25: skipped["short_lines"] += 1 continue try: wn, tow, sv = int(p[0]), int(float(p[1])), int(p[2]) except ValueError: skipped["short_lines"] += 1 continue if not 1 <= sv <= 32: continue key = (wn, tow, sv) if key in seen: skipped["duplicates"] += 1 continue seen.add(key) el = num(p[5]) if not el > 20: continue s4t, s4c, phi30, phi60, lock = num(p[7]), num(p[8]), num(p[12]), num(p[13]), num(p[24]) lock2 = num(p[26]) if len(p) > 26 else float("nan") # second-frequency lock time, addendum 3 (post hoc) s4 = float("nan") if s4t == s4t: c = s4c if s4c == s4c else 0.0 s4 = math.sqrt(max(s4t * s4t - c * c, 0.0)) for cut, h in ((20, h20), (30, h30)): if not el > cut: continue h["all"] += 1 if lock == lock and lock < 60: h["lock60"] += 1 if lock2 == lock2: h["l2_valid"] += 1 h["lock60_l2"] += lock2 < 60 if phi30 == phi30 and phi30 >= 0: h["sig30"] += 1 h["sig30_01"] += phi30 > 0.1 h["sig30_05"] += phi30 > 0.5 else: h["nosig"] += 1 if phi60 == phi60 and phi60 >= 0: h["sig60"] += 1 h["sig60_01"] += phi60 > 0.1 h["sig60_02"] += phi60 > 0.2 h["sig60_05"] += phi60 > 0.5 if s4 == s4: h["s4"] += 1 h["s4_01"] += s4 > 0.1 h["s4_02"] += s4 > 0.2 h["s4_03"] += s4 > 0.3 h["s4_06"] += s4 > 0.6 if el > 30: if phi30 == phi30 and phi30 >= 0: d["sig30_values"].append(phi30) hour_sig.append(phi30) sky = minute_sky.setdefault(tow, [0, 0]) sky[0] += 1 sky[1] += phi30 > 0.1 if s4 == s4: d["s4_values"].append(s4) if want_minutes: t = GPS0 + dt.timedelta(weeks=wn, seconds=tow) t -= dt.timedelta(seconds=leap(t)) m = minutes.setdefault(st, {}).setdefault(t.replace(second=0, microsecond=0) + (dt.timedelta(minutes=1) if t.second >= 30 else dt.timedelta(0)), [0, 0, 0, 0, 0]) # sats above cut; with sigma>0.1; with sigma>0.5; with S4>0.3; with a sigma value m[0] += 1 if phi30 == phi30 and phi30 >= 0: m[4] += 1 m[1] += phi30 > 0.1 m[2] += phi30 > 0.5 if s4 == s4: m[3] += s4 > 0.3 d["hours"][hour_tag] = {30: h30, 20: h20, "median": quantile(hour_sig, 0.5) if hour_sig else float("nan"), "sky_minutes": sum(1 for v in minute_sky.values() if v[0] >= 4), "sky_all": sum(1 for v in minute_sky.values() if v[0] >= 4 and v[1] == v[0])} return out, skipped, minutes def pct(k, n): return 100.0 * k / n if n else float("nan") def quantile(values, q): v = sorted(values) if not v: return float("nan") x = q * (len(v) - 1) i = int(x) return v[i] if i + 1 >= len(v) else v[i] + (x - i) * (v[i + 1] - v[i]) def metrics(hours, cut=30, sigma="sig30", tags=None): c = new_counts() for tag, h in hours.items(): if tags is not None and tag not in tags: continue for k in COUNT_KEYS: c[k] += h[cut][k] return {"M1": pct(c[sigma + "_01"], c[sigma]), "M2": pct(c[sigma + "_05"], c[sigma]), "M3": pct(c["s4_03"], c["s4"]), "M4": pct(c["s4_06"], c["s4"]), "M6": 100.0 * c["lock60"] / (c["all"] / 60.0) if c["all"] else float("nan"), "M7": 100.0 * c["lock60_l2"] / (c["l2_valid"] / 60.0) if c["l2_valid"] else float("nan"), "S4gt01": pct(c["s4_01"], c["s4"]), "S4gt02": pct(c["s4_02"], c["s4"]), "sig60gt02": pct(c["sig60_02"], c["sig60"]), "nosig_share": pct(c["nosig"], c["all"]), "n_all": c["all"], "n_sig": c[sigma], "n_s4": c["s4"]} def clock_screen(hours): """RULES_addendum_2, B1. A clock fault raises the phase sigma on every satellite at once.""" minutes = sum(h["sky_minutes"] for h in hours.values()) every = sum(h["sky_all"] for h in hours.values()) meds = [h["median"] for h in hours.values() if h["median"] == h["median"]] share = 100.0 * every / minutes if minutes else float("nan") low = min(meds) if meds else float("nan") over = sum(1 for m in meds if m > 0.1) return {"every_sat_pct": round(share, 2), "lowest_hour_median": round(low, 3), "hours_median_over_0.1": over, "hours_with_median": len(meds), "flag": bool(share >= 25 or low > 0.1)} def rank_of(values, key): """Rank 1 = highest. values: dict window -> number.""" good = {k: v for k, v in values.items() if v == v} order = sorted(good, key=lambda k: -good[k]) return order.index(key) + 1, len(order), order def spearman(xs, ys): def ranks(v): idx = sorted(range(len(v)), key=lambda i: v[i]) r = [0.0] * len(v) i = 0 while i < len(v): j = i while j + 1 < len(v) and v[idx[j + 1]] == v[idx[i]]: j += 1 for k in range(i, j + 1): r[idx[k]] = (i + j) / 2.0 + 1 i = j + 1 return r a, b = ranks(xs), ranks(ys) ma, mb = sum(a) / len(a), sum(b) / len(b) num_ = sum((p - ma) * (q - mb) for p, q in zip(a, b)) den = math.sqrt(sum((p - ma) ** 2 for p in a) * sum((q - mb) ** 2 for q in b)) return num_ / den if den else float("nan") def window_tags(hours_seen, anchor, part="all"): """Hour tags of the 24-h window, or of its first or last 12 h.""" t0 = dt.datetime.strptime(anchor, "%Y-%m-%d %H") - dt.timedelta(hours=10) tags = [] rng = {"all": range(24), "first": range(12), "last": range(12, 24)}[part] for i in rng: t = t0 + dt.timedelta(hours=i) tags.append(f"{t.timetuple().tm_yday:03d}{chr(97 + t.hour)}") return tags def counts_station(data, window, st, cut=30): hrs = data[window].get(st, {}).get("hours", {}) return sum(1 for h in hrs), sum(h[cut]["all"] for h in hrs.values()) def main(): raw, dst_path, gfz_path, out_dir = sys.argv[1:5] os.makedirs(out_dir, exist_ok=True) say_lines = [] def say(s=""): say_lines.append(s) print(s, flush=True) # Side data dst = {} for r in csv.reader(open(dst_path, encoding="utf-8")): if len(r) >= 2: try: dst[r[0][:13]] = (float(r[1]), r[2]) except ValueError: pass gfz = {} for line in open(gfz_path, encoding="utf-8"): if line.startswith("#"): continue p = line.split() gfz[f"{p[0]}-{p[1]}-{p[2]}"] = (max(float(x) for x in p[7:15]), int(p[23]), float(p[25])) data, skipped_all = {}, {} minutes = {} for w in ANCHORS: folder = os.path.join(raw, "storm_" + w) # the fetch folder is named from the date of the anchor if not os.path.isdir(folder): say(f"MISSING FOLDER {folder}") data[w] = {} continue data[w], skipped_all[w], m = read_window(folder, want_minutes=(w == MAY)) if w == MAY: minutes = m say(f"read {w}: {sorted(data[w])}; skipped {skipped_all[w]}") quiet, skipped_all["quiet"], _ = read_window(os.path.join(raw, "quiet_2024-04-09_15")) say(f"read quiet week: {sorted(quiet)}; skipped {skipped_all['quiet']}") # Which station counts in which window counts = {w: {} for w in ANCHORS} for w in ANCHORS: for st in STATIONS: nh, nall = counts_station(data, w, st) counts[w][st] = nh >= 18 and nall >= 1000 since_2023 = [w for w in ANCHORS if w >= "2023"] panel_a = [s for s in STATIONS if all(counts[w][s] for w in ANCHORS)] panel_b = [s for s in STATIONS if all(counts[w][s] for w in since_2023)] say("") say(f"Panel A (all 13 windows): {panel_a}") say(f"Panel B (all {len(since_2023)} windows since 2023): {panel_b}") say("") say("Stations counting per window:") for w in ANCHORS: say(f" {w}: {[s for s in STATIONS if counts[w][s]]}") # Per station per window metrics rows = [] table = {w: {} for w in ANCHORS} for w in ANCHORS: for st in STATIONS: d = data[w].get(st) if not d: continue m = metrics(d["hours"]) m["M5"] = quantile(d["sig30_values"], 0.99) m["sig30_median"] = quantile(d["sig30_values"], 0.5) m["s4_median"] = quantile(d["s4_values"], 0.5) m["hours"] = len(d["hours"]) m["counts"] = counts[w][st] table[w][st] = m rows.append([w, st, STATIONS[st][0], m["hours"], m["n_all"], int(m["counts"])] + [round(m[k], 4) for k in ("M1", "M2", "M3", "M4", "M5", "M6", "M7", "S4gt01", "S4gt02", "nosig_share", "sig30_median", "s4_median")]) with open(os.path.join(out_dir, "chain_station_window.csv"), "w", encoding="utf-8", newline="\n") as f: wr = csv.writer(f, lineterminator="\n") wr.writerow(["window", "station", "lat_N", "hours_with_files", "gps_sat_minutes_above_30deg", "counts_for_panels", "M1_pct_sigma30_gt_0.1rad", "M2_pct_sigma30_gt_0.5rad", "M3_pct_S4_gt_0.3", "M4_pct_S4_gt_0.6", "M5_p99_sigma30_rad", "M6_L1_lock_lt60s_per_100_sat_hours", "M7_L2_lock_lt60s_per_100_sat_hours_post_hoc", "pct_S4_gt_0.1", "pct_S4_gt_0.2", "pct_no_sigma_in_file", "median_sigma30_rad", "median_S4"]) wr.writerows(rows) quiet_table = {} for st, d in quiet.items(): m = metrics(d["hours"]) m["M5"] = quantile(d["sig30_values"], 0.99) m["sig30_median"] = quantile(d["sig30_values"], 0.5) m["s4_median"] = quantile(d["s4_values"], 0.5) m["hours"] = len(d["hours"]) quiet_table[st] = m def panel_value(w, panel, key, tab=table): vals = [tab[w][s][key] for s in panel if s in tab[w] and tab[w][s][key] == tab[w][s][key]] return sum(vals) / len(vals) if vals and len(vals) == len(panel) else float("nan") # Clock screen, RULES_addendum_2 clock = {w: {st: clock_screen(data[w][st]["hours"]) for st in data[w]} for w in ANCHORS} clock_quiet = {st: clock_screen(quiet[st]["hours"]) for st in quiet} flagged = {w: [st for st in clock[w] if clock[w][st]["flag"]] for w in ANCHORS} say("") say("CLOCK SCREEN. Flagged station-windows (every-satellite share >= 25%, or lowest hourly median > 0.1 rad):") for w in ANCHORS: say(f" {w}: {[(st, clock[w][st]['every_sat_pct'], clock[w][st]['lowest_hour_median']) for st in flagged[w]]}") say(f" quiet week: {[(st, clock_quiet[st]['every_sat_pct'], clock_quiet[st]['lowest_hour_median']) for st in clock_quiet if clock_quiet[st]['flag']]}") say("Every-satellite share (percent of minutes with at least 4 satellites), by station and window:") say("win " + " ".join(f"{s:>5s}" for s in STATIONS)) for w in ANCHORS: say(w + " " + " ".join((f"{clock[w][s]['every_sat_pct']:5.1f}" if s in clock[w] else " ---") for s in STATIONS)) say("quiet " + " ".join((f"{clock_quiet[s]['every_sat_pct']:5.1f}" if s in clock_quiet else " ---") for s in STATIONS)) say("Lowest hourly median of sigma_phi (rad):") for w in ANCHORS: say(w + " " + " ".join((f"{clock[w][s]['lowest_hour_median']:5.3f}" if s in clock[w] else " ---") for s in STATIONS)) say("quiet " + " ".join((f"{clock_quiet[s]['lowest_hour_median']:5.3f}" if s in clock_quiet else " ---") for s in STATIONS)) def panel_value_clean(w, panel, key): vals = [table[w][s][key] for s in panel if s in table[w] and not clock[w][s]["flag"] and table[w][s][key] == table[w][s][key]] return sum(vals) / len(vals) if vals else float("nan") res = {"panel_a": panel_a, "panel_b": panel_b, "skipped": skipped_all, "windows": {}, "clock": {"flagged": flagged, "by_window": clock, "quiet": clock_quiet}} KEYS = ["M1", "M2", "M3", "M4", "M5", "M6", "M7"] say("") head = "window Dst maxKp Ap F10.7 | " + " ".join(f"{k:>7s}" for k in KEYS) for pname, panel, wins in (("A", panel_a, list(ANCHORS)), ("B", panel_b, since_2023)): say(f"Panel {pname} values ({len(panel)} stations), plain mean of stations:") say(head) for w in wins: a = ANCHORS[w] hour_key = a[:10] + "T" + a[11:13] d = dst.get(hour_key, (float("nan"), ""))[0] g = gfz.get(w, (float("nan"), 0, float("nan"))) vals = " ".join(f"{panel_value(w, panel, k):7.2f}" for k in KEYS) say(f"{w} {d:6.0f} {g[0]:6.2f} {g[1]:4d} {g[2]:6.1f} | {vals}") res["windows"].setdefault(w, {"dst": d, "maxKp_day": g[0], "Ap_day": g[1], "F107_obs": g[2], "doy": dt.date.fromisoformat(w).timetuple().tm_yday}) res["windows"][w]["panel_" + pname] = {k: round(panel_value(w, panel, k), 3) for k in KEYS} qv = {k: (sum(quiet_table[s][k] for s in panel if s in quiet_table) / max(1, sum(1 for s in panel if s in quiet_table))) for k in KEYS} say("quiet week " + " " * 26 + " ".join(f"{qv[k]:7.2f}" for k in KEYS)) res["quiet_panel_" + pname] = {k: round(qv[k], 3) for k in KEYS} say("") for k in KEYS: vals = {w: panel_value(w, panel, k) for w in wins} r, n, order = rank_of(vals, MAY) ratio = vals[MAY] / qv[k] if qv[k] else float("nan") say(f" {k}: May 2024 rank {r} of {n}; May 2024 {vals[MAY]:.2f}, quiet week {qv[k]:.2f}, ratio {ratio:.1f}; order {order[:5]}") res[f"rank_panel_{pname}_{k}"] = {"rank": r, "of": n, "may": round(vals[MAY], 3), "quiet": round(qv[k], 3), "ratio": round(ratio, 2), "order": order} say("") say(f" Without clock-suspect station-windows (addendum 2), Panel {pname}:") for k in KEYS: vals = {w: panel_value_clean(w, panel, k) for w in wins} r, n, order = rank_of(vals, MAY) say(f" {k}: May 2024 rank {r} of {n}; May 2024 {vals[MAY]:.2f}; order {[(w, round(vals[w], 2)) for w in order[:4]]}") res[f"rank_clean_panel_{pname}_{k}"] = {"rank": r, "of": n, "may": round(vals[MAY], 3), "order": order, "values": {w: round(vals[w], 3) for w in wins}} z1 = {} z2 = {} for w in wins: ms = [metrics(data[w][s]["hours"], cut=20, sigma="sig60") for s in panel if s in data[w]] z1[w] = sum(m["sig60gt02"] for m in ms) / len(ms) if ms else float("nan") z2[w] = sum(m["S4gt02"] for m in ms) / len(ms) if ms else float("nan") say(f" Zhao et al.'s thresholds, 60-s sigma > 0.2 rad and S4 > 0.2, 20-degree cut: May 2024 {z1[MAY]:.2f} and {z2[MAY]:.2f}; ranks {rank_of(z1, MAY)[0]} and {rank_of(z2, MAY)[0]} of {len(wins)}") res["zhao_thresholds_panel_" + pname] = {"sigma60_gt_0.2": {w: round(z1[w], 3) for w in wins}, "s4_gt_0.2": {w: round(z2[w], 3) for w in wins}} say("") # Sensitivities sens = {} def sens_vals(cut=30, sigma="sig30", part="all"): out = {} for w in wins: tags = window_tags(None, ANCHORS[w], part) vs = {k: [] for k in ("M1", "M2", "M3", "M6")} for s in panel: d = data[w].get(s) if not d: continue m = metrics(d["hours"], cut=cut, sigma=sigma, tags=tags) for k in vs: if m[k] == m[k]: vs[k].append(m[k]) out[w] = {k: (sum(v) / len(v) if len(v) == len(panel) else float("nan")) for k, v in vs.items()} return out for label, kw in (("elevation 20", dict(cut=20)), ("60-second sigma", dict(sigma="sig60")), ("first 12 h", dict(part="first")), ("last 12 h", dict(part="last"))): sv = sens_vals(**kw) line = [] for k in ("M1", "M2", "M3", "M6"): r, n, _ = rank_of({w: sv[w][k] for w in wins}, MAY) line.append(f"{k} rank {r}/{n} ({sv[MAY][k]:.2f})") say(f" sensitivity, {label}: " + "; ".join(line)) sens[label] = {k: {"rank": rank_of({w: sv[w][k] for w in wins}, MAY)[0], "may": round(sv[MAY][k], 3), "values": {w: round(sv[w][k], 3) for w in wins}} for k in ("M1", "M2", "M3", "M6")} season = [w for w in wins if min(abs(res["windows"][w]["doy"] - 131), 365 - abs(res["windows"][w]["doy"] - 131)) <= 60] line = [] for k in ("M1", "M2", "M3", "M6"): r, n, order = rank_of({w: panel_value(w, panel, k) for w in season}, MAY) line.append(f"{k} rank {r}/{n}") say(f" same season (within 60 days of day 131): {season}: " + "; ".join(line)) sens["same season"] = {"windows": season, **{k: rank_of({w: panel_value(w, panel, k) for w in season}, MAY)[0] for k in ("M1", "M2", "M3", "M6")}} res["sensitivity_panel_" + pname] = sens # Leave one station out loo = {} for k in ("M1", "M2", "M3", "M6"): ranks = [] for drop in panel: p2 = [s for s in panel if s != drop] ranks.append(rank_of({w: panel_value(w, p2, k) for w in wins}, MAY)[0]) loo[k] = [min(ranks), max(ranks)] say(f" leave one station out, range of May 2024's rank: {loo}") res["leave_one_out_panel_" + pname] = loo # Hour bootstrap rng = random.Random(20261104) hist = {k: [] for k in ("M1", "M3")} first = {k: 0 for k in ("M1", "M3")} top3 = {k: 0 for k in ("M1", "M3")} # added after a first look at the ranks; descriptive only draws = 2000 hourly = {} for w in wins: tags = window_tags(None, ANCHORS[w]) hourly[w] = {} for s in panel: hrs = data[w].get(s, {}).get("hours", {}) hourly[w][s] = [(hrs.get(t, {30: new_counts()})[30]) for t in tags] for _ in range(draws): vals = {k: {} for k in hist} for w in wins: idx = [rng.randrange(24) for _ in range(24)] m1, m3 = [], [] for s in panel: hs = hourly[w][s] a = sum(hs[i]["sig30_01"] for i in idx) b = sum(hs[i]["sig30"] for i in idx) c = sum(hs[i]["s4_03"] for i in idx) d = sum(hs[i]["s4"] for i in idx) if b: m1.append(100.0 * a / b) if d: m3.append(100.0 * c / d) vals["M1"][w] = sum(m1) / len(m1) if m1 else float("nan") vals["M3"][w] = sum(m3) / len(m3) if m3 else float("nan") for k in hist: hist[k].append(vals[k][MAY]) rk = rank_of(vals[k], MAY)[0] if rk == 1: first[k] += 1 if rk <= 3: top3[k] += 1 boot = {k: {"p2.5": round(quantile(hist[k], 0.025), 2), "p97.5": round(quantile(hist[k], 0.975), 2), "share_rank1": round(first[k] / draws, 3), "share_top3": round(top3[k] / draws, 3)} for k in hist} say(f" hour bootstrap, {draws} draws, seed 20261104: {boot}") res["bootstrap_panel_" + pname] = boot # Spearman with Dst across windows sp = {} ds = [-res["windows"][w]["dst"] for w in wins] for k in ("M1", "M2", "M3"): sp[k] = round(spearman(ds, [panel_value(w, panel, k) for w in wins]), 3) say(f" Spearman of M1-M3 with storm depth (-Dst), description only: {sp}") res["spearman_panel_" + pname] = sp say("") # Each station: rank of May 2024 among windows where it counts say("Each station, rank of May 2024 among the windows where that station counts (M1, M2, M3, M6):") per = {} for st in sorted(STATIONS, key=lambda s: -STATIONS[s][0]): wins = [w for w in ANCHORS if counts[w][st]] if MAY not in wins: say(f" {st}: no May 2024 data that counts") continue items = {} for k in ("M1", "M2", "M3", "M6"): r, n, order = rank_of({w: table[w][st][k] for w in wins}, MAY) items[k] = {"rank": r, "of": n, "may": round(table[MAY][st][k], 2), "quiet": round(quiet_table[st][k], 2) if st in quiet_table else None, "top": order[0], "top_value": round(table[order[0]][st][k], 2)} clean = [w for w in wins if not clock[w][st]["flag"]] for k in items: r, n, order = rank_of({w: table[w][st][k] for w in clean}, MAY) items[k]["rank_clean"], items[k]["of_clean"], items[k]["top_clean"] = r, n, order[0] per[st] = items say(f" {st} {STATIONS[st][0]:5.1f}N " + " ".join(f"{k} {items[k]['rank']}/{items[k]['of']} ({items[k]['may']}; top {items[k]['top']} {items[k]['top_value']})" for k in items)) if len(clean) != len(wins): say(f" without clock-suspect windows ({[w for w in wins if w not in clean]}): " + " ".join(f"{k} {items[k]['rank_clean']}/{items[k]['of_clean']}" for k in items)) res["per_station"] = per # Noise floor say("") say("Noise floor: median sigma30 (rad) by station and window (M5 p99 is in the CSV):") say("win " + " ".join(f"{s:>5s}" for s in STATIONS)) for w in ANCHORS: say(w + " " + " ".join((f"{table[w][s]['sig30_median']:5.3f}" if s in table[w] else " ---") for s in STATIONS)) say("quiet " + " ".join((f"{quiet_table[s]['sig30_median']:5.3f}" if s in quiet_table else " ---") for s in STATIONS)) say("Median S4:") for w in ANCHORS: say(w + " " + " ".join((f"{table[w][s]['s4_median']:5.3f}" if s in table[w] else " ---") for s in STATIONS)) say("quiet " + " ".join((f"{quiet_table[s]['s4_median']:5.3f}" if s in quiet_table else " ---") for s in STATIONS)) say("") say("Share of satellite-minutes above 30 degrees with no phase sigma in the file (percent):") for w in ANCHORS: say(w + " " + " ".join((f"{table[w][s]['nosig_share']:5.1f}" if s in table[w] else " ---") for s in STATIONS)) say("quiet " + " ".join((f"{quiet_table[s]['nosig_share']:5.1f}" if s in quiet_table else " ---") for s in STATIONS)) res["nosig_share"] = {w: {s: round(table[w][s]["nosig_share"], 2) for s in table[w]} for w in ANCHORS} res["quiet_table"] = {s: {k: round(v, 3) if isinstance(v, float) else v for k, v in quiet_table[s].items()} for s in quiet_table} res["station_window_table"] = {w: {s: {k: (round(v, 3) if isinstance(v, float) else v) for k, v in table[w][s].items()} for s in table[w]} for w in ANCHORS} # Second test: May 2024 timeline, all stations say("") say("SECOND TEST, May 2024. Onsets from 17:05 UT May 10, stations by geographic latitude (minutes after 17:05 in brackets):") say("station lat minutes 16:00-17:05 with >=2 sats sigma>0.1 | first >=2 sats sigma>0.1 | first >=1 sat sigma>0.5 | first >=1 sat S4>0.3") onsets = {} for st in sorted(STATIONS, key=lambda s: -STATIONS[s][0]): mm = minutes.get(st) if not mm: say(f"{st}: no data") continue before = sum(1 for t, v in mm.items() if dt.datetime(2024, 5, 10, 16) <= t < SHOCK and v[1] >= 2) before_n = sum(1 for t in mm if dt.datetime(2024, 5, 10, 16) <= t < SHOCK) def first(cond): ts = sorted(t for t, v in mm.items() if t >= SHOCK and cond(v)) return ts[0] if ts else None a, b, c = first(lambda v: v[1] >= 2), first(lambda v: v[2] >= 1), first(lambda v: v[3] >= 1) fmt = lambda t: "none" if t is None else f"{t:%H:%M} (+{int((t - SHOCK).total_seconds() // 60)})" say(f"{st} {STATIONS[st][0]:5.1f} {before:3d} of {before_n:3d} | {fmt(a)} | {fmt(b)} | {fmt(c)}") onsets[st] = {"lat": STATIONS[st][0], "before_minutes": before, "before_of": before_n, "sigma01_2sats": fmt(a), "sigma05_1sat": fmt(b), "s403_1sat": fmt(c)} res["onsets"] = onsets # Main against recovery say("") say("Main phase 17:05-02:14 against recovery 02:14-16:00, M1 and M3 from minute records above 30 degrees:") groups = {} for gname, members in GROUPS.items(): for st in members: mm = minutes.get(st) if not mm: continue tot = {"main": [0, 0, 0, 0], "rec": [0, 0, 0, 0]} for t, v in mm.items(): if SHOCK <= t < SYMH_MIN: part = "main" elif SYMH_MIN <= t < dt.datetime(2024, 5, 11, 16): part = "rec" else: continue tot[part][0] += v[4] tot[part][1] += v[1] tot[part][2] += v[0] tot[part][3] += v[3] g = groups.setdefault(gname, {}) g[st] = {p: {"M1": round(pct(tot[p][1], tot[p][0]), 2), "M2_like_sats": tot[p][0], "M3": round(pct(tot[p][3], tot[p][2]), 3)} for p in tot} say(f" {gname:11s} {st}: M1 main {g[st]['main']['M1']:6.2f} rec {g[st]['rec']['M1']:6.2f} M3 main {g[st]['main']['M3']:6.3f} rec {g[st]['rec']['M3']:6.3f}") res["main_recovery"] = groups # Hour by hour, M1 say("") say("M1 hour by hour, May 2024 (percent; UT hour of the file):") tags = window_tags(None, ANCHORS[MAY]) order = sorted(STATIONS, key=lambda s: -STATIONS[s][0]) say("hour " + " ".join(f"{s:>5s}" for s in order)) hourly_out = {} t0 = dt.datetime(2024, 5, 10, 16) for i, tag in enumerate(tags): cells = [] for s in order: h = data[MAY].get(s, {}).get("hours", {}).get(tag) if not h: cells.append(" ---") continue v = pct(h[30]["sig30_01"], h[30]["sig30"]) cells.append(f"{v:5.1f}" if v == v else " nan") hourly_out.setdefault(s, {})[f"{(t0 + dt.timedelta(hours=i)):%d %H}"] = round(v, 2) if v == v else None say(f"{(t0 + dt.timedelta(hours=i)):%d %H} " + " ".join(cells)) res["may_hourly_M1"] = hourly_out with open(os.path.join(out_dir, "chain_compare.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(res, f, indent=1, ensure_ascii=False) with open(os.path.join(out_dir, "chain_compare.txt"), "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(say_lines) + "\n") if __name__ == "__main__": main()