#!/usr/bin/env python3 """Our analysis for may-2024-dc-ac-circuit, rules A (cutoffs, rigidities, neutron monitors) and B (storm timeline). Usage: python3 -I ab_storm_cutoffs.py DOWNLOADS_DIR OUT_DIR Needs numpy, pandas, netCDF4. Reads every input as data. Rules: RULES_A_gle_access.txt, RULES_A_amendment_hourly.txt, RULES_B_storm_timeline.txt (hashes in out/analysis-log.md). """ import json import math import os import re import sys import numpy as np import pandas as pd sys.stdout.reconfigure(encoding="utf-8") DL, OUT = sys.argv[1], sys.argv[2] os.makedirs(OUT, exist_ok=True) MP = 938.272 # proton rest energy, MeV SITES = {"KAK": (36.2448, 140.1928), "CHF": (35.6506, 139.5407), "BGL": (23.3349, 88.6483), "PRL": (23.3322, 86.3616)} CHECK = {"DJON": (36.37, 127.37, 11.20), "PSNM": (18.59, 98.49, 16.80)} # ---------------- A1: Smart & Shea (2019) Table 1A, epoch 2015, typed from the table image ---------------- GRID = { # (lat, lon): GV (15, 90): 17.25, (15, 105): 17.15, (20, 75): 16.23, (20, 90): 16.49, (20, 105): 16.44, (25, 75): 15.05, (25, 90): 15.32, (25, 105): 15.35, (35, 120): 11.29, (35, 135): 11.51, (35, 150): 11.16, (40, 120): 8.93, (40, 135): 9.30, (40, 150): 9.22, } def bilinear(lat, lon): la0 = 5 * math.floor(lat / 5) lo0 = 15 * math.floor(lon / 15) la1, lo1 = la0 + 5, lo0 + 15 q = [GRID[(la0, lo0)], GRID[(la0, lo1)], GRID[(la1, lo0)], GRID[(la1, lo1)]] t = (lat - la0) / 5 u = (lon - lo0) / 15 v0 = q[0] + u * (q[1] - q[0]) v1 = q[2] + u * (q[3] - q[2]) return v0 + t * (v1 - v0), {"nodes": [[la0, lo0, q[0]], [la0, lo1, q[1]], [la1, lo0, q[2]], [la1, lo1, q[3]]]} res = {"A1": {}, "A2": {}, "A3": {}, "A4": {}, "A4h": {}, "A5": {}, "B": {}} for s, (la, lo) in SITES.items(): v, nodes = bilinear(la, lo) res["A1"][s] = {"lat": la, "lon": lo, "Rc_grid_2015_GV": round(v, 2), **nodes} for s, (la, lo, pub) in CHECK.items(): v, nodes = bilinear(la, lo) res["A1"][s] = {"lat": la, "lon": lo, "Rc_grid_2015_GV": round(v, 2), "NMDB_2020_GV": pub, "diff_GV": round(v - pub, 2), **nodes} # rough Stormer from IGRF-14 dipole terms interpolated to 2024.36 igrf = open(os.path.join(DL, "igrf", "igrf14coeffs.txt"), encoding="utf-8").read().splitlines() hdr = [l for l in igrf if l.startswith("g/h")][0].split() years = hdr[3:] coef = {} for l in igrf: p = l.split() if p and p[0] in ("g", "h") and p[1] == "1" and p[2] in ("0", "1"): coef[(p[0], int(p[1]), int(p[2]))] = p[3:] i20 = years.index("2020.0") i25 = years.index("2025.0") tfrac = (2024.36 - 2020.0) / 5.0 dip = {} for k, vals in coef.items(): dip[k] = float(vals[i20]) + tfrac * (float(vals[i25]) - float(vals[i20])) g10, g11, h11 = dip[("g", 1, 0)], dip[("g", 1, 1)], dip[("h", 1, 1)] B0 = math.sqrt(g10 ** 2 + g11 ** 2 + h11 ** 2) * 1e-9 # T RE = 6371.2e3 M = 4 * math.pi * RE ** 3 * B0 / (4e-7 * math.pi) C = 4e-7 * math.pi * M * 299792458.0 / (4 * math.pi * RE ** 2) / 1e9 # GV # dipole north pole (geographic) from the coefficients theta0 = math.acos(-g10 / math.sqrt(g10 ** 2 + g11 ** 2 + h11 ** 2)) phi0 = math.atan2(-h11, -g11) pole_lat, pole_lon = 90 - math.degrees(theta0), math.degrees(phi0) res["A1"]["stormer_note"] = {"g10": round(g10, 1), "g11": round(g11, 1), "h11": round(h11, 1), "B0_nT": round(B0 * 1e9, 1), "M_Am2": f"{M:.3e}", "C_St_GV": round(C, 2), "vertical_equator_GV": round(C / 4, 2), "dipole_pole_lat": round(pole_lat, 2), "dipole_pole_lon": round(pole_lon, 2)} for s in list(SITES) + list(CHECK): la, lo = (SITES.get(s) or CHECK[s][:2]) # dipole latitude via spherical trig sl = math.sin(math.radians(la)) * math.sin(math.radians(pole_lat)) + math.cos(math.radians(la)) * math.cos( math.radians(pole_lat)) * math.cos(math.radians(lo - pole_lon)) lam = math.degrees(math.asin(sl)) res["A1"][s]["dipole_lat_deg"] = round(lam, 2) res["A1"][s]["Rc_stormer_rough_GV"] = round(C / 4 * math.cos(math.radians(lam)) ** 4, 2) # ---------------- A2: rigidities ---------------- def rig(T): return math.sqrt(T * T + 2 * T * MP) / 1000.0 def tke(R): return math.sqrt((1000 * R) ** 2 + MP ** 2) - MP res["A2"]["proton_rigidity_GV"] = {f"{T} MeV": round(rig(T), 3) for T in (10, 50, 100, 275, 433, 500, 1600)} for s in SITES: Rc = res["A1"][s]["Rc_grid_2015_GV"] res["A2"][s] = {"Rc_GV": Rc, "min_proton_kinetic_energy_GeV": round(tke(Rc) / 1000, 2), "ratio_Rc_to_100MeV_rigidity": round(Rc / rig(100), 1), "ratio_Rc_to_2.4GV": round(Rc / 2.4, 1)} # ---------------- A3: generous bound ---------------- for frac in (0.57, 0.50): res["A3"][f"cut_{round(frac*100)}pct"] ={s: round(res["A1"][s]["Rc_grid_2015_GV"] * (1 - frac), 2) for s in SITES} # ---------------- A4 / A4h: NMDB ---------------- ROW = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2});\s*([-+\d.eE]+|null|NaN)?\s*$") def read_nmdb(path): ts, vs = [], [] for line in open(path, encoding="utf-8", errors="replace"): m = ROW.match(line.strip()) if m: ts.append(pd.Timestamp(m.group(1))) try: vs.append(float(m.group(2))) except (TypeError, ValueError): vs.append(np.nan) if not ts: return None return pd.Series(vs, index=pd.DatetimeIndex(ts)).sort_index() STATIONS = [("DOMC", 0.01), ("SOPO", 0.10), ("OULU", 0.81), ("KIEL2", 2.36), ("NEWK", 2.40), ("LMKS", 3.84), ("JUNG1", 4.49), ("AATB", 5.90), ("ROME", 6.27), ("MXCO", 8.28), ("ATHN", 8.53), ("DJON", 11.20), ("PSNM", 16.80)] def stat_5min(s, t0): """B over [t0, t0+90m); W over [t0+90m, t0+360m); max 30-min running mean inside W.""" b = s[t0: t0 + pd.Timedelta(minutes=85)] w = s[t0 + pd.Timedelta(minutes=90): t0 + pd.Timedelta(minutes=355)] if len(b) < 18 or len(w) < 54 or b.isna().any() or w.isna().any(): return np.nan run = w.rolling(6).mean().dropna() return 100 * (run.max() - b.mean()) / b.mean() def stat_1h(s, t0): b = s.get(t0, np.nan) w = s[t0 + pd.Timedelta(hours=1): t0 + pd.Timedelta(hours=5)] if np.isnan(b) or len(w) < 5 or w.isna().any(): return np.nan return 100 * (w.max() - b) / b for name, rc in STATIONS: for kind, fn, step, store in (("5min", stat_5min, "30min", "A4"), ("1h", stat_1h, "1h", "A4h")): path = os.path.join(DL, "nmdb", f"nmdb_{name}_20240501_16_{kind}.html") s = read_nmdb(path) if os.path.exists(path) else None if s is None or s.dropna().empty: res[store][name] = {"Rc_GV": rc, "result": "no data"} continue day = s["2024-05-11 00:00":"2024-05-11 05:59"] exp = 72 if kind == "5min" else 6 if day.notna().sum() < 0.8 * exp: res[store][name] = {"Rc_GV": rc, "result": "no data (gaps on 11 May)"} continue null = [] for t0 in pd.date_range("2024-05-01 00:00", "2024-05-07 18:00", freq=step): v = fn(s, t0) if not np.isnan(v): null.append(v) null = np.array(null) i11 = fn(s, pd.Timestamp("2024-05-11 00:00")) p99 = float(np.percentile(null, 99)) if len(null) else np.nan res[store][name] = {"Rc_GV": rc, "I_11May_pct": round(i11, 2), "null_n": int(len(null)), "null_p99_pct": round(p99, 2), "null_max_pct": round(float(null.max()), 2) if len(null) else None, "registered": bool(i11 > p99) if not np.isnan(i11) else None, "I_10May_pct": round(fn(s, pd.Timestamp("2024-05-10 00:00")), 2), "I_12May_pct": round(fn(s, pd.Timestamp("2024-05-12 00:00")), 2)} # ---------------- A5: order-of-magnitude SEP share ---------------- for s in SITES: out = {} for lab, Rc in (("quiet", res["A1"][s]["Rc_grid_2015_GV"]), ("bound57", res["A3"]["cut_57pct"][s])): K = Rc ** -4 / Rc ** -1.7 out[lab] = {"Rc_GV": Rc, "K": f"{K:.2e}", "SEP_share_upper_pct": f"{10 * K:.1e}"} res["A5"][s] = out # ---------------- B1: OMNI ---------------- om = pd.read_csv(os.path.join(DL, "omni", "OMNI_HRO_1MIN_20240509_15.csv"), header=None, names=["t", "B", "Bz", "V", "N", "P", "E", "SYMH"]) om["t"] = pd.to_datetime(om["t"].str.replace("Z", "")) om = om.set_index("t") fills = {"B": 9999.99, "Bz": 9999.99, "V": 99999.9, "N": 999.99, "P": 99.99, "E": 999.99} for c, f in fills.items(): om.loc[om[c] >= f * 0.999, c] = np.nan pre = om.loc["2024-05-10 16:00":"2024-05-10 16:29", "P"].mean() shock = None cand = om.loc["2024-05-10 16:30":"2024-05-10 20:00", "P"] for t in cand.index: w = om.loc[t: t + pd.Timedelta(minutes=4), "P"] if len(w.dropna()) == 5 and (w > 2 * pre).all(): shock = t break win = om.loc["2024-05-10 16:00":"2024-05-11 23:59"] hourly = win.resample("1h").mean() b1 = {"P_pre_nPa": round(pre, 2), "shock_minute": str(shock)} if shock is not None: bef = om.loc[shock - pd.Timedelta(minutes=10): shock - pd.Timedelta(minutes=1)] aft = om.loc[shock + pd.Timedelta(minutes=1): shock + pd.Timedelta(minutes=10)] b1.update({"dB_nT": round(aft.B.mean() - bef.B.mean(), 1), "dV_kms": round(aft.V.mean() - bef.V.mean(), 0), "dP_nPa": round(aft.P.mean() - bef.P.mean(), 2)}) for c, f in (("B", "max"), ("Bz", "min"), ("V", "max"), ("P", "max")): s1 = win[c] idx = s1.idxmax() if f == "max" else s1.idxmin() sh = hourly[c] idh = sh.idxmax() if f == "max" else sh.idxmin() b1[f"{c}_{f}_1min"] = [round(float(s1[idx]), 1), str(idx)] b1[f"{c}_{f}_hourly"] = [round(float(sh[idh]), 1), str(idh)] res["B"]["B1_omni"] = b1 # ---------------- B2/B3: SYM-H, Dst ---------------- sy = pd.read_csv(os.path.join(DL, "kyoto", "symh_20240510T12_20240512T12.csv"), header=None, names=["t", "v", "code"]) sy["t"] = pd.to_datetime(sy["t"].str.replace("Z", "")) sy = sy.set_index("t") imin = sy.v.idxmin() pk = sy.loc["2024-05-10 16:00":imin, "v"] res["B"]["B2_symh"] = {"min_nT": int(sy.v.min()), "min_time": str(imin), "peak_before_nT": int(pk.max()), "peak_time": str(pk.idxmax()), "version_codes": sorted(set(int(x) for x in sy.code.unique()))} ds = pd.read_csv(os.path.join(DL, "kyoto", "hour_dst_20240508_16.csv"), header=None, names=["t", "v", "code"]) ds["t"] = pd.to_datetime(ds["t"].str.replace("Z", "")) ds = ds.set_index("t") dmin_t = ds.v.idxmin() after = ds.loc[dmin_t:] first_above = after[after.v > -100].index[0] res["B"]["B3_dst"] = {"min_nT": int(ds.v.min()), "min_bin_centre": str(dmin_t), "shock_hour_value": int(ds.loc["2024-05-10 17:00":"2024-05-10 17:59"].v.iloc[0]), "first_bin_after_min_above_-100": str(first_above), "value_there": int(after.loc[first_above, "v"]), "version_codes": sorted(set(int(x) for x in ds.code.unique()))} # ---------------- B4: Kp ---------------- kp = json.load(open(os.path.join(DL, "gfz", "kp_2024-05-08_16_def.json"), encoding="utf-8")) ap = json.load(open(os.path.join(DL, "gfz", "Ap_2024-05-08_16_def.json"), encoding="utf-8")) def kp_str(x): n = round(x * 3) base, r = divmod(n, 3) return {0: f"{base}o", 1: f"{base}+", 2: f"{base + 1}-"}[r] kps = [(t, v, kp_str(v)) for t, v in zip(kp["datetime"], kp["Kp"]) if "2024-05-10" <= t[:10] <= "2024-05-13"] mx = max(v for _, v, _ in kps) res["B"]["B4_kp"] = {"values": [[t, s] for t, _, s in kps], "max": kp_str(mx), "max_intervals": [t for t, v, _ in kps if v == mx], "daily_Ap": dict(zip([d[:10] for d in ap["datetime"]], ap["Ap"])), "status": sorted(set(kp["status"]))} # ---------------- B5: GOES-16 SGPS ---------------- import netCDF4 # noqa: E402 frames = [] for d in ("09", "10", "11", "12", "13"): p = os.path.join(DL, "goes", "g16_sgps_avg5m", f"sci_sgps-l2-avg5m_g16_d202405{d}_v3-0-2.nc") nc = netCDF4.Dataset(p) t = netCDF4.num2date(nc["time"][:], nc["time"].units, only_use_cftime_datetimes=False) diff = np.ma.filled(nc["AvgDiffProtonFlux"][:].astype(float), np.nan) # (time, unit, chan) lo = np.array(nc["DiffProtonLowerEnergy"][:], dtype=float) # keV (unit, chan) hi = np.array(nc["DiffProtonUpperEnergy"][:], dtype=float) p11 = np.ma.filled(nc["AvgIntProtonFlux"][:].astype(float), np.nan) # (time, unit) nc.close() for u in (0, 1): rec = {"t": pd.to_datetime([str(x) for x in t]), "unit": u, "P11": p11[:, u]} for thr in (10, 50, 100): thr_kev = thr * 1000.0 tot = np.zeros(len(t)) for c in range(diff.shape[2]): a, b = lo[u, c], hi[u, c] if b <= thr_kev or a <= 0: continue width = b - max(a, thr_kev) tot = tot + np.where(np.isnan(diff[:, u, c]), np.nan, diff[:, u, c] * width) rec[f"gt{thr}"] = tot frames.append(pd.DataFrame(rec)) g = pd.concat(frames) g.loc[g["P11"] < -1e20, "P11"] = np.nan b5 = {"channel_edges_keV_unit0": [[float(a), float(b)] for a, b in zip(lo[0], hi[0])]} for u in (0, 1): gu = g[g.unit == u].set_index("t").sort_index() d10 = gu.loc["2024-05-10"] d11 = gu.loc["2024-05-11"] out = {} for col in ("gt10", "gt50", "gt100", "P11"): out[col] = {"max_10May": [float(f"{d10[col].max():.3g}"), str(d10[col].idxmax())], "max_11May": [float(f"{d11[col].max():.3g}"), str(d11[col].idxmax())]} base = d11.loc["2024-05-11 00:00":"2024-05-11 00:55", "gt100"].mean() on = None v = d11["gt100"] for i in range(len(v) - 2): if (v.iloc[i:i + 3] > 1.5 * base).all(): on = str(v.index[i]) break out["onset_gt100_11May"] = on out["gt100_base_00_01UT"] = float(f"{base:.3g}") # local maxima on 11 May after 03 UT for >10 MeV late = d11.loc["2024-05-11 03:00":"2024-05-11 23:55", "gt10"] out["gt10_max_after_03UT"] = [float(f"{late.max():.3g}"), str(late.idxmax())] b5[f"unit{u}"] = out res["B"]["B5_goes16"] = b5 # ---------------- B6: Forbush decreases ---------------- b6 = {} for name in ("OULU", "DOMC", "SOPO", "PSNM", "MXCO", "ROME", "AATB", "JUNG1", "NEWK"): for kind in ("5min", "1h"): path = os.path.join(DL, "nmdb", f"nmdb_{name}_20240501_16_{kind}.html") if not os.path.exists(path): continue s = read_nmdb(path) if s is None or s.dropna().empty: continue h = s.resample("1h").mean() base = h["2024-05-08 17:00":"2024-05-10 16:59"].mean() seg = h["2024-05-10 17:00":"2024-05-11 23:59"] rec = {"baseline": round(float(base), 3), "FD_hourly_pct": round(100 * (seg.min() - base) / base, 2), "FD_hour": str(seg.idxmin())} if kind == "5min": seg5 = s["2024-05-10 17:00":"2024-05-11 23:59"] rec["FD_5min_pct"] = round(100 * (seg5.min() - base) / base, 2) rec["FD_5min_time"] = str(seg5.idxmin()) b6[f"{name}_{kind}"] = rec res["B"]["B6_fd"] = b6 json.dump(res, open(os.path.join(OUT, "AB_results.json"), "w", encoding="utf-8", newline="\n"), indent=1, default=str) print(json.dumps(res, indent=1, default=str))