#!/usr/bin/env python3 """Has Earth's geomagnetic response to a given solar-wind input grown since 2023? Rules: RULES_response_test.txt (pre-registered). Run after reproduce.py: py -3.12 -I response_test.py Reads work/hourly_cache.npz (our own arrays from OMNI2), GFZ's Kp/ap and Hp60/ap60 files and Kyoto's Dst pages. Writes out/response_test/*. Needs numpy and scipy. """ import csv import json import math import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import numpy as np from scipy import stats import omni_common as oc OUTDIR = os.path.join(oc.OUT, "response_test") os.makedirs(OUTDIR, exist_ok=True) LOG = [] def log(*a): s = " ".join(str(x) for x in a) print(s) LOG.append(s) def wcsv(name, header, rows): with open(os.path.join(OUTDIR, name), "w", encoding="utf-8", newline="\n") as f: w = csv.writer(f, lineterminator="\n") w.writerow(header) w.writerows(rows) log("# response_test.py run") log("rules RULES_response_test.txt", oc.sha256(os.path.join(HERE, "RULES_response_test.txt"))) log("sha256 Kp_ap_since_1932.txt", oc.sha256(os.path.join(oc.DL, "gfz-kp", "Kp_ap_since_1932.txt"))) log("sha256 Hp60_ap60_complete_series.txt", oc.sha256(os.path.join(oc.DL, "gfz-hpo", "Hp60_ap60_complete_series.txt"))) log("sha256 hourly_cache.npz (ours, from OMNI2; file hashes in out/reproduction/hashes.json)", oc.sha256(os.path.join(oc.WORK, "hourly_cache.npz"))) c = np.load(os.path.join(oc.WORK, "hourly_cache.npz")) keep = c["year"] >= 1994 # one spare year so that trailing hours exist at 1995-01-01 year, month, dom, hour = c["year"][keep], c["month"][keep], c["dom"][keep], c["hour"][keep] V, BY, BZ, eps, valid = c["V"][keep], c["BY"][keep], c["BZ"][keep], c["eps"][keep], c["valid"][keep] dst_omni = c["dst_omni"][keep] new = oc.newell(V, BY, BZ) N = len(year) # ---------------------------------------------------------------- responses gfz = oc.read_gfz_kp() hp = oc.read_gfz_hp60() ap = np.full(N, np.nan); kp = np.full(N, np.nan); ap60 = np.full(N, np.nan); defin = np.zeros(N, dtype=int) for i in range(N): y, m, d_, h = int(year[i]), int(month[i]), int(dom[i]), int(hour[i]) g = gfz.get((y, m, d_, h // 3 * 3)) if g and g[0] >= 0: kp[i], ap[i], defin[i] = g[0], g[1], g[2] q = hp.get((y, m, d_, h)) if q and q[1] >= 0: ap60[i] = q[1] log("GFZ ap present for %d of %d hours from 1995; preliminary (D=0) hours used: %d (first %s)" % ((~np.isnan(ap[year >= 1995])).sum(), (year >= 1995).sum(), ((defin == 0) & ~np.isnan(ap) & (year >= 1995)).sum(), next(("%d-%02d-%02d" % (year[i], month[i], dom[i]) for i in range(N) if year[i] >= 1995 and defin[i] == 0 and not np.isnan(ap[i])), "none"))) # Kyoto Dst dst = np.full(N, np.nan) kinds = {} index = {(int(year[i]), int(month[i]), int(dom[i]), int(hour[i])): i for i in range(N)} kd = os.path.join(oc.DL, "kyoto-dst") nfiles = 0 for name in sorted(os.listdir(kd)): if not (name.startswith("dst_final_") or name.startswith("dst_provisional_")) or not name.endswith(".html"): continue ym = name.split("_")[2][:6] y, m = int(ym[:4]), int(ym[4:]) kind, days = oc.read_kyoto_month(os.path.join(kd, name)) kinds[ym] = kind nfiles += 1 for day, vals in days.items(): if len(vals) != 24: raise ValueError("%s day %d has %d values" % (name, day, len(vals))) for k, v in enumerate(vals): i = index.get((y, m, day, k)) if i is not None and v is not None: dst[i] = v log("Kyoto Dst pages read: %d; kinds: %s" % (nfiles, {k: sum(1 for v in kinds.values() if v == k) for k in set(kinds.values())})) for ym, kind in sorted(kinds.items()): want = "FINAL" if ym <= "202012" else "PROVISIONAL" if kind.upper() != want: log(" WARNING: %s is labelled %s" % (ym, kind)) sel = (year >= 1995) & (year <= 2020) & ~np.isnan(dst) & ~np.isnan(dst_omni) log("Parser check on final months 1995-2020: hours compared with OMNI2's Dst column %d; equal %d; largest |difference| %g nT" % (sel.sum(), (dst[sel] == dst_omni[sel]).sum(), np.max(np.abs(dst[sel] - dst_omni[sel])))) log("Dst hours present 1995-2025: %d of %d; first/last month read %s/%s" % ((~np.isnan(dst[(year >= 1995) & (year <= 2025)])).sum(), ((year >= 1995) & (year <= 2025)).sum(), min(kinds), max(kinds))) # ---------------------------------------------------------------- monthly table months = [(y, m) for y in range(1995, 2027) for m in range(1, 13)] M = {} for (y, m) in months: s = (year == y) & (month == m) & valid n = int(s.sum()) if n == 0: continue sd = s & ~np.isnan(dst) M[(y, m)] = dict(n=n, eps=float(eps[s].mean()), new=float(new[s].mean()), ap=float(np.nanmean(ap[s])), kp=float(np.nanmean(kp[s])), dst=float(dst[sd].mean()) if sd.sum() else float("nan"), n_dst=int(sd.sum()), ap60=float(np.nanmean(ap60[s]))) MIN_H = 360 dropped = [k for k in M if M[k]["n"] < MIN_H and k[0] <= 2025] log("Months 1995-01..2025-12 with valid hours: %d; dropped for fewer than %d valid hours: %s" % (sum(1 for k in M if k[0] <= 2025), MIN_H, dropped)) last26 = max([k for k in M if k[0] == 2026 and M[k]["n"] >= MIN_H and k[1] <= 9] or [(2026, 0)]) log("2026 months usable (>= %d valid hours, not later than September): %s" % (MIN_H, [k[1] for k in sorted(M) if k[0] == 2026 and M[k]["n"] >= MIN_H and k[1] <= 9])) wcsv("monthly_inputs_and_responses.csv", ["year", "month", "valid_hours", "eps_mean_W", "newell_mean", "ap_mean", "kp_mean", "ap60_mean", "dst_hours", "note"], [[y, m, M[(y, m)]["n"], repr(M[(y, m)]["eps"]), repr(M[(y, m)]["new"]), repr(M[(y, m)]["ap"]), repr(M[(y, m)]["kp"]), repr(M[(y, m)]["ap60"]), M[(y, m)]["n_dst"], "Dst monthly means are not written here: derived scores only"] for (y, m) in sorted(M)]) def usable(k): return k in M and M[k]["n"] >= MIN_H FORMS = { "ap": dict(resp="ap", fx=np.log, fy=np.log, sign=1.0), "kp": dict(resp="kp", fx=np.log, fy=lambda v: v, sign=1.0), "dst": dict(resp="dst", fx=lambda v: v, fy=lambda v: v, sign=-1.0), } def fit(train_keys, form, inp): f = FORMS[form] x = f["fx"](np.array([M[k][inp] for k in train_keys])) y = f["fy"](np.array([M[k][f["resp"]] for k in train_keys])) ok = ~np.isnan(x) & ~np.isnan(y) A = np.column_stack([np.ones(ok.sum()), x[ok]]) beta, *_ = np.linalg.lstsq(A, y[ok], rcond=None) res = y[ok] - A @ beta return beta, float(np.sqrt(res @ res / (ok.sum() - 2))), int(ok.sum()) def score(keys, beta, form, inp): f = FORMS[form] out = {} for k in keys: x = f["fx"](M[k][inp]); y = f["fy"](M[k][f["resp"]]) if not (math.isnan(x) or math.isnan(y)): out[k] = f["sign"] * (y - (beta[0] + beta[1] * x)) return out TRAIN = [k for k in sorted(M) if 1995 <= k[0] <= 2022 and usable(k)] REF = [(y0, y0 + 2) for y0 in range(1995, 2021)] results = {} month_scores = {} for form in ("ap", "kp", "dst"): for inp in ("eps", "new"): tag = "M-%s-%s" % (form, inp) beta_all, rmse, ntr = fit(TRAIN, form, inp) ws = {} for (a, b) in REF: tr = [k for k in TRAIN if not (a <= k[0] <= b)] be, _, _ = fit(tr, form, inp) sc = score([k for k in TRAIN if a <= k[0] <= b], be, form, inp) if len(sc) >= 30: ws["%d-%d" % (a, b)] = (float(np.mean(list(sc.values()))), len(sc)) test_keys = [k for k in sorted(M) if 2023 <= k[0] <= 2025 and usable(k)] sc_t = score(test_keys, beta_all, form, inp) s_test = float(np.mean(list(sc_t.values()))) refv = np.array([v[0] for v in ws.values()]) rank = 1 + int((refv > s_test).sum()) # per-year scores, leave-year-out for 1995-2022 yr = {} for y in range(1995, 2026): ky = [k for k in sorted(M) if k[0] == y and usable(k)] be = beta_all if y >= 2023 else fit([k for k in TRAIN if k[0] != y], form, inp)[0] sc = score(ky, be, form, inp) yr[y] = (float(np.mean(list(sc.values()))), len(sc)) for k, v in sc.items(): month_scores[(tag, k)] = v # partial 2026: January..last usable month (<= September), same months of other years mm = [m for m in range(1, last26[1] + 1)] part = {} for y in range(1995, 2027): ky = [(y, m) for m in mm if usable((y, m))] be = beta_all if y >= 2023 else fit([k for k in TRAIN if k[0] != y], form, inp)[0] sc = score(ky, be, form, inp) if len(sc) >= max(1, len(mm) - 2): part[y] = (float(np.mean(list(sc.values()))), len(sc)) p_ref = np.array([v[0] for y, v in part.items() if y <= 2025]) results[tag] = dict(beta=[float(b) for b in beta_all], rmse=rmse, n_train=ntr, windows=ws, test_2023_2025=dict(score=s_test, n_months=len(sc_t)), rank_of_test=rank, n_windows=len(ws) + 1, ref_mean=float(refv.mean()), ref_sd=float(refv.std(ddof=1)), ref_min=float(refv.min()), ref_max=float(refv.max()), ref_median=float(np.median(refv)), s_2000_2002=ws["2000-2002"][0], s_2013_2015=ws["2013-2015"][0], yearly=yr, partial_2026=dict(months=mm, by_year=part, rank_2026=(1 + int((p_ref > part[2026][0]).sum())) if 2026 in part else None, n_years=len(p_ref) + 1)) unit = "ln units" if form == "ap" else ("Kp units" if form == "kp" else "nT") log("%s: fit %s (n=%d, rmse %.4g). 2023-2025 score %+.4f %s; reference windows: mean %+.4f, sd %.4f, min %+.4f, median %+.4f, max %+.4f; rank of 2023-2025: %d of %d; 2000-2002 %+.4f; 2013-2015 %+.4f" % (tag, np.round(beta_all, 5).tolist(), ntr, rmse, s_test, unit, refv.mean(), refv.std(ddof=1), refv.min(), np.median(refv), refv.max(), rank, len(ws) + 1, ws["2000-2002"][0], ws["2013-2015"][0])) log(" windows: " + "; ".join("%s %+.3f" % (k, v[0]) for k, v in ws.items())) log(" years: " + "; ".join("%d %+.3f" % (y, v[0]) for y, v in yr.items())) if 2026 in part: log(" Jan-%02d 2026 score %+.4f (%d months); same months of 1995-2025: min %+.4f, median %+.4f, max %+.4f; rank of 2026: %d of %d" % (last26[1], part[2026][0], part[2026][1], p_ref.min(), np.median(p_ref), p_ref.max(), results[tag]["partial_2026"]["rank_2026"], len(p_ref) + 1)) # pass mark a, b = results["M-ap-eps"], results["M-ap-new"] def verdict_one(r): s = r["test_2023_2025"]["score"] if s > 0 and r["rank_of_test"] == 1 and s > r["s_2000_2002"] and s > r["s_2013_2015"]: return "supported" if s <= 0 or s <= r["ref_median"]: return "contradicted" return "not shown" v1, v2 = verdict_one(a), verdict_one(b) overall = "SUPPORTED" if v1 == v2 == "supported" else ("CONTRADICTED" if v1 == v2 == "contradicted" else "NOT SHOWN") log("PASS MARK: M-ap-eps -> %s; M-ap-new -> %s; overall -> %s" % (v1, v2, overall)) results["pass_mark"] = dict(eps=v1, newell=v2, overall=overall) # ---------------------------------------------------------------- regressions S-step, S-trend def nw_ols(X, y, L): n, k = X.shape XtXi = np.linalg.inv(X.T @ X) beta = XtXi @ X.T @ y e = y - X @ beta S = (X.T * (e ** 2)) @ X for l in range(1, L + 1): w = 1.0 - l / (L + 1.0) G = (X[l:].T * (e[l:] * e[:-l])) @ X[:-l] S = S + w * (G + G.T) Vh = XtXi @ S @ XtXi return beta, np.sqrt(np.diag(Vh)) keys = [k for k in sorted(M) if 1995 <= k[0] <= 2025 and usable(k)] tdec = np.array([k[0] + (k[1] - 0.5) / 12.0 for k in keys]) for inp in ("eps", "new"): lx = np.log(np.array([M[k][inp] for k in keys])); ly = np.log(np.array([M[k]["ap"] for k in keys])) step = (np.array([k[0] for k in keys]) >= 2023).astype(float) for name, extra in (("S-step", step), ("S-trend", tdec - 2010.0)): X = np.column_stack([np.ones(len(keys)), lx, extra]) beta, se = nw_ols(X, ly, 24) z = beta[2] / se[2] p = 2 * stats.norm.sf(abs(z)) results["%s-%s" % (name, inp)] = dict(coef=float(beta[2]), se=float(se[2]), lo=float(beta[2] - 1.96 * se[2]), hi=float(beta[2] + 1.96 * se[2]), p=float(p), n=len(keys), b=float(beta[1])) if name == "S-step": log("%s-%s: shift since 2023 at a given input d = %+.4f ln units (%+.1f%%), Newey-West (24 lags) SE %.4f, 95%% interval %+.1f%% to %+.1f%%, p = %.3f (n=%d months)" % (name, inp, beta[2], 100 * (math.exp(beta[2]) - 1), se[2], 100 * (math.exp(beta[2] - 1.96 * se[2]) - 1), 100 * (math.exp(beta[2] + 1.96 * se[2]) - 1), p, len(keys))) else: log("%s-%s: drift at a given input c = %+.5f ln units a year (%+.1f%% a decade), SE %.5f, 95%% interval %+.1f%% to %+.1f%% a decade, p = %.3f" % (name, inp, beta[2], 100 * (math.exp(10 * beta[2]) - 1), se[2], 100 * (math.exp(10 * (beta[2] - 1.96 * se[2])) - 1), 100 * (math.exp(10 * (beta[2] + 1.96 * se[2])) - 1), p)) # ---------------------------------------------------------------- Test H v3 = valid.copy() v3[1:] &= valid[:-1] v3[2:] &= valid[:-2] v3[:2] = False for inp, arr in (("eps", eps), ("new", new)): x = np.full(N, np.nan) a0 = np.where(valid, arr, np.nan) x[2:] = (a0[2:] + a0[1:-1] + a0[:-2]) / 3.0 use = v3 & (year >= 1995) & (year <= 2025) & ~np.isnan(ap60) tr = use & (year <= 2022) lx = np.full(N, np.nan) pos = use & (x > 0) lx[pos] = np.log10(x[pos]) lo = math.floor(np.nanmin(lx[tr & pos]) * 10) / 10.0 hi = math.ceil(np.nanmax(lx[tr & pos]) * 10) / 10.0 nb = int(round((hi - lo) / 0.1)) b = np.zeros(N, dtype=int) b[pos] = np.clip(np.floor((lx[pos] - lo) / 0.1).astype(int), 0, nb - 1) cnt = np.bincount(b[tr], minlength=nb) # merge sparse bins towards the middle: map each raw bin to a merged bin id mid = int(np.argmax(np.cumsum(cnt) >= cnt.sum() / 2.0)) mp = np.arange(nb) i = 0 while i < mid: # from the low end upwards j = i tot = cnt[i] while tot < 50 and j + 1 <= mid: j += 1; tot += cnt[j] mp[i:j + 1] = j i = j + 1 i = nb - 1 while i > mid: # from the high end downwards j = i tot = cnt[i] while tot < 50 and j - 1 >= mid: j -= 1; tot += cnt[j] mp[j:i + 1] = j i = j - 1 bm = mp[b] q50, q90, q99 = np.nanpercentile(x[tr], [50, 90, 99]) cls = np.digitize(x, [q50, q90, q99]) # 0 quiet, 1 moderate, 2 active, 3 storm level names = ["quiet (below median)", "moderate (50-90%)", "active (90-99%)", "storm level (top 1%)", "all"] sums_all = np.bincount(bm[tr], weights=ap60[tr], minlength=nb) cnt_all = np.bincount(bm[tr], minlength=nb) def sH(wsel, leave_out): if leave_out is not None: s_ = sums_all - np.bincount(bm[leave_out], weights=ap60[leave_out], minlength=nb) c_ = cnt_all - np.bincount(bm[leave_out], minlength=nb) else: s_, c_ = sums_all, cnt_all with np.errstate(invalid="ignore", divide="ignore"): exp_bin = s_ / c_ out = [] for k in range(5): m_ = wsel if k == 4 else (wsel & (cls == k)) e_ = exp_bin[bm[m_]] okk = ~np.isnan(e_) if okk.sum() < 20: out.append((float("nan"), int(okk.sum()))) else: out.append((float(np.log(ap60[m_][okk].mean() / e_[okk].mean())), int(okk.sum()))) return out H = {} for (a_, b_) in REF: w_ = tr & (year >= a_) & (year <= b_) H["%d-%d" % (a_, b_)] = sH(w_, w_) wt = use & (year >= 2023) & (year <= 2025) Ht = sH(wt, None) res = dict(bins=int(len(set(mp.tolist()))), raw_bins=nb, range_log10=[lo, hi], quantiles=[float(q50), float(q90), float(q99)], train_hours=int(tr.sum()), test_hours=int(wt.sum()), classes={}) log("H-ap60-%s: %d training hours, %d test hours (2023-2025); %d merged bins over log10 %.1f..%.1f; class cuts %.3g, %.3g, %.3g" % (inp, tr.sum(), wt.sum(), res["bins"], lo, hi, q50, q90, q99)) for k in range(5): refv = np.array([H[w][k][0] for w in H]) refv = refv[~np.isnan(refv)] st = Ht[k][0] rank = 1 + int((refv > st).sum()) res["classes"][names[k]] = dict(test=st, hours=Ht[k][1], rank=rank, n=len(refv) + 1, ref_min=float(refv.min()), ref_median=float(np.median(refv)), ref_max=float(refv.max()), ref_sd=float(refv.std(ddof=1)), s_2000_2002=H["2000-2002"][k][0], s_2013_2015=H["2013-2015"][k][0], windows={w: H[w][k][0] for w in H}) log(" %-22s 2023-2025: %+.4f ln (%+.1f%%), %d hours; reference min %+.3f median %+.3f max %+.3f sd %.3f; rank %d of %d; 2000-2002 %+.3f; 2013-2015 %+.3f" % (names[k], st, 100 * (math.exp(st) - 1), Ht[k][1], refv.min(), np.median(refv), refv.max(), refv.std(ddof=1), rank, len(refv) + 1, H["2000-2002"][k][0], H["2013-2015"][k][0])) results["H-ap60-%s" % inp] = res # ---------------------------------------------------------------- scale of the expected effect igrf = oc.read_igrf() b01, b24 = oc.dipole_proxy(2001.0, igrf), oc.dipole_proxy(2024.0, igrf) r = b24 / b01 log("Scale: IGRF-14 dipole proxy 2001.0 %.1f nT, 2024.0 %.1f nT, change %+.2f%%; M^(1/3) %+.2f%%; M^(2/3) %+.2f%%; 1/M %+.2f%%" % (b01, b24, 100 * (r - 1), 100 * (r ** (1 / 3) - 1), 100 * (r ** (2 / 3) - 1), 100 * (1 / r - 1))) results["scale"] = dict(b2001=b01, b2024=b24, change=r - 1) # ---------------------------------------------------------------- outputs def clean(o): if isinstance(o, dict): return {str(k): clean(v) for k, v in o.items()} if isinstance(o, (list, tuple)): return [clean(v) for v in o] if isinstance(o, (np.floating, np.integer)): return o.item() return o with open(os.path.join(OUTDIR, "response_test.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(clean(results), f, indent=1) wcsv("monthly_scores.csv", ["test", "year", "month", "score"], [[t, k[0], k[1], repr(v)] for (t, k), v in sorted(month_scores.items())]) with open(os.path.join(OUTDIR, "response_test_log.txt"), "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(LOG) + "\n")