"""Exposure in 2015 (and the G4 storms of 2014-2019) from GFZ Potsdam's definitive Kp, ap and Ap. Fact-Checked Science ("Our analysis"), 20 November 2026, for the check of Marschollek's AGU26 abstract GH11D-VR9816 ("Age and Sex Differences in Causal Impact of Geomagnetic Ap on Cardiac Arrest Incidence during and after Solar Storms"). Rules: RULES_exposure.txt (fixed before GFZ's file was read). Input (read as data, never executed): Kp_ap_Ap_SN_F107_since_1932.txt from https://kp.gfz.de/app/files/Kp_ap_Ap_SN_F107_since_1932.txt (GFZ Helmholtz Centre for Geosciences, CC BY 4.0; Matzka et al. 2021, doi:10.5880/Kp.0001). Its sunspot-number column (CC BY-NC 4.0) is not read. Run: python3 -I exposure.py Standard library only. Writes ap_daily_2015.csv, kp_3h_2015.csv, storms_2014_2019.csv, exposure_2015.json and chart_ap_2015.json in the output folder, and prints a summary. """ import csv import datetime as dt import json import os import statistics import sys FIRST = dt.date(2014, 1, 1) LAST = dt.date(2019, 12, 31) CREDIT = ("GFZ Helmholtz Centre for Geosciences, Kp_ap_Ap_SN_F107_since_1932.txt (kp.gfz.de), CC BY 4.0; " "Matzka et al. (2021), doi:10.5880/Kp.0001") def thirds(n): """Kp in thirds (n = round(3 Kp)) to Bartels' notation: 23 -> '8-', 24 -> '8o', 25 -> '8+'.""" if n % 3 == 0: return f"{n // 3}o" if n % 3 == 1: return f"{(n - 1) // 3}+" return f"{(n + 1) // 3}-" def glevel(n): """NOAA G level of a three-hour Kp, as NOAA's Planetary K-index page draws it (RULES_exposure.txt).""" if n <= 13: return 0 if n <= 16: return 1 if n <= 19: return 2 if n <= 22: return 3 if n <= 26: return 4 return 5 def read_gfz(path): days = {} with open(path, encoding="utf-8") as f: for line in f: if line.startswith("#") or not line.strip(): continue p = line.split() d = dt.date(int(p[0]), int(p[1]), int(p[2])) if d < FIRST or d > LAST: continue kp = [float(x) for x in p[7:15]] ap = [int(x) for x in p[15:23]] days[d] = {"kp": kp, "ap": ap, "Ap": int(p[23]), "D": int(p[27])} return days def intervals(days): out = [] for d in sorted(days): for i in range(8): kp = days[d]["kp"][i] if kp < 0: raise SystemExit(f"missing Kp on {d} interval {i}") n = round(3 * kp) out.append({"start": dt.datetime(d.year, d.month, d.day, 3 * i), "date": d, "i": i, "kp": kp, "n": n, "ap": days[d]["ap"][i], "G": glevel(n)}) return out def storms(ivs, join_hours=24): g1 = [x for x in ivs if x["G"] >= 1] groups = [] for x in g1: if groups and (x["start"] - groups[-1][-1]["start"]) <= dt.timedelta(hours=join_hours): groups[-1].append(x) else: groups.append([x]) return groups def describe(group, days): peak_n = max(x["n"] for x in group) top_g = max(x["G"] for x in group) first_peak = next(x for x in group if x["n"] == peak_n) first_top = next(x for x in group if x["G"] == top_g) first_g4 = next((x for x in group if x["G"] >= 4), None) first_g3 = next((x for x in group if x["G"] >= 3), None) touched = sorted({x["date"] for x in group}) return { "onset_utc": group[0]["start"].strftime("%Y-%m-%d %H:%M"), "last_g1_interval_utc": group[-1]["start"].strftime("%Y-%m-%d %H:%M"), "n_g1_intervals": len(group), "peak_kp": round(first_peak["kp"], 3), "peak_kp_thirds": thirds(peak_n), "peak_interval_utc": first_peak["start"].strftime("%Y-%m-%d %H:%M"), "n_intervals_at_peak": sum(1 for x in group if x["n"] == peak_n), "max_G": top_g, "first_interval_at_max_G_utc": first_top["start"].strftime("%Y-%m-%d %H:%M"), "first_G4_interval_utc": first_g4["start"].strftime("%Y-%m-%d %H:%M") if first_g4 else None, "storm_day_G4": first_g4["date"].isoformat() if first_g4 else None, "first_G3_interval_utc": first_g3["start"].strftime("%Y-%m-%d %H:%M") if first_g3 else None, "storm_day_G3": first_g3["date"].isoformat() if first_g3 else None, "n_G4_intervals": sum(1 for x in group if x["G"] >= 4), "n_G4_intervals_strict_8o": sum(1 for x in group if x["n"] >= 24), "days_touched": [d.isoformat() for d in touched], "max_daily_Ap_days_touched": max(days[d]["Ap"] for d in touched), "daily_Ap_days_touched": {d.isoformat(): days[d]["Ap"] for d in touched}, "D_flags": sorted({days[d]["D"] for d in touched}), } def window_stats(ap2015, dates2015, start, end, all_means): idx = [i for i, d in enumerate(dates2015) if start <= d <= end] vals = [ap2015[i] for i in idx] rest = [ap2015[i] for i in range(len(ap2015)) if i not in idx] m = statistics.mean(vals) greater = sum(1 for x in all_means if x > m + 1e-12) at_or_above = sum(1 for x in all_means if x >= m - 1e-12) return { "start": start.isoformat(), "end": end.isoformat(), "n_days": len(vals), "mean_Ap": round(m, 3), "median_Ap": statistics.median(vals), "max_Ap": max(vals), "max_Ap_date": dates2015[idx[vals.index(max(vals))]].isoformat(), "days_Ap_ge_30": sum(1 for v in vals if v >= 30), "days_Ap_ge_50": sum(1 for v in vals if v >= 50), "mean_Ap_rest_of_2015": round(statistics.mean(rest), 3), "n_rest": len(rest), "ratio_window_to_rest": round(m / statistics.mean(rest), 3), "share_of_2015_summed_Ap": round(sum(vals) / sum(ap2015), 4), "rank_among_352_windows": greater + 1, "windows_at_or_above": at_or_above, "n_windows": len(all_means), "daily_Ap": {dates2015[i].isoformat(): ap2015[i] for i in idx}, } def main(): src, outdir = sys.argv[1], sys.argv[2] os.makedirs(outdir, exist_ok=True) days = read_gfz(src) n_days = (LAST - FIRST).days + 1 if len(days) != n_days: raise SystemExit(f"expected {n_days} days, found {len(days)}") ivs = intervals(days) groups24 = storms(ivs, 24) groups48 = storms(ivs, 48) desc24 = [describe(g, days) for g in groups24] # ---- 2015 daily series d2015 = [d for d in sorted(days) if d.year == 2015] ap2015 = [days[d]["Ap"] for d in d2015] flags2015 = sorted({days[d]["D"] for d in d2015}) maxn = {d: max(round(3 * k) for k in days[d]["kp"]) for d in d2015} with open(os.path.join(outdir, "ap_daily_2015.csv"), "w", newline="\n", encoding="utf-8") as f: w = csv.writer(f, lineterminator="\n") w.writerow(["date_utc", "Ap", "max_Kp", "max_Kp_thirds", "max_G_level", "gfz_definitive_flag_D"]) for d in d2015: w.writerow([d.isoformat(), days[d]["Ap"], round(maxn[d] / 3, 3), thirds(maxn[d]), glevel(maxn[d]), days[d]["D"]]) with open(os.path.join(outdir, "kp_3h_2015.csv"), "w", newline="\n", encoding="utf-8") as f: w = csv.writer(f, lineterminator="\n") w.writerow(["start_utc", "Kp", "Kp_thirds", "ap", "G_level"]) for x in ivs: if x["date"].year == 2015: w.writerow([x["start"].strftime("%Y-%m-%d %H:%M"), f"{x['kp']:.3f}", thirds(x["n"]), x["ap"], x["G"]]) # ---- Q1, Q2: the storms containing 17 March and 22/23 June 2015 def storm_containing(dates): for g, ds in zip(groups24, desc24): if any(dt.date.fromisoformat(s) in dates for s in ds["days_touched"]): return ds return None q1 = storm_containing({dt.date(2015, 3, 17)}) q2 = storm_containing({dt.date(2015, 6, 22), dt.date(2015, 6, 23)}) q1_daily = {d.isoformat(): days[d]["Ap"] for d in d2015 if dt.date(2015, 3, 10) <= d <= dt.date(2015, 3, 31)} q2_daily = {d.isoformat(): days[d]["Ap"] for d in d2015 if dt.date(2015, 6, 15) <= d <= dt.date(2015, 7, 6)} # ---- Q3: G4+ intervals of 2015, strict reading, G3+ storms of 2015 g4_2015 = [{"start_utc": x["start"].strftime("%Y-%m-%d %H:%M"), "Kp": round(x["kp"], 3), "Kp_thirds": thirds(x["n"]), "G": x["G"], "strict_8o_or_more": x["n"] >= 24} for x in ivs if x["date"].year == 2015 and x["G"] >= 4] storms2015_g3 = [ds for ds in desc24 if ds["onset_utc"][:4] == "2015" and ds["max_G"] >= 3] storms2015_g4 = [ds for ds in desc24 if ds["max_G"] >= 4 and ds["storm_day_G4"][:4] == "2015"] storms2015_g4_strict = [ds for ds in storms2015_g4 if ds["n_G4_intervals_strict_8o"] > 0] # ---- Q4: 14-day windows all_means = [statistics.mean(ap2015[i:i + 14]) for i in range(len(ap2015) - 13)] W = { "A1_from_CME_day": (dt.date(2015, 3, 15), dt.date(2015, 3, 28)), "A2_after_CME_day": (dt.date(2015, 3, 16), dt.date(2015, 3, 29)), "B1_from_storm_day": (dt.date(2015, 3, 17), dt.date(2015, 3, 30)), "B2_after_storm_day": (dt.date(2015, 3, 18), dt.date(2015, 3, 31)), "J1_from_22_June": (dt.date(2015, 6, 22), dt.date(2015, 7, 5)), "J2_from_23_June": (dt.date(2015, 6, 23), dt.date(2015, 7, 6)), } q4 = {k: window_stats(ap2015, d2015, a, b, all_means) for k, (a, b) in W.items()} top_windows = sorted(range(len(all_means)), key=lambda i: -all_means[i])[:12] q4_top = [{"start": d2015[i].isoformat(), "end": d2015[i + 13].isoformat(), "mean_Ap": round(all_means[i], 3)} for i in top_windows] pre = [days[d]["Ap"] for d in d2015 if d <= dt.date(2015, 3, 14)] pre_storms_g3 = [ds for ds in storms2015_g3 if ds["onset_utc"] < "2015-03-15"] year_stats = {"mean_Ap_2015": round(statistics.mean(ap2015), 3), "median_Ap_2015": statistics.median(ap2015), "days_Ap_ge_30_2015": sum(1 for v in ap2015 if v >= 30), "days_Ap_ge_50_2015": sum(1 for v in ap2015 if v >= 50), "top10_days_2015": sorted(({"date": d.isoformat(), "Ap": days[d]["Ap"]} for d in d2015), key=lambda r: (-r["Ap"], r["date"]))[:10], "pre_CME_2015-01-01_to_03-14": {"n_days": len(pre), "mean_Ap": round(statistics.mean(pre), 3), "max_Ap": max(pre), "G3plus_storms": [{"onset_utc": s["onset_utc"], "peak_kp_thirds": s["peak_kp_thirds"], "max_G": s["max_G"], "max_daily_Ap": s["max_daily_Ap_days_touched"]} for s in pre_storms_g3]}} # ---- Q5: storm lists 2014-2019 with open(os.path.join(outdir, "storms_2014_2019.csv"), "w", newline="\n", encoding="utf-8") as f: w = csv.writer(f, lineterminator="\n") w.writerow(["onset_utc", "peak_kp_thirds", "peak_interval_utc", "max_G", "first_G3_interval_utc", "storm_day_G3", "first_G4_interval_utc", "storm_day_G4", "n_G1_intervals", "n_G4_intervals", "n_G4_intervals_strict_8o", "max_daily_Ap", "gfz_D_flags"]) for ds in desc24: if ds["max_G"] >= 3: w.writerow([ds["onset_utc"], ds["peak_kp_thirds"], ds["peak_interval_utc"], ds["max_G"], ds["first_G3_interval_utc"], ds["storm_day_G3"], ds["first_G4_interval_utc"] or "", ds["storm_day_G4"] or "", ds["n_g1_intervals"], ds["n_G4_intervals"], ds["n_G4_intervals_strict_8o"], ds["max_daily_Ap_days_touched"], " ".join(str(x) for x in ds["D_flags"])]) g4_all = [ds for ds in desc24 if ds["max_G"] >= 4] g3_all = [ds for ds in desc24 if ds["max_G"] >= 3] # 48-hour joining sensitivity: does it change membership of the G3+/G4+ storms? def key_set(groups, gmin): return sorted(tuple(x["start"].strftime("%Y-%m-%d %H") for x in g if x["G"] >= gmin) for g in groups if max(x["G"] for x in g) >= gmin) sens48 = {"G4_storms_24h": len(g4_all), "G4_storms_48h": sum(1 for g in groups48 if max(x["G"] for x in g) >= 4), "G3_storms_24h": len(g3_all), "G3_storms_48h": sum(1 for g in groups48 if max(x["G"] for x in g) >= 3), "G4_membership_same": key_set(groups24, 4) == key_set(groups48, 4), "G3_membership_same": key_set(groups24, 3) == key_set(groups48, 3)} if not sens48["G3_membership_same"]: merged = [] for g in groups48: if max(x["G"] for x in g) >= 3: parts = [ds["onset_utc"] for g24, ds in zip(groups24, desc24) if ds["max_G"] >= 3 and g24[0]["start"] >= g[0]["start"] and g24[-1]["start"] <= g[-1]["start"]] if len(parts) > 1: merged.append(parts) sens48["G3_storms_merged_at_48h"] = merged result = { "source": CREDIT, "rules": "RULES_exposure.txt", "days_read": len(days), "definitive_flags_2015": flags2015, "definitive_flags_2014_2019": sorted({v["D"] for v in days.values()}), "Q1_storm_17_March_2015": q1, "Q1_daily_Ap_10_to_31_March": q1_daily, "Q2_storm_22_23_June_2015": q2, "Q2_daily_Ap_15_June_to_6_July": q2_daily, "Q3_G4plus_intervals_2015": g4_2015, "Q3_G4_storms_2015": [{"onset_utc": s["onset_utc"], "storm_day_G4": s["storm_day_G4"], "peak_kp_thirds": s["peak_kp_thirds"], "n_G4_intervals": s["n_G4_intervals"], "n_G4_intervals_strict_8o": s["n_G4_intervals_strict_8o"]} for s in storms2015_g4], "Q3_n_G4_storms_2015": len(storms2015_g4), "Q3_n_G4_storms_2015_strict_8o": len(storms2015_g4_strict), "Q3_G3plus_storms_2015": [{"onset_utc": s["onset_utc"], "peak_kp_thirds": s["peak_kp_thirds"], "peak_interval_utc": s["peak_interval_utc"], "max_G": s["max_G"], "max_daily_Ap": s["max_daily_Ap_days_touched"]} for s in storms2015_g3], "Q4_windows": q4, "Q4_top12_windows_2015": q4_top, "year_2015": year_stats, "Q5_G4_storms_2014_2019": [{"onset_utc": s["onset_utc"], "storm_day_G4": s["storm_day_G4"], "first_G4_interval_utc": s["first_G4_interval_utc"], "peak_kp_thirds": s["peak_kp_thirds"], "max_G": s["max_G"], "n_G4_intervals_strict_8o": s["n_G4_intervals_strict_8o"]} for s in g4_all], "Q5_n_G3plus_storms_2014_2019": len(g3_all), "joining_sensitivity_48h": sens48, } with open(os.path.join(outdir, "exposure_2015.json"), "w", newline="\n", encoding="utf-8") as f: json.dump(result, f, indent=1, ensure_ascii=False) f.write("\n") chart = { "title": "Daily Ap, 2015 (GFZ definitive)", "credit": CREDIT + ". Chart data: Fact-Checked Science.", "dates": [d.isoformat() for d in d2015], "Ap": ap2015, "max_Kp_thirds": [thirds(maxn[d]) for d in d2015], "G4_days": [d.isoformat() for d in d2015 if glevel(maxn[d]) >= 4], "windows": {"abstract_14_days_after_15_March": {"start": "2015-03-16", "end": "2015-03-29", "note": "the 14 days after the CME day (window A2)"}, "J1_from_22_June": {"start": "2015-06-22", "end": "2015-07-05"}}, "mean_Ap_2015": year_stats["mean_Ap_2015"], } with open(os.path.join(outdir, "chart_ap_2015.json"), "w", newline="\n", encoding="utf-8") as f: json.dump(chart, f, ensure_ascii=False, separators=(",", ":")) f.write("\n") # ---- summary print("days read", len(days), "flags 2014-2019", result["definitive_flags_2014_2019"]) for name, s in (("Q1 17 March", q1), ("Q2 22-23 June", q2)): print(name, {k: s[k] for k in ("onset_utc", "first_G4_interval_utc", "peak_kp_thirds", "peak_interval_utc", "n_intervals_at_peak", "max_G", "n_g1_intervals", "n_G4_intervals", "n_G4_intervals_strict_8o", "daily_Ap_days_touched")}) print("Q1 daily Ap 10-31 March", q1_daily) print("Q2 daily Ap 15 June-6 July", q2_daily) print("Q3 G4+ intervals 2015:") for r in g4_2015: print(" ", r) print("Q3 n G4 storms 2015:", len(storms2015_g4), " strict 8o:", len(storms2015_g4_strict)) print("Q3 G3+ storms 2015:") for s in result["Q3_G3plus_storms_2015"]: print(" ", s) print("Q4 windows:") for k, v in q4.items(): print(" ", k, {kk: v[kk] for kk in v if kk != "daily_Ap"}) print("Q4 top 12 windows:", q4_top) print("2015:", {k: v for k, v in year_stats.items()}) print("Q5 G4 storms 2014-2019:") for s in result["Q5_G4_storms_2014_2019"]: print(" ", s) print("Q5 n G3+ storms 2014-2019:", len(g3_all)) print("48h sensitivity:", sens48) if __name__ == "__main__": main()