#!/usr/bin/env python3
"""Our ranks, data checks and re-run on factchecked.science/may-2024-weak-icme/ ("Our analysis"). The checks on the copied rows use
columns we don't host, so they are not here.
Usage: python3 -I may2024_numbers.py [DATA_FOLDER]
It needs Python 3.10 or later with numpy and pandas. It downloads what it lacks into DATA_FOLDER (default: a folder
may2024_data beside this script), about 105 MB, reads everything as data, and writes three files beside this script:
may2024-numbers.json, may2024-storms.csv and may2024-chart-series.json.
WHAT THE DEFINITIONS ARE. We could read only the abstract of Balan et al. (2026, JGR Space Physics, doi:10.1029/2026JA035527).
So every definition of dIEFy, "front" and "body" below is OURS, a stated stand-in, and the paper's may differ:
IEFy = -|Vx| * Bz * 1e-3 mV/m (Vx in km/s, Bz GSM in nT): positive when Bz is southward.
front = the step in 1-min |B| at the monitor, on its own clock, found near Richardson and Cane's disturbance time;
in OMNI, the step in flow pressure near that time. Then moved to the earliest minute at half the step.
dIEFy = A: mean of the 10 min after the front minus mean of the 10 min before. Also B 5 min, C 30 min, D 60 min, E the
highest 5-min running mean in the first 30 min minus the 30 min before, F adjacent 5-min blocks on OMNI's grid.
A window with under 50% valid minutes gives no value.
body = I: mean IEFy from the front to the SYM-H minimum. J: over the 6 h after the front. G: front to the end of
Richardson and Cane's ICME. H: Richardson and Cane's ICME alone.
dV x Bz = one more stand-in, after the group's earlier quantity (Balan et al. 2017, doi:10.1002/2016JA023853, abstract only):
mean speed of the 10 min after the front minus that of the 10 min before, times the mean Bz GSM of the 10 min after,
sign flipped so that southward is positive, in mV/m. The form is ours.
These rules grew in stages, and most of the stages came after seeing the data. See RULES_before_running.txt,
RULES_addendum_after_availability.txt, RULES_amendment_stage3.txt and rules_sha256.txt, hosted beside this script.
THE SPEEDS OF 2001 AND 2003. ACE's 64-s plasma data stop before these shocks. raj2025-ace-speeds-transcribed.csv holds ACE's
about 33-minute speeds as listed in Raj (2025), Zenodo doi:10.5281/zenodo.17440621, CC BY 4.0, a data set by one of the paper's
authors. An AI page reader copied the rows. They were not parsed and could not be checked against the files themselves; one 2003
row is missing and 14 are fitted speeds, as the CSV's header says. If you can reach Zenodo, compare them.
REVISED INTENSITY. revised() is a simplified form of Manu et al.'s (2024) rule: the largest initial-phase peak only.
second_peak() is our reading of their criterion 5, which can pick a later peak instead. "Same subtraction" on hourly Dst is our
arithmetic; hourly means hide short peaks, so it is rough.
CREDIT AND TERMS. OMNI: J. H. King and N. E. Papitashvili, NASA/GSFC. CDAWeb: NASA/GSFC SPDF; ACE MAG and SWEPAM, Wind MFI and
SWE, and MIT's IMP 8 plasma teams. Dst and SYM-H: World Data Center for Geomagnetism, Kyoto, and the observatories that supply
it, doi:10.17593/14515-74000 and doi:10.14989/267216, for scientific use and no commercial use, a condition that carries over
to this script's outputs. Richardson and Cane's ICME list, doi:10.7910/DVN/C2MHTH.
"""
import itertools
import json
import os
import re
import sys
import time
import urllib.error
import urllib.request
import numpy as np
import pandas as pd
HERE = os.path.dirname(os.path.abspath(__file__))
UA = "factchecked-research/1.0"
MIN = pd.Timedelta(minutes=1)
HOUR = pd.Timedelta(hours=1)
SPDF = "https://spdf.gsfc.nasa.gov/pub/data/omni/high_res_omni/monthly_1min/"
CDAWEB = "https://cdaweb.gsfc.nasa.gov/hapi/data"
KYOTO = "https://wdc.kugi.kyoto-u.ac.jp/hapi/data"
RC_URL = "https://izw1.caltech.edu/ACE/ASC/DATA/level3/icmetable2.htm"
# Storms with hourly Dst at or below -250 nT since 1981 (Kyoto): month, time of the Dst minimum (bin centre), Dst minimum.
STORMS_1981 = [
("1981-04-13 06:29", -311), ("1982-07-14 01:29", -325), ("1982-09-06 11:29", -289), ("1986-02-09 00:29", -307),
("1989-03-14 01:29", -589), ("1989-09-19 04:29", -255), ("1989-10-21 16:29", -268), ("1989-11-17 22:29", -266),
("1990-04-10 18:29", -281), ("1991-03-25 00:29", -298), ("1991-10-29 07:29", -254), ("1991-11-09 01:29", -354),
("1992-05-10 14:29", -288), ("2000-04-07 00:29", -292), ("2000-07-16 00:29", -300), ("2001-03-31 08:29", -387),
("2001-04-11 23:29", -271), ("2001-11-06 06:29", -292), ("2003-10-30 00:29", -353), ("2003-10-30 22:29", -383),
("2003-11-20 20:29", -422), ("2004-11-08 06:29", -374), ("2024-05-11 02:29", -406), ("2024-10-11 01:29", -333)]
# The re-run's events: key, file tags, R&C disturbance time, flagged "(A)" (time at ACE), R&C ICME start and end, SYM-H minimum time,
# Dst minimum, outage label as the abstract has it, monitor.
EVENTS = [
("2000-04-06", ["2000apr"], "2000-04-06 16:39", False, "2000-04-07 06:00", "2000-04-08 06:00", "2000-04-07 00:09", -292, 0, "ACE"),
("2000-07-15", [], "2000-07-15 14:37", False, "2000-07-15 19:00", "2000-07-17 08:00", "2000-07-15 21:54", -300, 0, "OMNI"),
("2001-03-31", ["2001mar"], "2001-03-31 00:52", False, "2001-03-31 05:00", "2001-03-31 22:00", "2001-03-31 08:06", -387, 0, "ACE"),
("2001-04-11", ["2001apr"], "2001-04-11 13:43", False, "2001-04-11 22:00", "2001-04-13 07:00", "2001-04-11 23:57", -271, 0, "ACE"),
("2001-11-06", ["2001nov", "2001nov2"], "2001-11-06 01:52", False, "2001-11-06 12:00", "2001-11-09 03:00", "2001-11-06 04:06", -292, 1, "ACE+rows"),
("2003-10-29", ["2003oct", "2003nov2"], "2003-10-29 06:11", False, "2003-10-29 11:00", "2003-10-30 03:00", "2003-10-30 01:48", -353, 0, "ACE+rows"),
("2003-10-30", ["2003oct", "2003nov2"], "2003-10-30 16:19", True, "2003-10-31 02:00", "2003-11-02 00:00", "2003-10-30 22:55", -383, 1, "ACE+rows"),
("2003-11-20", ["2003nov"], "2003-11-20 08:03", False, "2003-11-20 10:00", "2003-11-21 08:00", "2003-11-20 18:17", -422, 0, "ACE"),
("2004-11-07", ["2004nov"], "2004-11-07 18:27", False, "2004-11-07 22:00", "2004-11-09 10:00", "2004-11-08 05:55", -374, 0, "ACE"),
("2024-05-10", ["2024may", "2024may2"], "2024-05-10 17:05", False, "2024-05-10 20:00", "2024-05-12 15:00", "2024-05-11 02:14", -406, 0, "ACE"),
("2024-10-10", [], "2024-10-10 15:14", False, "2024-10-10 22:00", "2024-10-12 03:00", "2024-10-10 23:14", -333, 0, "OMNI"),
]
WINDOWS = {"2000apr": ("2000-04-06T00:00:00Z", "2000-04-08T12:00:00Z"), "2001mar": ("2001-03-30T12:00:00Z", "2001-04-01T06:00:00Z"),
"2001apr": ("2001-04-11T00:00:00Z", "2001-04-13T12:00:00Z"), "2001nov": ("2001-11-05T18:00:00Z", "2001-11-06T12:00:00Z"),
"2001nov2": ("2001-11-06T12:00:00Z", "2001-11-09T06:00:00Z"), "2003oct": ("2003-10-29T00:00:00Z", "2003-10-31T12:00:00Z"),
"2003nov2": ("2003-10-31T12:00:00Z", "2003-11-02T06:00:00Z"), "2003nov": ("2003-11-20T00:00:00Z", "2003-11-21T12:00:00Z"),
"2004nov": ("2004-11-07T06:00:00Z", "2004-11-09T12:00:00Z"), "2024may": ("2024-05-10T12:00:00Z", "2024-05-11T12:00:00Z"),
"2024may2": ("2024-05-11T12:00:00Z", "2024-05-12T16:00:00Z")}
OMNI_MONTHS = ["198903", "200007", "200111", "200310", "202405", "202410"]
SPEED_FILE = "raj2025-ace-speeds-transcribed.csv"
# ---------------------------------------------------------------- downloads
def fetch(url, path):
if os.path.exists(path) and os.path.getsize(path) > 0:
return path
os.makedirs(os.path.dirname(path), exist_ok=True)
req = urllib.request.Request(url, headers={"User-Agent": UA})
for attempt in range(4):
try:
with urllib.request.urlopen(req, timeout=300) as r:
data = r.read()
with open(path, "wb") as f:
f.write(data)
print("fetched", url[:110], len(data))
time.sleep(0.3)
return path
except (urllib.error.URLError, TimeoutError) as e:
print("retrying", url[:110], e)
time.sleep(5 * (attempt + 1))
raise SystemExit("Could not fetch " + url)
def cdaweb(folder, tag, dataset, params, name=None):
a, z = WINDOWS[tag]
u = f"{CDAWEB}?id={dataset}¶meters={params}&time.min={a}&time.max={z}&format=csv"
return fetch(u, os.path.join(folder, "cdaweb_hapi", f"{tag}__{name or dataset}.csv"))
def get_inputs(folder):
for m in OMNI_MONTHS:
fetch(SPDF + f"omni_min{m}.asc", os.path.join(folder, "omni_hro_1min", f"omni_min{m}.asc"))
fetch(RC_URL, os.path.join(folder, "richardson_cane_icme", "icmetable2.htm"))
for tag in WINDOWS:
cdaweb(folder, tag, "AC_H0_MFI", "Magnitude,BGSM")
cdaweb(folder, tag, "AC_H0_SWE", "Np,Vp,V_GSM")
cdaweb(folder, "2024may", "WI_H0_MFI@0", "BF1,BGSM,PGSE", name="WI_H0_MFI_1min")
cdaweb(folder, "2024may", "WI_H1_SWE", "fit_flag,Proton_V_nonlin,Proton_VX_nonlin,Proton_Np_nonlin")
fetch(f"{CDAWEB}?id=I8_H0_MITPLASMA¶meters=Region,xyzgse,V_fit,V_mom,proton_density_fit&time.min=1989-03-12T00:00:00Z&time.max=1989-03-15T12:00:00Z&format=csv",
os.path.join(folder, "cdaweb_hapi", "1989mar__I8_H0_MITPLASMA.csv"))
fetch(f"{KYOTO}?id=hour_dst¶meters=dstValue,versionCode&time.min=1957-01-01T00:29:30Z&time.max=2026-11-01T00:00:00Z&format=csv",
os.path.join(folder, "kyoto_hapi", "hour_dst_1957_2026.csv"))
for t, _ in STORMS_1981:
symh_window(folder, t)
def symh_window(folder, tdst):
t = pd.Timestamp(tdst)
a, z = t - pd.Timedelta(hours=62), t + pd.Timedelta(hours=13)
u = f"{KYOTO}?id=min_asysym¶meters=symHValue,versionCode&time.min={a:%Y-%m-%dT%H:%M}:00Z&time.max={z:%Y-%m-%dT%H:%M}:00Z&format=csv"
return fetch(u, os.path.join(folder, "kyoto_hapi", f"symh_{t:%Y%m%d%H}.csv"))
# ---------------------------------------------------------------- readers
OMNI_WIDTHS = [4, 4, 3, 3, 3, 3, 4, 4, 4, 7, 7, 6, 7] + [8] * 8 + [8] * 4 + [7, 9, 6, 7, 7, 6] + [8] * 6 + [6] * 7 + [7, 5]
OMNI_NAMES = ["year", "doy", "hour", "minute", "imf_id", "sw_id", "n_imf", "n_plasma", "pct_interp", "timeshift", "rms_timeshift",
"rms_pfn", "dbot", "B", "Bx", "ByGSE", "BzGSE", "ByGSM", "BzGSM", "rms_b", "rms_bv", "V", "Vx", "Vy", "Vz", "N", "T", "P",
"E", "beta", "MA", "xsc", "ysc", "zsc", "xbsn", "ybsn", "zbsn", "AE", "AL", "AU", "SYMD", "SYMH", "ASYD", "ASYH", "PCN", "Mms"]
OMNI_FILL = {"imf_id": 99, "sw_id": 99, "timeshift": 999999, "B": 9999.99, "BzGSM": 9999.99, "V": 99999.9, "Vx": 99999.9, "N": 999.99,
"P": 99.99, "E": 999.99, "SYMH": 99999}
def read_omni(folder, month):
df = pd.read_fwf(os.path.join(folder, "omni_hro_1min", f"omni_min{month}.asc"), widths=OMNI_WIDTHS, names=OMNI_NAMES, header=None)
for k, f in OMNI_FILL.items():
df[k] = df[k].astype(float).where(lambda s: np.abs(s - f) > 1e-6)
base = pd.to_datetime(df["year"].astype(str), format="%Y")
df.index = base + pd.to_timedelta(df["doy"] - 1, unit="D") + pd.to_timedelta(df["hour"], unit="h") + pd.to_timedelta(df["minute"], unit="m")
df["IEFy"] = -np.abs(df["Vx"]) * df["BzGSM"] * 1e-3
return df
def read_csv(path, cols):
df = pd.read_csv(path, header=None, names=["t"] + cols, comment="#")
df["t"] = pd.to_datetime(df["t"], format="%Y-%m-%dT%H:%M:%S.%fZ", errors="coerce")
df = df.dropna(subset=["t"]).set_index("t").sort_index()
for c in cols:
df[c] = pd.to_numeric(df[c], errors="coerce")
df.loc[df[c].abs() > 1e20, c] = np.nan
return df
def load_ace(folder, tags):
ms, ss = [], []
for tag in tags:
ms.append(read_csv(os.path.join(folder, "cdaweb_hapi", f"{tag}__AC_H0_MFI.csv"), ["B", "Bx", "By", "Bz"]))
ss.append(read_csv(os.path.join(folder, "cdaweb_hapi", f"{tag}__AC_H0_SWE.csv"), ["Np", "Vp", "Vx", "Vy", "Vz"]))
m = pd.concat(ms).sort_index()
s = pd.concat(ss).sort_index()
return pd.DataFrame({"B": m["B"].resample("1min").mean(), "Bz": m["Bz"].resample("1min").mean(),
"V": s["Vx"].abs().resample("1min").mean().where(lambda x: x.notna(), s["Vp"].resample("1min").mean()),
"N": s["Np"].resample("1min").mean()}).asfreq("1min")
def load_wind(folder, tag):
m = read_csv(os.path.join(folder, "cdaweb_hapi", f"{tag}__WI_H0_MFI_1min.csv"), ["B", "Bx", "By", "Bz", "x", "y", "z"])
m.index = m.index.floor("1min")
s = read_csv(os.path.join(folder, "cdaweb_hapi", f"{tag}__WI_H1_SWE.csv"), ["flag", "V", "Vx", "Np"])
s.loc[s["V"] > 9000, ["V", "Vx", "Np"]] = np.nan
return pd.DataFrame({"B": m["B"], "Bz": m["Bz"]}).join(pd.DataFrame({"V": s["Vx"].abs().resample("1min").mean(), "N": s["Np"].resample("1min").mean()}), how="outer").asfreq("1min")
def read_speeds():
df = pd.read_csv(os.path.join(HERE, SPEED_FILE), comment="#")
df["t"] = pd.to_datetime(df["time_utc"])
return df.set_index("t").sort_index()
def read_rc(path):
raw = open(path, encoding="latin-1").read()
out = []
for row in re.split(r"
]+>", " ", row)
toks = re.findall(r"(\d{4}/\d{2}/\d{2}\s+\d{4})", txt)
if len(toks) >= 3:
out.append(tuple(pd.Timestamp(x.replace("/", "-")[:10] + " " + x.split()[1][:2] + ":" + x.split()[1][2:]) for x in toks[:3]))
return out
# ---------------------------------------------------------------- measures
def mean_win(s, a, b):
"""Mean over [a, b) if at least 50% of the minutes are valid, else NaN; also returns coverage."""
w = s.loc[a: b - MIN]
n = int(round((b - a) / MIN))
v = w.notna().sum()
if n == 0 or v < 0.5 * n:
return np.nan, v / max(n, 1)
return float(w.mean()), v / n
def blocks_5min(iefy, t0):
start, end = t0.ceil("5min"), t0.floor("5min")
post, _ = mean_win(iefy, start, start + 5 * MIN)
pre, _ = mean_win(iefy, end - 5 * MIN, end)
return post - pre
def variants(iefy, t0):
r = {}
for name, w in (("A", 10), ("B", 5), ("C", 30), ("D", 60)):
post, cp = mean_win(iefy, t0, t0 + w * MIN)
pre, cq = mean_win(iefy, t0 - w * MIN, t0)
r[name] = post - pre
r[name + "_cov"] = min(cp, cq)
run5 = iefy.rolling(5, min_periods=3).mean()
seg = run5.loc[t0 + 4 * MIN: t0 + 34 * MIN]
pre, _ = mean_win(iefy, t0 - 30 * MIN, t0)
r["E"] = float(seg.max()) - pre if seg.notna().any() else np.nan
r["F"] = blocks_5min(iefy, t0)
for k, label in ((-5, "Am5"), (-2, "Am2"), (2, "Ap2"), (5, "Ap5")):
t = t0 + k * MIN
post, _ = mean_win(iefy, t, t + 10 * MIN)
pre, _ = mean_win(iefy, t - 10 * MIN, t)
r[label] = post - pre
r["pre10"], _ = mean_win(iefy, t0 - 10 * MIN, t0)
r["post10"], _ = mean_win(iefy, t0, t0 + 10 * MIN)
return r
def step_front(series, a, b, around_after=True):
"""The minute in [a, b] maximising the step in 10-min medians, moved to the earliest minute within +/-10 min at half the step."""
best, bv, bpre = None, -np.inf, None
for t in series.loc[a: b].index:
pre = series.loc[t - 10 * MIN: t - MIN].dropna()
post = series.loc[t: t + 9 * MIN].dropna()
if len(pre) < 3 or len(post) < 3:
continue
d = post.median() - pre.median()
if d > bv:
best, bv, bpre = t, d, pre.median()
if best is None:
return None, None
level = bpre + 0.5 * bv
w = series.loc[best - 10 * MIN: best + 10 * MIN]
above = w[w >= level]
return (above.index[0] if len(above) else best), bv
def front_monitor(b, tdist, flagged):
if flagged:
return step_front(b, tdist - 10 * MIN, tdist + 10 * MIN)
return step_front(b, tdist - 75 * MIN, tdist - 5 * MIN)
def front_omni(df, tdist):
for col in ("P", "B"):
t, st = step_front(df[col], tdist - 20 * MIN, tdist + 20 * MIN)
if t is not None:
return t, st, col
return None, None, None
def hybrid_speed(index, rows, t0):
"""V(t) on a 1-min index: linear between listed speeds on each side of t0, with a step at t0."""
r = rows["speed_km_s"].dropna()
pre, post = r[r.index < t0], r[r.index >= t0]
v = pd.Series(np.nan, index=index, dtype=float)
ti = index.astype("int64").values.astype(float)
if str(index.dtype) != "datetime64[ns]": # pandas may hold seconds or microseconds; compare on one clock
ti = index.as_unit("ns").astype("int64").values.astype(float)
pre_t = pre.index.as_unit("ns").astype("int64").values.astype(float)
post_t = post.index.as_unit("ns").astype("int64").values.astype(float)
t0v = t0.value
a = ti < t0v
v[a] = np.interp(ti[a], pre_t, pre.values)
v[~a] = np.interp(ti[~a], post_t, post.values)
return v
def largest_step(iefy, t0):
out, when = -np.inf, None
for t in iefy.loc[t0: t0 + 6 * HOUR].index:
a, _ = mean_win(iefy, t - 10 * MIN, t)
b, _ = mean_win(iefy, t, t + 10 * MIN)
if np.isfinite(a) and np.isfinite(b) and b - a > out:
out, when = b - a, t
return out, when
def comb(iefy, t0, step=33):
"""For every phase of a 33-min comb: first tooth at or after t0 minus last tooth before t0; a tooth is the mean within +/-1 min."""
out = []
for ph in range(step):
after = t0 + ph * MIN
before = after - step * MIN
a = iefy.loc[after - MIN: after + MIN].mean()
b = iefy.loc[before - MIN: before + MIN].mean()
if np.isfinite(a) and np.isfinite(b):
out.append(a - b)
return np.array(out)
def separation(vals, labels, higher=True):
"""AUC and exact one-sided permutation p over all arrangements. A description of a few events, not a test."""
x = np.array(vals, float)
y = np.array(labels, int)
ok = ~np.isnan(x)
x, y = x[ok], y[ok]
if not higher:
x = -x
n_all, n_pos = len(x), int(y.sum())
pos, neg = x[y == 1], x[y == 0]
auc = float(np.mean([(p > q) + 0.5 * (p == q) for p in pos for q in neg]))
ranks = pd.Series(x).rank().values
obs = ranks[y == 1].sum()
combs = list(itertools.combinations(range(n_all), n_pos))
c = sum(ranks[list(cc)].sum() >= obs - 1e-9 for cc in combs)
return {"N": n_all, "n": n_pos, "auc": round(auc, 3), "p": round(c / len(combs), 4), "floor": round(1 / len(combs), 4), "gap": round(float(pos.min() - neg.max()), 2)}
def initial_phase(s, tmin):
"""The 8 h up to the moment the index last turned negative before tmin, or None if it never did in the 48 h before."""
back = s.loc[tmin - pd.Timedelta(hours=48): tmin].dropna()
neg = (back < 0).values
for i in range(len(back) - 1, 0, -1):
if neg[i] and not neg[i - 1]:
cross = back.index[i]
return back.loc[cross - pd.Timedelta(hours=8): cross]
return None
def revised(s, tmin):
"""A simplified form of Manu et al. (2024): the minimum minus the largest peak of the initial phase, if that peak is positive."""
ip = initial_phase(s, tmin)
if ip is None or float(ip.max()) <= 0:
return float(s.loc[tmin]), None, None
mpo = float(ip.max())
return float(s.loc[tmin]) - mpo, mpo, ip.idxmax()
def second_peak(s, tmin):
"""Our reading of Manu et al.'s criterion 5: a later peak of the same initial phase, at least 60% of the largest, with a minimum
at or below 40% of the largest between them, replaces the largest. Returns the largest such peak, or None. Their program may differ."""
ip = initial_phase(s, tmin)
if ip is None or float(ip.max()) <= 0:
return None
largest = float(ip.max())
after = ip.loc[ip.idxmax():]
vals, times = after.values, after.index
low, best = np.inf, None
for i in range(1, len(vals) - 1):
low = min(low, vals[i])
if vals[i] >= vals[i - 1] and vals[i] > vals[i + 1] and vals[i] >= 0.6 * largest and low <= 0.4 * largest:
if best is None or vals[i] > best["peak"]:
best = {"peak": float(vals[i]), "peak_time": str(times[i]), "min_between": float(low), "revised": float(s.loc[tmin]) - float(vals[i])}
return best
def rd(x, n=3):
return None if x is None or (isinstance(x, float) and not np.isfinite(x)) else round(float(x), n)
# ---------------------------------------------------------------- main
def main():
folder = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "may2024_data")
get_inputs(folder)
out = {"note": "Our analysis. Every definition of dIEFy, front and body is ours; the paper's may differ. See the docstring of may2024_numbers.py and the hosted rules."}
rows = read_speeds()
# ---- Kyoto: Dst
dst = pd.read_csv(os.path.join(folder, "kyoto_hapi", "hour_dst_1957_2026.csv"), header=None, names=["t", "v", "code"])
dst["t"] = pd.to_datetime(dst["t"].str[:19])
dst = dst[dst["v"] < 9000].set_index("t")
low = dst[dst["v"] <= -250]
storms = []
for t, r in low.iterrows():
if storms and (t - storms[-1][-1][0]) < pd.Timedelta(hours=48):
storms[-1].append((t, r["v"], r["code"]))
else:
storms.append([(t, r["v"], r["code"])])
table = sorted((min(s, key=lambda x: x[1]) for s in storms), key=lambda x: x[1])
may = dst.loc["2024-05-10":"2024-05-11"]
out["dst"] = {"may_2024_min": int(may["v"].min()), "may_2024_min_bin_centre": str(may["v"].idxmin()), "may_2024_version_code": int(may.loc[may["v"].idxmin(), "code"]),
"may_2024_peak_before_fall": int(may.loc["2024-05-10", "v"].max()), "march_1989_min": int(dst.loc["1989-03-13":"1989-03-14", "v"].min()),
"rank_since_1957": 1 + sum(1 for x in table if x[1] < -406), "rank_since_1981": 1 + sum(1 for x in table if x[1] < -406 and x[0] >= pd.Timestamp("1981")),
"deeper_or_equal_storms": [{"time": str(x[0]), "dst": int(x[1])} for x in table if x[1] <= -387],
"same_subtraction": int(may["v"].min() - may.loc["2024-05-10", "v"].max())}
dv = dst["v"].astype(float)
same = []
for st in storms:
tm, vm, _ = min(st, key=lambda x: x[1])
r, mpo, tp = revised(dv, tm)
same.append({"time": str(tm), "dst": int(vm), "peak_before": None if mpo is None else int(mpo), "peak_time": None if tp is None else str(tp), "same_subtraction": int(r)})
same.sort(key=lambda x: x["same_subtraction"])
out["dst"]["same_subtraction_on_hourly_dst_since_1957"] = {
"note": "Our arithmetic, with revised() on Kyoto's hourly Dst, storms at or below -250 nT. Hourly means hide short peaks, so small margins here are not firm.",
"storms": len(same), "rank_may_2024": 1 + next(i for i, x in enumerate(same) if x["time"].startswith("2024-05")), "top": same[:9]}
# ---- Kyoto: SYM-H and the revised measure
rev = []
series_may = None
for t, d in STORMS_1981:
f = symh_window(folder, t)
s = pd.read_csv(f, header=None, names=["t", "v", "code"])
s["t"] = pd.to_datetime(s["t"].str[:19])
s = s[s["v"] < 9000].set_index("t")["v"].astype(float)
tt = pd.Timestamp(t)
w = s.loc[tt - pd.Timedelta(hours=12): tt + pd.Timedelta(hours=12)]
tmin, vmin = w.idxmin(), float(w.min())
r, mpo, tmpo = revised(s, tmin)
rev.append({"dst_time": t, "dst_min": d, "symh_min": vmin, "symh_min_time": str(tmin), "peak_before": mpo, "peak_time": None if tmpo is None else str(tmpo), "revised": r, "second_peak_reading": second_peak(s, tmin)})
if t.startswith("2024-05"):
series_may = s
out["symh_since_1981"] = rev
out["rank_symh"] = [x["dst_time"][:10] for x in sorted(rev, key=lambda x: x["symh_min"])][:4]
out["rank_revised"] = [x["dst_time"][:10] for x in sorted(rev, key=lambda x: x["revised"])][:4]
with_second = lambda x: x["second_peak_reading"]["revised"] if x["second_peak_reading"] else x["revised"]
out["rank_revised_on_our_reading_of_criterion_5"] = [[x["dst_time"][:10], with_second(x)] for x in sorted(rev, key=with_second)][:4]
# ---- what data exist
avail = {}
om = {m: read_omni(folder, m) for m in OMNI_MONTHS}
both = lambda d: d["Vx"].notna() & d["BzGSM"].notna()
o89 = om["198903"]
b89 = both(o89)
avail["omni_1989_minutes_with_speed_and_Bz_13Mar0000_14Mar2200"] = int(b89.loc["1989-03-13 00:00":"1989-03-14 22:00"].sum())
avail["omni_1989_first_minute_after_storm_start"] = str(b89[b89].loc["1989-03-13 00:00":].index[0])
p8 = pd.read_csv(os.path.join(folder, "cdaweb_hapi", "1989mar__I8_H0_MITPLASMA.csv"), header=None, names=["t", "Region", "x", "y", "z", "Vf", "Vm", "Np"])
p8["t"] = pd.to_datetime(p8["t"].str[:19])
p8 = p8.set_index("t")
sw = p8[p8["Region"].isin([1, 2])].loc["1989-03-13":]
avail["imp8_first_record_flagged_solar_wind_after_13Mar"] = str(sw.index[0])
seg = p8.loc["1989-03-13":str(sw.index[0])].iloc[:-1]
avail["imp8_records_13Mar_until_then"] = int(len(seg))
avail["imp8_flags_until_then"] = {str(int(k)): int(v) for k, v in seg["Region"].value_counts().items()}
avail["imp8_x_gse_re"] = [float(p8.loc["1989-03-13":"1989-03-14 23:59", "x"].min()), float(p8.loc["1989-03-13":"1989-03-14 23:59", "x"].max())]
o01, o03, o24 = om["200111"], om["200310"], om["202405"]
avail["omni_2001_minutes_with_both_0130_0330"] = int(both(o01).loc["2001-11-06 01:52":"2001-11-06 03:30"].sum())
b03 = both(o03)
avail["omni_2003_gap_29Oct"] = [str(b03[b03].loc[:"2003-10-29 06:00"].index[-1]), str(b03[b03].loc["2003-10-29 06:00":].index[0])]
avail["omni_2003_gap_30Oct"] = [str(b03[b03].loc[:"2003-10-30 12:00"].index[-1]), str(b03[b03].loc["2003-10-30 12:00":].index[0])]
sh = o24.loc["2024-05-10 17:05":"2024-05-10 17:33"]
ts = o24["timeshift"].loc["2024-05-10 16:50":"2024-05-10 18:00"]
avail["omni_2024_minutes_under_520_kms_1705_1733"] = [int((sh["Vx"].abs() < 520).sum()), int(sh["Vx"].notna().sum())]
avail["omni_2024_time_shift_s_1650_1800"] = [float(ts.min()), float(ts.max())]
v01 = read_csv(os.path.join(folder, "cdaweb_hapi", "2001nov__AC_H0_SWE.csv"), ["Np", "Vp", "Vx", "Vy", "Vz"])["Vp"].loc["2001-11-05 23:00":"2001-11-06 03:00"].dropna()
avail["ace_2001_last_valid_64s_speed_before_shock"] = [str(v01.index[-1].floor("s")), rd(float(v01.iloc[-1]), 2)]
r03 = rows[rows["event"] == "2003-10"]["speed_km_s"]
spacing = r03.index.to_series().diff().dt.total_seconds().div(60)
avail["listed_speeds"] = {"rows": int(len(rows)), "rows_2003": int(len(r03)), "median_spacing_min_2003": rd(spacing.median(), 2), "largest_spacing_min_2003": rd(spacing.max(), 1),
"largest_gap_ends": str(spacing.idxmax().floor("s"))}
out["availability"] = avail
# ---- the re-run
rc = read_rc(os.path.join(folder, "richardson_cane_icme", "icmetable2.htm"))
out["richardson_cane_rows_read"] = len(rc)
results = []
traces = {}
for key, tags, tdist, flagged, rcs, rce, tsym, dmin, outage, monitor in EVENTS:
tdist, rcs, rce, tsym = map(pd.Timestamp, (tdist, rcs, rce, tsym))
if monitor == "OMNI":
d = om[tdist.strftime("%Y%m")]
t0, st, _ = front_omni(d, tdist)
iefy = d["IEFy"]
speed, bz = d["Vx"].abs(), d["BzGSM"]
source = "OMNI"
else:
d = load_ace(folder, tags)
t0, st = front_monitor(d["B"], tdist, flagged)
v = d["V"].copy()
source = "ACE"
if monitor == "ACE+rows":
ev = rows[rows["event"] == key[:7]]
hv = hybrid_speed(d.index[d.index <= ev.index[-1]], ev, t0)
v.loc[hv.index] = v.loc[hv.index].where(v.loc[hv.index].notna(), hv)
source = "ACE field, speeds transcribed from Raj 2025"
iefy = -v * d["Bz"] * 1e-3
speed, bz = v, d["Bz"]
res = variants(iefy, t0)
v_after, _ = mean_win(speed, t0, t0 + 10 * MIN)
v_before, _ = mean_win(speed, t0 - 10 * MIN, t0)
bz_after, _ = mean_win(bz, t0, t0 + 10 * MIN)
s_val, s_when = largest_step(iefy, t0)
g, cg = mean_win(iefy, t0, rce)
h, ch = mean_win(iefy, rcs, rce)
i, ci = mean_win(iefy, t0, tsym)
j, cj = mean_win(iefy, t0, t0 + 6 * HOUR)
c = comb(iefy, t0)
run5 = iefy.rolling(5, min_periods=3).mean().loc[t0 + 4 * MIN: t0 + 6 * HOUR]
sy = next(pd.read_csv(symh_window(folder, x[0]), header=None, names=["t", "v", "code"]) for x in STORMS_1981 if abs((pd.Timestamp(x[0]) - tsym) / HOUR) <= 12 and x[1] == dmin)
sy["t"] = pd.to_datetime(sy["t"].str[:19])
sy = sy[sy["v"] < 9000].set_index("t")["v"].astype(float)
cg0 = tdist + (25 * MIN if flagged else 0 * MIN)
wsy = sy.loc[cg0 - 15 * MIN: cg0 + 25 * MIN]
rise = float((wsy.shift(-10) - wsy.rolling(3, center=True, min_periods=3).min()).max())
results.append({"storm": key, "outage_in_abstract": outage, "data": source, "front_utc": str(t0), "dst_min": dmin, "symh_min": float(sy.loc[tsym]), "ssc_rise_nT": rise,
"pre10": rd(res["pre10"]), "post10": rd(res["post10"]), "dIEFy_A_10min": rd(res["A"]), "dIEFy_B_5min": rd(res["B"]), "dIEFy_C_30min": rd(res["C"]), "dIEFy_D_60min": rd(res["D"]),
"dIEFy_E_first_peak": rd(res["E"]), "dIEFy_F_blocks": rd(res["F"]), "dV_km_s": rd(v_after - v_before), "Bz_10min_after_nT": rd(bz_after), "dV_x_Bz_10min": rd(-(v_after - v_before) * bz_after * 1e-3), "A_front_minus5": rd(res["Am5"]), "A_front_minus2": rd(res["Am2"]), "A_front_plus2": rd(res["Ap2"]), "A_front_plus5": rd(res["Ap5"]),
"largest_10min_step_in_6h": rd(s_val), "step_after_min": None if s_when is None else (s_when - t0) / MIN, "peak_5min_running_mean_in_6h": rd(run5.max()),
"mean_I_front_to_symh_min": rd(i), "I_coverage": rd(ci), "mean_J_6h": rd(j), "J_coverage": rd(cj), "mean_G_front_to_rc_end": rd(g), "G_coverage": rd(cg), "mean_H_rc_icme": rd(h), "H_coverage": rd(ch),
"comb_min": rd(c.min()) if len(c) else None, "comb_median": rd(np.median(c)) if len(c) else None, "comb_max": rd(c.max()) if len(c) else None, "comb_share_under_4": rd((c < 4).mean()) if len(c) else None, "comb_share_over_15": rd((c > 15).mean()) if len(c) else None})
if key in ("2024-05-10", "2001-11-06", "2003-10-30"):
tr = iefy.loc[t0 - 30 * MIN: t0 + 90 * MIN]
traces[key] = {"front_utc": str(t0), "minutes": [(x - t0) / MIN for x in tr.index], "iefy": [rd(x, 2) for x in tr.values]}
t = pd.DataFrame(results)
t.to_csv(os.path.join(HERE, "may2024-storms.csv"), index=False, lineterminator="\n")
out["storms_note"] = "13 Mar 1989 has no solar-wind measurement and cannot enter. Outage labels are the abstract's. 2001 and 2003 speeds are a transcription of Raj (2025)."
# ---- May 2024 by monitor and window
ace = load_ace(folder, ["2024may", "2024may2"])
ai = -ace["V"] * ace["Bz"] * 1e-3
at0, _ = front_monitor(ace["B"], pd.Timestamp("2024-05-10 17:05"), False)
wd = load_wind(folder, "2024may")
wi = -wd["V"] * wd["Bz"] * 1e-3
wt0, _ = front_monitor(wd["B"], pd.Timestamp("2024-05-10 17:05"), False)
win = {}
for name, s0, tt in (("ACE", ai, at0), ("Wind", wi, wt0)):
win[name] = {"front_utc": str(tt), "by_window_min": {str(w): rd(mean_win(s0, tt, tt + w * MIN)[0] - mean_win(s0, tt - w * MIN, tt)[0]) for w in (3, 5, 7, 10, 12, 15, 20, 30, 45, 60)}}
hi = s0.loc[tt: tt + HOUR]
fp = hi[hi > 15]
win[name]["first_minute_over_15"] = str(fp.index[0])
win[name]["minutes_after_front"] = (fp.index[0] - tt) / MIN
win[name]["highest_in_6h_1min"] = rd(s0.loc[tt: tt + 6 * HOUR].max())
d = o24
v = d["Vx"].abs()
vf = v.copy()
t0 = pd.Timestamp("2024-05-10 17:03")
mask = vf.index < t0
vf[mask] = v[mask].ffill(limit=5)
relaxed = variants(-vf * d["BzGSM"] * 1e-3, t0)
win["OMNI_relaxed_gap_rule"] = {"front_utc": str(t0), **{k: rd(relaxed[k]) for k in ("A", "B", "C", "D", "E", "F")}}
first10 = ace.loc[at0: at0 + 9 * MIN, "Bz"]
win["ACE_Bz_first_10_min_range_nT"] = [rd(first10.min()), rd(first10.max())]
out["may_2024_by_monitor"] = win
# ---- context
ctx = {}
for name, dd, tt in (("ACE", ace, pd.Timestamp("2024-05-10 16:37")), ("Wind", wd, pd.Timestamp("2024-05-10 16:36"))):
p = 2e-6 * dd["N"] * dd["V"] ** 2
ctx[f"pressure_{name}_nPa_before_after"] = [rd(p.loc[tt - 10 * MIN: tt - MIN].median(), 1), rd(p.loc[tt: tt + 9 * MIN].median(), 1)]
ctx["iefy_near_highest_US_GIC_ACE_0125_0155_11May"] = rd(ai.loc["2024-05-11 01:25":"2024-05-11 01:55"].mean(), 1)
ctx["iefy_near_Eyrewell_321nT_per_min_ACE_0755_0825_11May"] = rd(ai.loc["2024-05-11 07:55":"2024-05-11 08:25"].mean(), 1)
ctx["iefy_near_Awarua_478nT_per_min_ACE_1150_1220_11May"] = rd(ai.loc["2024-05-11 11:50":"2024-05-11 12:20"].mean(), 1)
ctx["iefy_ACE_5min_means_from_0750_0755_0800_11May"] = [rd(ai.loc[f"2024-05-11 {a}":f"2024-05-11 {z}"].mean(), 1) for a, z in (("07:50", "07:54"), ("07:55", "07:59"), ("08:00", "08:04"))]
b03a = load_ace(folder, ["2003oct"])
ev = rows[rows["event"] == "2003-10"]
idx = b03a.index[b03a.index <= ev.index[-1]]
v3 = hybrid_speed(idx, ev, pd.Timestamp("2003-10-30 16:19"))
i3 = -v3 * b03a.loc[idx, "Bz"] * 1e-3
ctx["iefy_near_Malmo_ACE_1930_1955_30Oct2003"] = rd(i3.loc["2003-10-30 19:30":"2003-10-30 19:55"].mean(), 1)
b01a = load_ace(folder, ["2001nov"])
ev = rows[rows["event"] == "2001-11"]
idx = b01a.index[b01a.index <= ev.index[-1]]
v1 = hybrid_speed(idx, ev, pd.Timestamp("2001-11-06 01:24"))
i1 = -v1 * b01a.loc[idx, "Bz"] * 1e-3
ctx["iefy_just_after_2001_shock_ACE_0124_0134"] = rd(i1.loc["2001-11-06 01:24":"2001-11-06 01:34"].mean(), 1)
# October 30, 2003: how far its mean from the front to SYM-H's low leans on the listed speeds
d03 = load_ace(folder, ["2003oct", "2003nov2"])
ev = rows[rows["event"] == "2003-10"]
idx = d03.index[d03.index <= ev.index[-1]]
f03, l03 = pd.Timestamp("2003-10-30 16:19"), pd.Timestamp("2003-10-30 22:55")
bz03, r03 = d03.loc[idx, "Bz"], ev["speed_km_s"]
lin = hybrid_speed(idx, ev, f03)
mean_i = lambda sp: rd(mean_win(-sp * bz03 * 1e-3, f03, l03)[0], 2)
fitted = (idx >= pd.Timestamp("2003-10-30 17:20")) & (idx <= pd.Timestamp("2003-10-30 19:00"))
ctx["oct30_2003_mean_I_speed_tests"] = {"linear_between_rows": mean_i(lin), "previous_row_held": mean_i(pd.Series(r03.reindex(idx.union(r03.index)).ffill().reindex(idx).values, index=idx)),
"next_row_held": mean_i(pd.Series(r03.reindex(idx.union(r03.index)).bfill().reindex(idx).values, index=idx)),
"fitted_rows_window_x0.9": mean_i(lin.where(~fitted, lin * 0.9)), "fitted_rows_window_x1.1": mean_i(lin.where(~fitted, lin * 1.1)),
"speed_factor_to_20": rd(20 / mean_win(-lin * bz03 * 1e-3, f03, l03)[0], 3), "speed_factor_to_15.5": rd(15.5 / mean_win(-lin * bz03 * 1e-3, f03, l03)[0], 3)}
solar = lambda lon, h, m: "{:02d}:{:02d}".format(int((h + m / 60 + lon / 15) % 24), int(((h + m / 60 + lon / 15) % 24) % 1 * 60))
ctx["solar_times_from_longitude"] = {"Quebec_71.2W_at_17:05_UT": solar(-71.2, 17, 5), "Dunedin_170.5E_at_17:05_UT": solar(170.5, 17, 5), "Dunedin_170.5E_at_01:53_UT": solar(170.5, 1, 53), "Malmo_13.0E_at_20:07_UT": solar(13.0, 20, 7),
"Quebec_71.2W_at_07:44_UT": solar(-71.2, 7, 44), "Jicamarca_76.9W_at_17:05_UT": solar(-76.9, 17, 5), "Thumba_77.0E_at_17:05_UT": solar(77.0, 17, 5), "Sanya_109.6E_at_17:05_UT": solar(109.6, 17, 5)}
out["context"] = ctx
# ---- how well things separate (a description of 2 outage storms among 11, chosen after seeing the data; not a test)
sep = {}
for name, col, hi in (("dIEFy A", "dIEFy_A_10min", True), ("dIEFy B", "dIEFy_B_5min", True), ("dIEFy C", "dIEFy_C_30min", True), ("dIEFy D", "dIEFy_D_60min", True), ("dIEFy E", "dIEFy_E_first_peak", True), ("dIEFy F", "dIEFy_F_blocks", True), ("dV x Bz", "dV_x_Bz_10min", True),
("largest step", "largest_10min_step_in_6h", True), ("peak 5-min", "peak_5min_running_mean_in_6h", True), ("mean G", "mean_G_front_to_rc_end", True), ("mean H", "mean_H_rc_icme", True), ("mean I", "mean_I_front_to_symh_min", True), ("mean J", "mean_J_6h", True),
("Dst", "dst_min", False), ("SYM-H", "symh_min", False), ("sudden commencement rise", "ssc_rise_nT", True)):
sep[name] = separation(t[col].astype(float).values, t["outage_in_abstract"].values, hi)
out["separation_description_only"] = sep
with open(os.path.join(HERE, "may2024-numbers.json"), "w", encoding="utf-8", newline="\n") as f:
json.dump(out, f, ensure_ascii=False, indent=1)
sym = series_may.loc["2024-05-10 16:00":"2024-05-11 06:00"]
dh = dst.loc["2024-05-10 16:00":"2024-05-11 06:00", "v"]
with open(os.path.join(HERE, "may2024-chart-series.json"), "w", encoding="utf-8", newline="\n") as f:
json.dump({"note": "SYM-H: WDC for Geomagnetism, Kyoto, doi:10.14989/267216, provisional, scientific use only, no commercial use. IEFy: our calculation, ACE on its own clock; 2001 and 2003 speeds as listed in Raj (2025), transcribed; minutes are relative to our front.",
"symh_start_utc": str(sym.index[0]), "symh_nT_per_minute": [int(x) for x in sym.values], "dst_first_bin_centre_utc": str(dh.index[0]), "dst_nT_per_hour": [int(x) for x in dh.values], "iefy_around_fronts": traces}, f, ensure_ascii=False)
print(json.dumps({k: out[k] for k in ("dst", "rank_symh", "rank_revised", "availability", "context")}, indent=1, ensure_ascii=False))
print(t[["storm", "data", "front_utc", "pre10", "post10", "dIEFy_A_10min", "dIEFy_B_5min", "dIEFy_C_30min", "dIEFy_D_60min", "dIEFy_E_first_peak", "mean_I_front_to_symh_min", "mean_J_6h", "mean_H_rc_icme"]].to_string(index=False))
if __name__ == "__main__":
main()