#!/usr/bin/env python3 """Storm replication, placebo test and Kp-quiet sensitivity (RULES_spotcheck.txt, RULES_placebo.txt, RULES_kpquiet_symh.txt part A), with the locked implementation. Usage: python3 -I run_all.py [--run2h 6|7] Writes results/*.csv and results/summary.json. """ import csv import datetime as dt import json import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import kp_lib # noqa: E402 import stats_lib as st # noqa: E402 import tec_pipeline as tp # noqa: E402 P = lambda s: dt.datetime.strptime(s, "%Y-%m-%dT%H:%MZ") # noqa: E731 HOURS = (0, 12, 24, 48, 72, 96, 120, 144, 167) BANDS = tp.BAND_KEYS def read(path): with open(path, encoding="utf-8", newline="") as f: return list(csv.DictReader(f)) def write_csv(path, rows, keys=None): keys = keys or list(rows[0].keys()) with open(path, "w", encoding="utf-8", newline="\n") as f: w = csv.DictWriter(f, fieldnames=keys, lineterminator="\n", extrasaction="ignore") w.writeheader() w.writerows(rows) def km_info(times, events): c = st.km(times, events) return {"n": len(times), "recovered": sum(events), "n_Trec0": sum(1 for t, e in zip(times, events) if e and t == 0), "never": sum(1 for t, e in zip(times, events) if not e), "median_h": st.km_median(c), "S": {str(h): round(st.surv_at(c, h), 4) for h in HOURS}}, c def main(): base = sys.argv[1] run2h = int(sys.argv[sys.argv.index("--run2h") + 1]) if "--run2h" in sys.argv else 6 dl = os.path.join(base, "downloads") res_dir = os.path.join(base, "results") opts = tp.Opts(dipole="map", lon73=False, pct="linear", midnight="prev24", run2h=run2h) store = tp.BandStore(os.path.join(dl, "code-gim"), os.path.join(base, "work"), os.path.join(dl, "igrf14", "igrf14coeffs.txt"), opts) drive = os.path.join(dl, "s0-note-002-drive") inv = read(os.path.join(drive, "storm_inventory.csv")) rec_note = {(r["storm_id"], r["band"]): r for r in read(os.path.join(drive, "recovery_times.csv"))} qsel = {} for r in read(os.path.join(drive, "quiet_days_selected.csv")): qsel.setdefault(r["storm_id"], []).append(dt.date.fromisoformat(r["quiet_date"])) env_note = {} for r in read(os.path.join(drive, "quiet_band_envelopes.csv")): env_note[(r["storm_id"], r["band"], int(r["ut_hour"]))] = r plac = read(os.path.join(res_dir, "placebos.csv")) spot = [x.strip() for x in open(os.path.join(res_dir, "spotcheck_sample.txt"), encoding="utf-8") if x.strip()] summary = {"opts": repr(opts)} # ------------------------------------------------------------------ storms storm_rows = [] env_stats = {"cells": 0, "match": 0, "maxd": 0.0} storm_series = {} missing_storms = [] for r in inv: sid = r["storm_id"] t0 = P(r["t0_utc"]) F = float(r["window_h"]) qd = qsel[sid] need = set(qd) | set((t0 + dt.timedelta(hours=k)).date() for k in range(int(F))) if any(store.day(d) is None for d in need): missing_storms.append(sid) continue for band in BANDS: env = tp.quiet_envelope(store, qd, band, opts.pct) for h in range(24): n = env_note[(sid, band, h)] for name, idx in (("q025", 1), ("q50", 2), ("q975", 3)): d = abs(env[h][idx] - float(n[name])) env_stats["cells"] += 1 env_stats["match"] += int(d <= 0.0015) env_stats["maxd"] = max(env_stats["maxd"], d) out = tp.recovery(store, env, t0, F, band, run2h=run2h) note = rec_note[(sid, band)] row = {"storm_id": sid, "band": band, "t0_utc": r["t0_utc"], "window_h": F, "solar_phase": r["solar_phase"], "in_spotcheck": sid in spot, "T_rec_h_ours": out["T_rec_h"], "recovered_ours": out["recovered"], "T_rec_h_note": float(note["T_rec_h"]), "recovered_note": note["recovered"] == "TRUE", "frac_out_0_24_ours": out["frac_outside_0_24h"], "frac_out_0_24_note": float(note["frac_outside_0_24h"]), "dTEC_0_24_ours": out["dTEC_pct_median_0_24h"], "dTEC_0_24_note": float(note["dTEC_pct_median_0_24h"]), "n_grid_ours": out["n_grid"], "n_grid_note": int(note["n_grid"])} row["same_T_rec"] = abs(row["T_rec_h_ours"] - row["T_rec_h_note"]) < 1e-9 and row["recovered_ours"] == row["recovered_note"] storm_rows.append(row) if band == "NS50": storm_series[sid] = (t0, env) write_csv(os.path.join(res_dir, "storms_recomputed.csv"), storm_rows) summary["storms_missing_files"] = missing_storms summary["envelope_agreement"] = env_stats agree = {} for band in BANDS: rows = [x for x in storm_rows if x["band"] == band] agree[band] = {"n": len(rows), "same_T_rec": sum(1 for x in rows if x["same_T_rec"]), "within_1h": sum(1 for x in rows if abs(x["T_rec_h_ours"] - x["T_rec_h_note"]) <= 1 and x["recovered_ours"] == x["recovered_note"]), "spot_n": sum(1 for x in rows if x["in_spotcheck"]), "spot_same": sum(1 for x in rows if x["in_spotcheck"] and x["same_T_rec"])} summary["trec_agreement"] = agree summary["trec_disagreements_NS50"] = [(x["storm_id"], x["T_rec_h_note"], x["T_rec_h_ours"], x["recovered_note"], x["recovered_ours"]) for x in storm_rows if x["band"] == "NS50" and not x["same_T_rec"]] # ------------------------------------------------------------------ placebos plac_rows = [] plac_series = {} missing_plac = [] no_quiet_plac = [] for p in plac: if not p["placebo_t0_utc"]: continue t = P(p["placebo_t0_utc"]) qd = [dt.date.fromisoformat(x) for x in p["quiet_days"].split(";") if x] if not qd: # amendment A1: no quiet day at all -> dropped and counted no_quiet_plac.append(p["storm_id"]) continue need = set(qd) | set((t + dt.timedelta(hours=k)).date() for k in range(-24, 168)) if any(store.day(d) is None for d in need): missing_plac.append(p["storm_id"]) continue storm_phase = next(r["solar_phase"] for r in inv if r["storm_id"] == p["storm_id"]) for band in BANDS: env = tp.quiet_envelope(store, qd, band, opts.pct) full = tp.recovery(store, env, t, 168, band, run2h=run2h) cens = tp.recovery(store, env, t, float(p["storm_window_h"]), band, run2h=run2h) plac_rows.append({"storm_id": p["storm_id"], "band": band, "placebo_t0_utc": p["placebo_t0_utc"], "solar_phase": storm_phase, "n_quiet": len(qd), "pooled_hours": sum(1 for h in range(24) if env[h][4] != "sameUT"), "T_rec_h": full["T_rec_h"], "recovered": full["recovered"], "T_rec_h_matchcens": cens["T_rec_h"], "recovered_matchcens": cens["recovered"], "followup_matchcens": float(p["storm_window_h"]), "frac_out_0_24": full["frac_outside_0_24h"], "dTEC_0_24": full["dTEC_pct_median_0_24h"]}) if band == "NS50": plac_series[p["storm_id"]] = (t, env) write_csv(os.path.join(res_dir, "placebo_trec.csv"), plac_rows) summary["placebos_missing_files"] = missing_plac summary["placebos_no_quiet_days"] = no_quiet_plac nq_storm = {r["storm_id"]: len(qsel[r["storm_id"]]) for r in inv} # ------------------------------------------------------------------ KM comparisons comp = {} km_rows = [] for band in BANDS: s_rows = [x for x in storm_rows if x["band"] == band] p_rows = [x for x in plac_rows if x["band"] == band] groups = { "storms_note": ([x["T_rec_h_note"] for x in s_rows], [x["recovered_note"] for x in s_rows]), "storms_ours": ([x["T_rec_h_ours"] for x in s_rows], [x["recovered_ours"] for x in s_rows]), "placebo": ([x["T_rec_h"] for x in p_rows], [x["recovered"] for x in p_rows]), "placebo_matchcens": ([x["T_rec_h_matchcens"] for x in p_rows], [x["recovered_matchcens"] for x in p_rows]), } # amendment A2: both groups restricted to starts with >= 5 quiet days groups["storms_ours_q5"] = ([x["T_rec_h_ours"] for x in s_rows if nq_storm[x["storm_id"]] >= 5], [x["recovered_ours"] for x in s_rows if nq_storm[x["storm_id"]] >= 5]) groups["placebo_q5"] = ([x["T_rec_h"] for x in p_rows if x["n_quiet"] >= 5], [x["recovered"] for x in p_rows if x["n_quiet"] >= 5]) for ph in ("SC24_decline", "SC25"): groups["storms_ours_" + ph] = ([x["T_rec_h_ours"] for x in s_rows if x["solar_phase"] == ph], [x["recovered_ours"] for x in s_rows if x["solar_phase"] == ph]) groups["placebo_" + ph] = ([x["T_rec_h"] for x in p_rows if x["solar_phase"] == ph], [x["recovered"] for x in p_rows if x["solar_phase"] == ph]) comp[band] = {} for g, (t, e) in groups.items(): if not t: continue info, curve = km_info(t, e) comp[band][g] = info for h in range(0, 169): km_rows.append({"band": band, "group": g, "hour": h, "S": round(st.surv_at(curve, h), 4)}) ts, es = groups["storms_ours"] tpl, epl = groups["placebo"] chi2, p, o1, e1 = st.logrank(ts, es, tpl, epl) comp[band]["logrank_storms_ours_vs_placebo"] = {"chi2": round(chi2, 3), "p": p, "O_storm": o1, "E_storm": round(e1, 2)} chi2n, pn, _, _ = st.logrank(*groups["storms_note"], tpl, epl) comp[band]["logrank_storms_note_vs_placebo"] = {"chi2": round(chi2n, 3), "p": pn} tpc, epc = groups["placebo_matchcens"] chi2c, pc, _, _ = st.logrank(ts, es, tpc, epc) comp[band]["logrank_storms_ours_vs_placebo_matchcens"] = {"chi2": round(chi2c, 3), "p": pc} chi2q, pq, _, _ = st.logrank(*groups["storms_ours_q5"], *groups["placebo_q5"]) comp[band]["logrank_q5"] = {"chi2": round(chi2q, 3), "p": pq} if band == "NS50": bs = st.bootstrap_diff(ts, es, tpl, epl, (24, 48, 96)) comp[band]["bootstrap"] = {"diff_S_storm_minus_placebo_95ci": {str(k): v for k, v in bs["diff_ci"].items()}, "median_storm_95ci": bs["median1_ci"], "median_placebo_95ci": bs["median2_ci"]} # calibration: share of first-24-h hours outside the quiet range comp[band]["frac_out_0_24_mean"] = { "storms_ours": round(sum(x["frac_out_0_24_ours"] for x in s_rows) / len(s_rows), 4) if s_rows else None, "placebo": round(sum(x["frac_out_0_24"] for x in p_rows) / len(p_rows), 4) if p_rows else None} comp[band]["dTEC_0_24_median"] = {"storms_ours": st.median([x["dTEC_0_24_ours"] for x in s_rows]), "placebo": st.median([x["dTEC_0_24"] for x in p_rows])} summary["km"] = comp write_csv(os.path.join(res_dir, "km_compare.csv"), km_rows) # ------------------------------------------------------------------ superposed epoch strips (NS50 and others) strip_rows = [] for band in ("NS30", "NS50", "NS70"): for label, items, windows in ( ("storms_ours", [(P(r["t0_utc"]), qsel[r["storm_id"]], float(r["window_h"])) for r in inv if r["storm_id"] not in missing_storms], None), ("placebo", [(P(p["placebo_t0_utc"]), [dt.date.fromisoformat(x) for x in p["quiet_days"].split(";") if x], 168.0) for p in plac if p["placebo_t0_utc"] and p["quiet_days"] and p["storm_id"] not in missing_plac], None)): per_h = {h: [] for h in range(-24, 168)} for t0, qd, F in items: env = tp.quiet_envelope(store, qd, band, opts.pct) for h in range(-24, 168): if h >= F: break tt = t0 + dt.timedelta(hours=h) v = store.value(tt, band) if v is None: continue q50 = env[tt.hour][2] per_h[h].append(100.0 * (v - q50) / q50) for h in range(-24, 168): v = per_h[h] strip_rows.append({"band": band, "group": label, "hours_from_t0": h, "n": len(v), "median": round(st.median(v), 3) if v else "", "q25": round(st.quantile(v, 0.25), 3) if v else "", "q75": round(st.quantile(v, 0.75), 3) if v else ""}) write_csv(os.path.join(res_dir, "strip_compare.csv"), strip_rows) # ------------------------------------------------------------------ Kp-quiet sensitivity (part A) ts_, ks_, _ = kp_lib.load_kp(os.path.join(dl, "gfz-kp", "Kp_ap_Ap_SN_F107_since_1932.txt")) idx = {t: i for i, t in enumerate(ts_)} kq_rows = [] for r in inv: sid = r["storm_id"] t0 = P(r["t0_utc"]) i0 = idx[t0] F = float(r["window_h"]) end = t0 + dt.timedelta(hours=F) row = {"storm_id": sid, "t0_utc": r["t0_utc"], "kp_bin1": ks_[i0], "kp_bin2": ks_[i0 + 1], "t0_bins_active": ks_[i0] >= 3.667 - 1e-3 or ks_[i0 + 1] >= 3.667 - 1e-3} for lab, thr in (("3p", 3.333 + 1e-3), ("2p", 2.333 + 1e-3)): j = i0 found = None while ts_[j] + dt.timedelta(hours=6) <= end: if ks_[j] <= thr and ks_[j + 1] <= thr: found = j break j += 1 if found is None: row["shift_" + lab] = "" row["T_rec_" + lab] = "" row["rec_" + lab] = "" continue t0s = ts_[found] shift = (t0s - t0).total_seconds() / 3600.0 row["shift_" + lab] = shift if sid in storm_series: _, env = storm_series[sid] out = tp.recovery(store, env, t0s, F - shift, "NS50", run2h=run2h) row["T_rec_" + lab] = out["T_rec_h"] row["rec_" + lab] = out["recovered"] kq_rows.append(row) write_csv(os.path.join(res_dir, "kp_quiet_sensitivity.csv"), kq_rows, ["storm_id", "t0_utc", "kp_bin1", "kp_bin2", "t0_bins_active", "shift_3p", "T_rec_3p", "rec_3p", "shift_2p", "T_rec_2p", "rec_2p"]) kq = {"n_t0_bins_active": sum(1 for x in kq_rows if x["t0_bins_active"])} for lab in ("3p", "2p"): sh = [x["shift_" + lab] for x in kq_rows if x["shift_" + lab] != ""] kq["shift_" + lab] = {"n": len(sh), "none_before_end": len(kq_rows) - len(sh), "median": st.median(sh), "q25": st.quantile(sh, 0.25), "q75": st.quantile(sh, 0.75), "n_zero": sum(1 for x in sh if x == 0)} tt = [x["T_rec_" + lab] for x in kq_rows if x["T_rec_" + lab] != ""] ee = [x["rec_" + lab] for x in kq_rows if x["T_rec_" + lab] != ""] if tt: kq["km_" + lab], _ = km_info(tt, ee) summary["kp_quiet"] = kq summary["midnight_fallback_days"] = sorted(d.isoformat() for d in store.fallbacks) with open(os.path.join(res_dir, "summary.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(summary, f, indent=1, default=str) print(json.dumps({k: summary[k] for k in ("opts", "storms_missing_files", "placebos_missing_files", "envelope_agreement", "trec_agreement")}, indent=1, default=str)) if __name__ == "__main__": main()