#!/usr/bin/env python3 """Exploratory checks added after the fresh review of 2026-11-06 (NOT pre-registered; say so wherever used). A. The pre-registered period split (RULES_placebo.txt, secondary (iii)), with bootstrap intervals (exploratory): NS50 KM share still "disturbed", storms minus storm-free starts, by period, at 24-144 h; log-rank within periods; the difference between the two periods' gaps at 48 and 72 h. B. The same within periods, on starts with >= 5 and >= 8 quiet days. C. Pooled differences, and like with like (>= 8 quiet days), at 96, 120 and 144 h, with intervals. D. Median change in TEC, storms minus storm-free starts, by period, at 24-96 h, with intervals. E. Storm-free starts close to storms: inside their matched storm's follow-up, or within 7 days after a Kp >= 6- bin; the KM without the latter. F. Quiet-day mix: a log-rank stratified by quiet-day count (< 5, 5-7, >= 8), and storm-free curves reweighted to the storms' mix. G. Numbers the page used that no hosted script computed: SYM-H on GFZ quiet days; the whole-week share of storm-free hours outside the band, above and below; the band's width; the chance an exchangeable day falls outside a band built from 8 others. H. Kp in the three days after t0, storms against storm-free starts. I. Where our storm curve differs from the note's. Usage: python3 -I review_checks.py (writes /results/review_checks.json) """ import csv import datetime as dt import json import os import random import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import check_symh # noqa: E402 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 HRS = (24, 48, 72, 96, 120, 144) SEED = 20261106 NB = 2000 def read(path): with open(path, encoding="utf-8", newline="") as f: return list(csv.DictReader(f)) def S(t, e, h): return st.surv_at(st.km(t, e), h) def boot_diff(a, b, hours, rng): """a, b: lists of (T, event). Returns {h: (diff, lo, hi)} for S_a(h) - S_b(h), and the draws.""" ta, ea = [x[0] for x in a], [x[1] for x in a] tb, eb = [x[0] for x in b], [x[1] for x in b] point = {h: S(ta, ea, h) - S(tb, eb, h) for h in hours} draws = {h: [] for h in hours} for _ in range(NB): ra = [a[rng.randrange(len(a))] for _ in a] rb = [b[rng.randrange(len(b))] for _ in b] ca = st.km([x[0] for x in ra], [x[1] for x in ra]) cb = st.km([x[0] for x in rb], [x[1] for x in rb]) for h in hours: draws[h].append(st.surv_at(ca, h) - st.surv_at(cb, h)) out = {} for h in hours: d = sorted(draws[h]) out[h] = (round(100 * point[h], 1), round(100 * d[int(0.025 * NB)], 1), round(100 * d[int(0.975 * NB) - 1], 1)) return out, draws def ci(v): v = sorted(v) return (round(v[int(0.025 * len(v))], 1), round(v[int(0.975 * len(v)) - 1], 1)) def strat_logrank(groups): """groups: list of (t1, e1, t2, e2) per stratum. Returns (chi2, p).""" import math o = e = v = 0.0 for t1, e1, t2, e2 in groups: if not t1 or not t2: continue times = sorted(set([x for x, ev in zip(t1, e1) if ev] + [x for x, ev in zip(t2, e2) if ev])) for t in times: n1 = sum(1 for x in t1 if x >= t) n2 = sum(1 for x in t2 if x >= t) d1 = sum(1 for x, ev in zip(t1, e1) if ev and x == t) d2 = sum(1 for x, ev in zip(t2, e2) if ev and x == t) n, d = n1 + n2, d1 + d2 if n < 2: continue o += d1 e += d * n1 / n v += d * (n1 / n) * (n2 / n) * (n - d) / (n - 1) z = (o - e) / math.sqrt(v) return round(z * z, 3), math.erfc(abs(z) / math.sqrt(2.0)) def main(): base = sys.argv[1] res, dl = os.path.join(base, "results"), os.path.join(base, "downloads") drive = os.path.join(dl, "s0-note-002-drive") rng = random.Random(SEED) out = {"note": "exploratory, added after the fresh review of 2026-11-06; not pre-registered"} srows = [r for r in read(os.path.join(res, "storms_recomputed.csv")) if r["band"] == "NS50"] prows = [r for r in read(os.path.join(res, "placebo_trec.csv")) if r["band"] == "NS50"] nq_s = {} for r in read(os.path.join(drive, "quiet_days_selected.csv")): nq_s[r["storm_id"]] = nq_s.get(r["storm_id"], 0) + 1 S_ = [(float(r["T_rec_h_ours"]), r["recovered_ours"] == "True", r["solar_phase"], nq_s[r["storm_id"]], r["storm_id"]) for r in srows] P_ = [(float(r["T_rec_h"]), r["recovered"] == "True", r["solar_phase"], int(r["n_quiet"]), r["storm_id"], r["placebo_t0_utc"]) for r in prows] # A. period split with intervals A = {} draws_gap = {} for ph in ("SC24_decline", "SC25"): a = [(x[0], x[1]) for x in S_ if x[2] == ph] b = [(x[0], x[1]) for x in P_ if x[2] == ph] d, draws = boot_diff(a, b, HRS, rng) chi2, p, _, _ = st.logrank([x[0] for x in a], [x[1] for x in a], [x[0] for x in b], [x[1] for x in b]) A[ph] = {"n_storms": len(a), "n_placebo": len(b), "diff_pts_ci": d, "logrank_p": round(p, 3), "S_storms": {h: round(100 * S([x[0] for x in a], [x[1] for x in a], h), 1) for h in HRS}, "S_placebo": {h: round(100 * S([x[0] for x in b], [x[1] for x in b], h), 1) for h in HRS}} draws_gap[ph] = draws A["gap_difference_between_periods"] = { h: (round(A["SC24_decline"]["diff_pts_ci"][h][0] - A["SC25"]["diff_pts_ci"][h][0], 1), ci([100 * (u - w) for u, w in zip(draws_gap["SC24_decline"][h], draws_gap["SC25"][h])])) for h in (48, 72)} out["A_period_split"] = A # B. within periods, quiet-day restrictions B = {} for ph in ("SC24_decline", "SC25"): for q in (5, 8): a = [(x[0], x[1]) for x in S_ if x[2] == ph and x[3] >= q] b = [(x[0], x[1]) for x in P_ if x[2] == ph and x[3] >= q] d, _ = boot_diff(a, b, (24, 48, 72, 96), rng) B["%s_q%d" % (ph, q)] = {"n_storms": len(a), "n_placebo": len(b), "diff_pts_ci": d} out["B_period_by_quiet_days"] = B # C. pooled and like with like a = [(x[0], x[1]) for x in S_] b = [(x[0], x[1]) for x in P_] out["C_pooled"], _ = boot_diff(a, b, HRS, rng) a8 = [(x[0], x[1]) for x in S_ if x[3] >= 8] b8 = [(x[0], x[1]) for x in P_ if x[3] >= 8] out["C_like_with_like_q8"], _ = boot_diff(a8, b8, HRS, rng) out["C_like_with_like_q8_n"] = (len(a8), len(b8)) # D. median change in TEC by period opts = tp.Opts(dipole="map", lon73=False, pct="linear", midnight="prev24", run2h=6) store = tp.BandStore(os.path.join(dl, "code-gim"), os.path.join(base, "work"), os.path.join(dl, "igrf14", "igrf14coeffs.txt"), opts) inv = {r["storm_id"]: r for r in read(os.path.join(drive, "storm_inventory.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"])) plac = {p["storm_id"]: p for p in read(os.path.join(res, "placebos.csv")) if p["placebo_t0_utc"] and p["quiet_days"]} def series(t0, qd, F, hours): env = tp.quiet_envelope(store, qd, "NS50", "linear") d = {} for h in hours: if h >= F: continue tt = t0 + dt.timedelta(hours=h) v = store.value(tt, "NS50") if v is not None: d[h] = 100.0 * (v - env[tt.hour][2]) / env[tt.hour][2] return d DH = (24, 48, 72, 96) D = {} for ph in ("SC24_decline", "SC25"): ss = [series(P(r["t0_utc"]), qsel[sid], float(r["window_h"]), DH) for sid, r in inv.items() if r["solar_phase"] == ph] pp = [series(P(p["placebo_t0_utc"]), [dt.date.fromisoformat(x) for x in p["quiet_days"].split(";")], 168.0, DH) for sid, p in plac.items() if inv[sid]["solar_phase"] == ph] D[ph] = {} for h in DH: u = [x[h] for x in ss if h in x] w = [x[h] for x in pp if h in x] dd = [] for _ in range(NB): uu = [u[rng.randrange(len(u))] for _ in u] ww = [w[rng.randrange(len(w))] for _ in w] dd.append(st.median(uu) - st.median(ww)) D[ph][h] = {"storms": round(st.median(u), 1), "placebo": round(st.median(w), 1), "gap": round(st.median(u) - st.median(w), 1), "ci95": ci(dd), "n": (len(u), len(w))} out["D_dip_by_period"] = D # E. starts close to storms 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)} six = [t for t, k in zip(ts, ks) if k >= kp_lib.KP6M] inside, inside_win, recent = [], [], [] for sid, p in plac.items(): t = P(p["placebo_t0_utc"]) r = inv[sid] if P(r["t0_utc"]) <= t < P(r["t0_utc"]) + dt.timedelta(hours=168): inside.append(sid) if P(r["t0_utc"]) <= t < P(r["t0_utc"]) + dt.timedelta(hours=float(r["window_h"])): inside_win.append((sid, round((t - P(r["t0_utc"])).total_seconds() / 86400.0, 2))) if any(t - dt.timedelta(days=7) <= x < t for x in six): recent.append(sid) keep = [(x[0], x[1]) for x in P_ if x[4] not in recent] chi2, p, _, _ = st.logrank([x[0] for x in S_], [x[1] for x in S_], [x[0] for x in keep], [x[1] for x in keep]) ck = st.km([x[0] for x in keep], [x[1] for x in keep]) out["E_close_to_storms"] = {"inside_matched_7d_after_t0": sorted(inside), "n_inside": len(inside), "n_inside_matched_window": len(inside_win), "inside_matched_window_days_after_t0": inside_win, "n_within_7d_after_kp6": len(recent), "without_them": {"n": len(keep), "median_h": st.km_median(ck), "S96": round(100 * st.surv_at(ck, 96), 1), "logrank_p_vs_storms": round(p, 3)}} # F. quiet-day mix def stratum(n): return "lt5" if n < 5 else ("5to7" if n <= 7 else "ge8") groups = [] for k in ("lt5", "5to7", "ge8"): a = [x for x in S_ if stratum(x[3]) == k] b = [x for x in P_ if stratum(x[3]) == k] groups.append(([x[0] for x in a], [x[1] for x in a], [x[0] for x in b], [x[1] for x in b])) out["F_stratified_logrank"] = strat_logrank(groups) w = {k: sum(1 for x in S_ if stratum(x[3]) == k) / len(S_) for k in ("lt5", "5to7", "ge8")} rw = {} for h in (24, 48, 96): tot = 0.0 for k in ("lt5", "5to7", "ge8"): b = [x for x in P_ if stratum(x[3]) == k] tot += w[k] * S([x[0] for x in b], [x[1] for x in b], h) rw[h] = round(100 * tot, 1) out["F_placebo_reweighted_to_storm_mix"] = {"weights": {k: round(v, 3) for k, v in w.items()}, "S": rw, "storms_S": {h: round(100 * S([x[0] for x in S_], [x[1] for x in S_], h), 1) for h in (24, 48, 96)}} # G. numbers no hosted script computed sym = {} for y in (2015, 2024, 2025): sym.update(check_symh.load_symh(os.path.join(dl, "omni-hro", "omni_5min%d.asc" % y))) qd, _ = kp_lib.load_qdays(os.path.join(dl, "gfz-kp"), range(2015, 2026)) vq = [v for t, v in sym.items() if t.date() in qd] tot = outn = above = 0 for sid, p in plac.items(): qds = [dt.date.fromisoformat(x) for x in p["quiet_days"].split(";")] env = tp.quiet_envelope(store, qds, "NS50", "linear") t0 = P(p["placebo_t0_utc"]) r = tp.recovery(store, env, t0, 168, "NS50") for k, v, ins in r["series"]: if ins is None: continue tot += 1 if not ins: outn += 1 above += v > env[(t0 + dt.timedelta(hours=k)).hour][3] env_rows = [r for r in read(os.path.join(drive, "quiet_band_envelopes.csv")) if r["band"] == "NS50"] same = [r for r in env_rows if r["band_type"] == "sameUT"] wid = lambda rows: st.median([(float(r["q975"]) - float(r["q025"])) / float(r["q50"]) for r in rows]) # noqa: E731 lowhalf = st.median([(float(r["q50"]) - float(r["q025"])) / float(r["q50"]) for r in same]) sim = random.Random(1) outside = 0 for _ in range(200000): v = [sim.gauss(0, 1) for _ in range(8)] x = sim.gauss(0, 1) outside += x < tp.percentile(v, 0.025) or x > tp.percentile(v, 0.975) out["G_unscripted_numbers"] = { "symh_qdays_median_nT": st.median(vq), "symh_qdays_iqr": (st.quantile(vq, 0.25), st.quantile(vq, 0.75)), "placebo_hours_outside": (outn, tot, round(100 * outn / tot, 1)), "share_of_outside_above": round(100 * above / outn, 1), "band_width_sameUT_pct": round(100 * wid(same), 1), "band_width_all_cells_pct": round(100 * wid(env_rows), 1), "band_lower_half_sameUT_pct": round(100 * lowhalf, 1), "p_outside_8_days_sim": round(outside / 200000, 3), "mean_quiet_days_storms": round(sum(x[3] for x in S_) / len(S_), 2), "mean_quiet_days_placebo": round(sum(x[3] for x in P_) / len(P_), 2), "first_bin_kp_4minus_to_4plus": sum(1 for r in inv.values() if 3.666 <= ks[idx[P(r["t0_utc"])]] <= 4.334), "either_opening_bin_kp_4minus_or_more": sum(1 for r in inv.values() if max(ks[idx[P(r["t0_utc"])]], ks[idx[P(r["t0_utc"])] + 1]) >= 3.666)} # H. Kp after t0 idx = {t: i for i, t in enumerate(ts)} def kp_days(t0, window_h): """Kp bins of days 1-3 after t0, stopping at the end of follow-up (a new storm), as the note's masking.""" i = idx[t0] nmax = int(window_h // 3) return [[ks[i + j] for j in range(8 * d, 8 * (d + 1)) if j < nmax] for d in range(3)] sk = [kp_days(P(r["t0_utc"]), float(r["window_h"])) for r in inv.values()] pk = [kp_days(P(p["placebo_t0_utc"]), 168.0) for p in plac.values()] def mean_day(rows, d): v = [k for x in rows for k in x[d]] return round(sum(v) / len(v), 2) day1 = [k for x in sk for k in x[0]] out["H_kp_after_t0"] = { "storms_mean_kp_days_1_3_masked": [mean_day(sk, d) for d in range(3)], "storms_share_ge_4minus_day1": round(100 * sum(1 for k in day1 if k >= 3.666) / len(day1), 1), "placebo_mean_kp_days_1_3": [mean_day(pk, d) for d in range(3)]} # I. our storm curve against the note's km = [r for r in read(os.path.join(res, "km_compare.csv")) if r["band"] == "NS50" and r["group"] in ("storms_ours", "storms_note")] ours = {int(r["hour"]): float(r["S"]) for r in km if r["group"] == "storms_ours"} note = {int(r["hour"]): float(r["S"]) for r in km if r["group"] == "storms_note"} diff = [(h, round(100 * (ours[h] - note[h]), 1)) for h in sorted(ours) if abs(ours[h] - note[h]) > 1e-9] out["I_storm_curve_vs_note"] = {"hours_that_differ": diff} with open(os.path.join(res, "review_checks.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=1, default=str) print(json.dumps(out, indent=1, default=str)) if __name__ == "__main__": main()