#!/usr/bin/env python3 """Analysis (a) for march-2023-storm: was the storm of 23-24 March 2023 the strongest in six years? Fact-Checked Science, "Our analysis". Standard library only. Follows RULES_rank.txt (pre-registered). Run: python3 -I -X utf8 storm_rank.py RULES_rank.txt GFZ_FILE KYOTO_FOLDER ALERTS_FOLDER OUT_FOLDER [UNTIL] UNTIL (YYYY-MM-DD, optional) ignores GFZ's rows after that day, so that a later copy of the growing file gives the numbers of an earlier run. Our run of 11 November 2026 read the file to its end, 10 November. Reads, as data only: GFZ_FILE Kp_ap_Ap_SN_F107_since_1932.txt (GFZ, CC BY 4.0) KYOTO_FOLDER dst_final_YYYYMM.html / dst_provisional_YYYYMM.html (WDC Kyoto monthly pages; no real-time month) ALERTS_FOLDER alerts_YYYYMM.html (NOAA SWPC's monthly alert archive) Writes OUT_FOLDER/storm_rank.json and storm_rank.log (with SHA-256 of the rules and of every input), and OUT_FOLDER/storms-2017-2026.csv, the list of storms behind the page's chart (added for the page; no test). Implementation details fixed before the first run (RULES_rank.txt, amendment 2): - a storm belongs to a window when its peak lies inside it (Kp storms: the start of the first interval at the storm's highest Kp; Dst storms: the hour of the minimum); - "the storm" among Kp storms is the one holding 2023-03-24 03:00 UT; among Dst storms the one holding the minimum of 23-25 March 2023; - NOAA alerts are counted once per K level and synoptic period (a corrected alert is not a second one). """ import datetime as dt import glob import hashlib import html import json import os import re import sys UTC = dt.timezone.utc EPS = 1e-6 def sha(path): with open(path, "rb") as f: return hashlib.sha256(f.read()).hexdigest() def kpname(k): i = int(round(k * 3)) base = (i + 1) // 3 third = i - 3 * base return f"{base}{'-' if third == -1 else '+' if third == 1 else 'o'}" # ---------- readers ---------- def read_gfz(path, since=dt.datetime(2017, 1, 1), until=None): """Three-hour series [(t_start, kp, ap, dflag)], and daily {date: (Ap, dflag)}, from `since` on (and to `until`, if given). No window of RULES_rank.txt begins before 23 March 2017.""" three, daily = [], {} for line in open(path, encoding="utf-8", errors="replace"): if line.startswith("#") or not line.strip(): continue f = line.split() day = dt.datetime(int(f[0]), int(f[1]), int(f[2])) if day < since or (until is not None and day > until): continue kps = [float(x) for x in f[7:15]] aps = [int(x) for x in f[15:23]] Ap = int(f[23]) D = int(f[-1]) for i in range(8): if kps[i] < 0 or aps[i] < 0: continue three.append((day + dt.timedelta(hours=3 * i), kps[i], aps[i], D)) if Ap >= 0: daily[day.date()] = (Ap, D) return three, daily MONTHS = {m.upper(): i for i, m in enumerate( ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], 1)} def read_kyoto_month(path): """{t_start_of_hour: Dst} from one monthly page. Column n is the hour ending n:00 UT.""" raw = open(path, encoding="utf-8", errors="replace").read() txt = html.unescape(re.sub(r"<[^>]+>", "", raw)) m = re.search(r"\n\s*([A-Z]+)\s+(\d{4})\s*\n", txt) year, month = int(m.group(2)), MONTHS[m.group(1)] kind = "final" if "(FINAL)" in txt.upper() or "FINAL)" in txt.upper() else ( "provisional" if "PROVISIONAL" in txt.upper() else ("realtime" if "REAL-TIME" in txt.upper() or "QUICKLOOK" in txt.upper() else "unknown")) out = {} for line in txt.splitlines(): mm = re.match(r"^([ \d]\d) ", line) if not mm: continue day = int(mm.group(1)) # fixed width: dd, space, 8 x I4, space, 8 x I4, space, 8 x I4 vals = [] body = line[3:] pos = 0 ok = True for g in range(3): for k in range(8): cell = body[pos:pos + 4] pos += 4 try: vals.append(int(cell)) except ValueError: ok = False pos += 1 # independent parse by regular expression, as a check alt = [int(v) for v in re.findall(r"-?\d+", body.replace("-", " -"))] if not ok or len(vals) != 24: raise SystemExit(f"bad row in {path}: {line!r}") if alt[:24] != vals: raise SystemExit(f"fixed-width and regex parses differ in {path}: {line!r}") for n, v in enumerate(vals): if v in (9999, 99999): continue out[dt.datetime(year, month, day) + dt.timedelta(hours=n)] = v return (year, month), kind, out def read_kyoto(folder): dst, status = {}, {} for p in sorted(glob.glob(os.path.join(folder, "dst_*_*.html"))): fn = os.path.basename(p) kind_fn = fn.split("_")[1] if kind_fn not in ("final", "provisional"): raise SystemExit("refusing to read a non-final, non-provisional Kyoto file: " + fn) (y, mth), kind_txt, vals = read_kyoto_month(p) if kind_txt != kind_fn: raise SystemExit(f"{fn}: file name says {kind_fn}, page says {kind_txt}") ndays = (dt.date(y + (mth == 12), mth % 12 + 1, 1) - dt.date(y, mth, 1)).days if len(vals) != 24 * ndays: raise SystemExit(f"{fn}: {len(vals)} hours, expected {24 * ndays}") status[(y, mth)] = kind_fn dst.update(vals) return dst, status MON3 = {m: i for i, m in enumerate(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], 1)} def read_alerts(folder): """NOAA alerts of an observed K-index of 7, 8 or 9: [(threshold_time, K, synoptic_period_start, file)].""" seen, out = set(), [] for p in sorted(glob.glob(os.path.join(folder, "alerts_*.html"))): raw = open(p, encoding="utf-8", errors="replace").read() txt = html.unescape(re.sub(r"<[^>]+>", "\n", raw)) for b in re.split(r"(?=Space Weather Message Code:)", txt): mc = re.search(r"Space Weather Message Code:\s*(\w+)", b) if not mc or not re.fullmatch(r"ALTK0[789]", mc.group(1)): continue if re.search(r"\bCANCEL", b): continue K = int(mc.group(1)[-1]) mt = re.search(r"Threshold Reached:\s*(\d{4}) (\w{3}) (\d{1,2}) (\d{2})(\d{2}) UTC", b) ms = re.search(r"Synoptic Period:\s*(\d{2})(\d{2})-(\d{4}) UTC", b) if not mt: continue t = dt.datetime(int(mt.group(1)), MON3[mt.group(2)], int(mt.group(3)), int(mt.group(4)), int(mt.group(5))) if ms: syn = dt.datetime(t.year, t.month, t.day, int(ms.group(1))) # a threshold time just after midnight can belong to the previous day's last period if syn - t > dt.timedelta(hours=12): syn -= dt.timedelta(days=1) else: syn = t.replace(minute=0) syn = syn.replace(hour=syn.hour - syn.hour % 3) key = (K, syn) if key in seen: continue seen.add(key) out.append((t, K, syn, os.path.basename(p))) out.sort() return out # ---------- storms ---------- def kp_storms(three, thr, join_h): """Storms: intervals with Kp >= thr, joined when starts are join_h hours or less apart.""" storms, cur = [], None for t, kp, ap, D in three: if kp >= thr - EPS: if cur and (t - cur["last"]) <= dt.timedelta(hours=join_h): cur["items"].append((t, kp, ap, D)) cur["last"] = t else: cur = {"items": [(t, kp, ap, D)], "last": t} storms.append(cur) return storms def dst_storms(dst, thr, join_h): storms, cur = [], None for t in sorted(dst): v = dst[t] if v <= thr: if cur and (t - cur["last"]) <= dt.timedelta(hours=join_h): cur["items"].append((t, v)) cur["last"] = t else: cur = {"items": [(t, v)], "last": t} storms.append(cur) return storms def running_ap(three): """24-hour running means of ap over eight consecutive three-hour values: [(t_start, mean)].""" out = [] for i in range(len(three) - 7): w = three[i:i + 8] if (w[7][0] - w[0][0]) != dt.timedelta(hours=21): continue # a gap in the series out.append((w[0][0], sum(x[2] for x in w) / 8.0)) return out def iso(t): return t.strftime("%Y-%m-%d %H:%M") def main(): rules, gfz_path, kyoto_dir, alerts_dir, outdir = sys.argv[1:6] until = dt.datetime.strptime(sys.argv[6], "%Y-%m-%d") if len(sys.argv) > 6 else None log = [] def say(*a): s = " ".join(str(x) for x in a) print(s) log.append(s) say("storm_rank.py run at", dt.datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")) say("rules ", sha(rules), os.path.basename(rules)) say("GFZ ", sha(gfz_path), os.path.basename(gfz_path)) kfiles = sorted(glob.glob(os.path.join(kyoto_dir, "dst_*_*.html"))) h = hashlib.sha256() for p in kfiles: h.update(os.path.basename(p).encode() + b" " + sha(p).encode() + b"\n") say("Kyoto ", h.hexdigest(), f"(SHA-256 of the list of {len(kfiles)} file names and their SHA-256)") afiles = sorted(glob.glob(os.path.join(alerts_dir, "alerts_*.html"))) h = hashlib.sha256() for p in afiles: h.update(os.path.basename(p).encode() + b" " + sha(p).encode() + b"\n") say("alerts ", h.hexdigest(), f"(the same, {len(afiles)} files)") three, daily = read_gfz(gfz_path, until=until) if until is not None: say("GFZ rows after", until.date().isoformat(), "ignored") dst, status = read_kyoto(kyoto_dir) alerts = read_alerts(alerts_dir) run = running_ap(three) last_def = max(t for t, kp, ap, D in three if D >= 1) last_pre = max(t for t, kp, ap, D in three) first_dst, last_dst = min(dst), max(dst) fin = sorted(k for k, v in status.items() if v == "final") pro = sorted(k for k, v in status.items() if v == "provisional") say(f"GFZ Kp: last definitive interval starts {iso(last_def)}; last value in file {iso(last_pre)}") say(f"Kyoto Dst read: {iso(first_dst)} to {iso(last_dst)}; final months {fin[0]}..{fin[-1]} ({len(fin)}), " f"provisional {pro[0]}..{pro[-1]} ({len(pro)})") say(f"NOAA alerts (K>=7) read: {len(alerts)} distinct level-and-period alerts, {alerts[0][0].date()} to {alerts[-1][0].date()}") S0, S1 = dt.datetime(2023, 3, 23), dt.datetime(2023, 3, 26) W = { "W6": (dt.datetime(2017, 3, 23), S0), "W5": (dt.datetime(2017, 9, 10), S0), "C25a": (dt.datetime(2019, 12, 1), S0), } WP = { "WP1": (dt.datetime(2017, 6, 24), dt.datetime(2023, 6, 24)), "WP2": (dt.datetime(2018, 2, 1), dt.datetime(2024, 2, 1)), } C25B_KP_DEF = (dt.datetime(2019, 12, 1), last_def + dt.timedelta(hours=3)) C25B_KP_ALL = (dt.datetime(2019, 12, 1), last_pre + dt.timedelta(hours=3)) C25B_DST = (dt.datetime(2019, 12, 1), last_dst + dt.timedelta(hours=1)) out = {"what": "Rank of the storm of 23-24 March 2023 (factchecked.science, Our analysis; RULES_rank.txt)", "terms": "Dst: World Data Center for Geomagnetism, Kyoto, final and provisional values only, for scientific, " "non-commercial use with acknowledgement of the WDC and the observatories. Kp, ap, Ap: GFZ, CC BY 4.0.", "kyoto_status": {"final": [f"{fin[0][0]}-{fin[0][1]:02d}", f"{fin[-1][0]}-{fin[-1][1]:02d}"], "provisional": [f"{pro[0][0]}-{pro[0][1]:02d}", f"{pro[-1][0]}-{pro[-1][1]:02d}"]}, "kp_last_definitive": iso(last_def), "kp_last_in_file": iso(last_pre)} # ---- the storm's own values def ext(lo, hi, skip=None): """Extremes inside [lo, hi), leaving out [skip0, skip1) if given.""" def inside(t): return lo <= t < hi and not (skip and skip[0] <= t < skip[1]) k = [(kp, t, ap) for t, kp, ap, D in three if inside(t)] mk = max(k) if k else None kmax = mk[0] if mk else None kfirst = min(t for kp, t, ap in k if abs(kp - kmax) < EPS) if mk else None apmax = max(ap for kp, t, ap in k) if k else None d = [(v[0], day) for day, v in daily.items() if inside(dt.datetime(day.year, day.month, day.day))] dmax = max(d) if d else None r = [(mean, t) for t, mean in run if inside(t) and inside(t + dt.timedelta(hours=21)) and not (skip and t < skip[1] and t + dt.timedelta(hours=24) > skip[0])] rmax = max(r) if r else None x = [(v, t) for t, v in dst.items() if inside(t)] xmin = min(x) if x else None al = [(K, t) for t, K, syn, fn in alerts if inside(syn)] amax = max(al)[0] if al else None adates = sorted({syn.date().isoformat() for t, K, syn, fn in alerts if inside(syn) and K == amax}) if al else [] return {"M1_kp": kmax, "M1_kp_name": kpname(kmax) if kmax is not None else None, "M1_first_at": iso(kfirst) if kfirst else None, "ap_peak": apmax, "M2_Ap": dmax[0] if dmax else None, "M2_day": dmax[1].isoformat() if dmax else None, "M3_ap24": round(rmax[0], 3) if rmax else None, "M3_from": iso(rmax[1]) if rmax else None, "M4_dst": xmin[0] if xmin else None, "M4_hour_start": iso(xmin[1]) if xmin else None, "M5_K": amax, "M5_days": adates} storm = ext(S0, S1) out["storm"] = storm say("\nTHE STORM (2023-03-23 00:00 to 2023-03-26 00:00 UT)") say(json.dumps(storm)) kp_rows = [(iso(t), kpname(kp), ap) for t, kp, ap, D in three if S0 <= t < S1] out["storm_kp_rows"] = kp_rows say("three-hour Kp, ap:", "; ".join(f"{a[5:]} {b} {c}" for a, b, c in kp_rows)) out["storm_daily_Ap"] = {d.isoformat(): daily[d][0] for d in (dt.date(2023, 3, 23), dt.date(2023, 3, 24), dt.date(2023, 3, 25))} say("daily Ap:", out["storm_daily_Ap"]) say("NOAA alerts in the storm:", "; ".join(f"K{K} {iso(t)} (period {syn.strftime('%d %H')}h)" for t, K, syn, fn in alerts if S0 <= syn < S1)) def compare(a, b, lower_is_stronger=False): """Is the window's extreme (a) weaker than, equal to or stronger than the storm's (b)?""" if a is None: return "no data" if abs(a - b) < EPS: return "equal" stronger = a < b if lower_is_stronger else a > b return "stronger" if stronger else "weaker" def verdict(c): return {"weaker": "holds", "equal": "ties", "stronger": "fails", "no data": "no data"}[c] say("\nDIRECT TEST") out["direct"] = {} for name, (lo, hi) in W.items(): e = ext(lo, hi) res = {"window": [iso(lo), iso(hi)], "extremes": e, "against_storm": { "M1": compare(e["M1_kp"], storm["M1_kp"]), "M2": compare(e["M2_Ap"], storm["M2_Ap"]), "M3": compare(e["M3_ap24"], storm["M3_ap24"]), "M4": compare(e["M4_dst"], storm["M4_dst"], True), "M5": compare(e["M5_K"], storm["M5_K"])}} res["ranking"] = {k: verdict(v) for k, v in res["against_storm"].items()} out["direct"][name] = res say(f"{name} {iso(lo)} .. {iso(hi)}") say(" extremes:", json.dumps(e)) say(" window's extreme against the storm:", res["against_storm"]) say(" the ranking:", res["ranking"]) for name, (lo, hi) in WP.items(): e = ext(lo, hi, skip=(S0, S1)) res = {"window": [iso(lo), iso(hi)], "extremes_outside_the_storm": e, "against_storm": { "M1": compare(e["M1_kp"], storm["M1_kp"]), "M2": compare(e["M2_Ap"], storm["M2_Ap"]), "M3": compare(e["M3_ap24"], storm["M3_ap24"]), "M4": compare(e["M4_dst"], storm["M4_dst"], True)}} res["ranking"] = {k: verdict(v) for k, v in res["against_storm"].items()} out["direct"][name] = res say(f"{name} {iso(lo)} .. {iso(hi)} (the storm's 72 h left out)") say(" extremes:", json.dumps(e)) say(" against the storm:", res["against_storm"], "->", res["ranking"]) # ---- rank among storms def describe_kp(st): items = st["items"] kmax = max(k for t, k, a, D in items) tpk = min(t for t, k, a, D in items if abs(k - kmax) < EPS) t0, t1 = items[0][0], items[-1][0] + dt.timedelta(hours=3) days = set() d = t0.date() while d <= (t1 - dt.timedelta(seconds=1)).date(): days.add(d) d += dt.timedelta(days=1) Apmax = max(daily[d][0] for d in days if d in daily) r = [mean for t, mean in run if t < t1 and t + dt.timedelta(hours=24) > t0] return {"start": iso(t0), "end": iso(t1), "peak_at": iso(tpk), "_peak": tpk, "kp": kmax, "kp_name": kpname(kmax), "ap_peak": max(a for t, k, a, D in items), "Ap": Apmax, "ap24": round(max(r), 3) if r else None, "preliminary": any(D == 0 for t, k, a, D in items)} def describe_dst(st): items = st["items"] vmin = min(v for t, v in items) tmin = min(t for t, v in items if v == vmin) return {"start": iso(items[0][0]), "end": iso(items[-1][0] + dt.timedelta(hours=1)), "min": vmin, "min_hour_start": iso(tmin), "_peak": tmin} def rank(values, mine, lower_is_stronger=False): if lower_is_stronger: better = sum(1 for v in values if v < mine - EPS) else: better = sum(1 for v in values if v > mine + EPS) ties = sum(1 for v in values if abs(v - mine) < EPS) - 1 return better + 1, ties out["ranks"] = {} for join_h in (24, 48): ks = [describe_kp(s) for s in kp_storms(three, 14.0 / 3.0, join_h)] ds = [describe_dst(s) for s in dst_storms(dst, -50, join_h)] mine_k = [s for s in ks if s["start"] <= "2023-03-24 03:00" < s["end"]] mine_d = [s for s in ds if S0 <= s["_peak"] < S1] assert len(mine_k) == 1 and len(mine_d) == 1, (mine_k, mine_d) mk, md = mine_k[0], mine_d[0] say(f"\nRANK AMONG STORMS, joining at {join_h} h") say(" the storm as a Kp storm:", {k: v for k, v in mk.items() if k != "_peak"}) say(" the storm as a Dst storm:", {k: v for k, v in md.items() if k != "_peak"}) res = {"storm_kp": {k: v for k, v in mk.items() if k != "_peak"}, "storm_dst": {k: v for k, v in md.items() if k != "_peak"}, "windows": {}} wins = {"W6": (W["W6"][0], S1), "W5": (W["W5"][0], S1), "C25a": (W["C25a"][0], S1), "C25b_definitive": (C25B_KP_DEF[0], C25B_KP_DEF[1]), "C25b_with_preliminary": (C25B_KP_ALL[0], C25B_KP_ALL[1])} for wname, (lo, hi) in wins.items(): kin = [s for s in ks if lo <= s["_peak"] < hi] hi_d = hi if not wname.startswith("C25b") else C25B_DST[1] din = [s for s in ds if lo <= s["_peak"] < hi_d] r1 = rank([s["kp"] for s in kin], mk["kp"]) r2 = rank([s["Ap"] for s in kin], mk["Ap"]) r3 = rank([s["ap24"] for s in kin if s["ap24"] is not None], mk["ap24"]) r4 = rank([s["min"] for s in din], md["min"], True) atleast_k = sorted([s for s in kin if s["kp"] >= mk["kp"] - EPS and s is not mk], key=lambda s: (-s["kp"], s["start"])) atleast_ap24 = sorted([s for s in kin if s["ap24"] is not None and s["ap24"] >= mk["ap24"] - EPS and s is not mk], key=lambda s: -s["ap24"]) atleast_Ap = sorted([s for s in kin if s["Ap"] >= mk["Ap"] and s is not mk], key=lambda s: -s["Ap"]) atleast_d = sorted([s for s in din if s["min"] <= md["min"] and s is not md], key=lambda s: s["min"]) n_g3 = sum(1 for s in kin if s["kp"] >= 20.0 / 3.0 - EPS) n_100 = sum(1 for s in din if s["min"] <= -100) wres = {"window": [iso(lo), iso(hi)], "dst_window_end": iso(hi_d), "N_kp_storms": len(kin), "N_dst_storms": len(din), "N_kp_G3": n_g3, "N_dst_100": n_100, "rank_M1": {"rank": r1[0], "tied_with": r1[1]}, "rank_M2": {"rank": r2[0], "tied_with": r2[1]}, "rank_M3": {"rank": r3[0], "tied_with": r3[1]}, "rank_M4": {"rank": r4[0], "tied_with": r4[1]}, "kp_equal_or_more": [{k: v for k, v in s.items() if k != "_peak"} for s in atleast_k], "Ap_equal_or_more": [{k: v for k, v in s.items() if k != "_peak"} for s in atleast_Ap], "ap24_equal_or_more": [{k: v for k, v in s.items() if k != "_peak"} for s in atleast_ap24], "dst_equal_or_deeper": [{k: v for k, v in s.items() if k != "_peak"} for s in atleast_d]} res["windows"][wname] = wres say(f" {wname} {iso(lo)} .. {iso(hi)} (Dst to {iso(hi_d)}): Kp storms {len(kin)} ({n_g3} at G3+), " f"Dst storms {len(din)} ({n_100} at -100 nT or below)") say(f" rank by peak Kp {r1[0]} (tied with {r1[1]}); by daily Ap {r2[0]} (tied {r2[1]}); " f"by 24-h ap {r3[0]} (tied {r3[1]}); by lowest Dst {r4[0]} (tied {r4[1]})") say(" Kp equal or more:", "; ".join(f"{s['peak_at'][:10]} {s['kp_name']}{' (prelim.)' if s['preliminary'] else ''}" for s in atleast_k) or "none") say(" daily Ap equal or more:", "; ".join(f"{s['peak_at'][:10]} {s['Ap']}" for s in atleast_Ap) or "none") say(" 24-h ap equal or more:", "; ".join(f"{s['peak_at'][:10]} {s['ap24']}" for s in atleast_ap24) or "none") say(" Dst equal or deeper:", "; ".join(f"{s['min_hour_start'][:13]}h {s['min']}" for s in atleast_d) or "none") out["ranks"][f"join_{join_h}h"] = res # the storms behind the page's chart (24-hour joining): every Kp storm at G3 or more and every Dst storm # at -100 nT or below whose peak falls on or after 23 March 2017. Added for the page; it carries no test. ks = [describe_kp(s) for s in kp_storms(three, 14.0 / 3.0, 24)] ds = [describe_dst(s) for s in dst_storms(dst, -50, 24)] lo0 = W["W6"][0] rows_k = [s for s in ks if s["_peak"] >= lo0 and s["kp"] >= 20.0 / 3.0 - EPS] rows_d = [s for s in ds if s["_peak"] >= lo0 and s["min"] <= -100] out["storms_since_2017"] = { "kp_storms_G3_or_more": [{"peak_at": s["peak_at"], "kp": round(s["kp"], 3), "kp_name": s["kp_name"], "ap_peak": s["ap_peak"], "Ap": s["Ap"], "ap24": s["ap24"], "preliminary": s["preliminary"]} for s in rows_k], "dst_storms_minus100_or_below": [{"min_hour_start": s["min_hour_start"], "min": s["min"], "status": status[(s["_peak"].year, s["_peak"].month)]} for s in rows_d]} csv_lines = [ "# Storms from 23 March 2017, joined at 24 hours (RULES_rank.txt). Fact-Checked Science, our analysis.", "# Kp, ap, Ap: GFZ Helmholtz Centre for Geosciences, CC BY 4.0 (Matzka et al. 2021, doi:10.5880/Kp.0001).", "# Dst: World Data Center for Geomagnetism, Kyoto (doi:10.17593/14515-74000), final and provisional values only,", "# for scientific, non-commercial use, with acknowledgement of the WDC and of the observatories that supply the data.", "kind,peak_or_minimum_start_UT,value,name_or_status,daily_Ap,ap_24h,kp_preliminary"] for s in rows_k: csv_lines.append(f"Kp storm (G3 or more),{s['peak_at']},{s['kp']:.3f},{s['kp_name']},{s['Ap']},{s['ap24']}," f"{'yes' if s['preliminary'] else 'no'}") for s in rows_d: csv_lines.append(f"Dst storm (-100 nT or below),{s['min_hour_start']},{s['min']}," f"{status[(s['_peak'].year, s['_peak'].month)]},,,") with open(os.path.join(outdir, "storms-2017-2026.csv"), "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(csv_lines) + "\n") say("") say(f"storms-2017-2026.csv: {len(rows_k)} Kp storms at G3 or more, {len(rows_d)} Dst storms at -100 nT or below") # NOAA's own alerts in W6 lo, hi = W["W6"] days8 = sorted({syn.date().isoformat() for t, K, syn, fn in alerts if lo <= syn < hi and K >= 8}) days7 = sorted({syn.date().isoformat() for t, K, syn, fn in alerts if lo <= syn < hi and K >= 7}) out["noaa_alert_days_W6"] = {"K8_or_more": days8, "K7_or_more": days7} say("\nNOAA's alerts in W6: days with K of 8 or more:", days8) say("NOAA's alerts in W6: days with K of 7 or more:", days7) with open(os.path.join(outdir, "storm_rank.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=1, ensure_ascii=False) f.write("\n") with open(os.path.join(outdir, "storm_rank.log"), "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(log) + "\n") if __name__ == "__main__": main()