#!/usr/bin/env python3 """POST HOC, DESCRIPTIVE numbers for may-2024-dc-ac-circuit (not tests; not pre-registered; written after the pre-registered runs). Each item answers a question the pre-registered results raised; none changes a decision. Usage: python3 -I descriptive_post_hoc.py SUPPLIED_PDF DOWNLOADS_DIR OUT_DIR (needs pandas; uses pdf_vector.py beside it) 1. From the paper's Fig. 3 (digitised): hourly means at KAK and CHF on 9-11 May (UT), and same-hours (00-16 UT) means for 9-12 May, because the paper's "12 May" values cover only 00:00-16:05 UT. 1b. (added 2026-11-15, wave 2) The lowest and highest value of each Fig. 3 curve on each UT day, 9-12 May, beside the paper's Table 2 (diurnal minimum and maximum, V/m), for the comparison on the page. 2. Neutron monitor count rates (PSNM 16.8 GV, MXCO 8.3 GV, SOPO 0.1 GV), hourly, in % of their 7-9 May means, beside Kyoto's provisional hourly Dst, 10 May 15 UT - 11 May 12 UT. 3. Wind at the airports nearest CHF (RJTF) and KAK (RJAH) by UT day, 9-12 May: vector-mean direction, mean speed and the number of reports above 8 m/s. 4. GOES-16 approximate integral proton fluxes (as in ab_storm_cutoffs.py) in 30-min means on 11 May. """ import csv import json import math import os import re import sys import numpy as np import pandas as pd sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import pdf_objects as po # noqa: E402 import pdf_vector as pv # noqa: E402 sys.stdout.reconfigure(encoding="utf-8") PDF, DL, OUT = sys.argv[1], sys.argv[2], sys.argv[3] res = {"note": "post hoc, descriptive; not pre-registered tests"} # 1. Fig. 3 E = json.load(open(os.path.join(OUT, "E_figures.json"), encoding="utf-8")) # The paper's Table 2, diurnal minimum and maximum (V/m) for 9, 10, 11 and 12 May, as printed (preprint p. 11) TABLE2 = {"KAK": {"min": [20, 12, 35, 20], "max": [70, 70, 85, 70]}, "CHF": {"min": [10, 53, 80, 69], "max": [170, 196, 200, 127]}} def lin(p): n = len(p) mx = sum(a for a, _ in p) / n my = sum(b for _, b in p) / n b = sum((a - mx) * (c - my) for a, c in p) / sum((a - mx) ** 2 for a, _ in p) return my - b * mx, b data, objs, parsed = po.read_pdf(PDF) r = pv.Renderer(parsed, objs) r.run_form(147, [1, 0, 0, 1, 0, 0]) xa = lin(E["fig3_xaxis"]["pairs"]) for name, box in (("KAK", E["fig3_frames"][1]), ("CHF", E["fig3_frames"][0])): ya = lin(E["fig3_" + name]["left_axis"]["pairs"]) pts = [] for p in r.paths: if p["stroke"] == [1.0, 0.0, 0.0] and len(p["pts"]) > 20 and sum(1 for q in p["pts"] if box[1] - 1 <= q[1] <= box[3] + 1) > 0.5 * len(p["pts"]): pts += [(xa[0] + xa[1] * x, ya[0] + ya[1] * y) for x, y in p["pts"]] hrs = {} for t, v in pts: d = int(t) h = int((t - d) * 24 + 1e-9) hrs.setdefault((d, h), []).append(v) table = {} for h in range(24): a = [round(sum(hrs[(d, h)]) / len(hrs[(d, h)]), 1) if (d, h) in hrs else None for d in (9, 10, 11)] ex = round(a[2] - (a[0] + a[1]) / 2, 1) if None not in a else None table[f"{h:02d}"] = {"9May": a[0], "10May": a[1], "11May": a[2], "excess_11_vs_mean_9_10": ex} same = {} for d in (9, 10, 11, 12): v = [val for t, val in pts if d <= t < d + 16 / 24] same[str(d)] = round(sum(v) / len(v), 1) mm = {} for d in (9, 10, 11, 12): day = [(t, val) for t, val in pts if d <= t < d + 1] lo = min(day, key=lambda q: q[1]) hi = max(day, key=lambda q: q[1]) mm[str(d)] = {"min": round(lo[1], 1), "min_UT_h": round((lo[0] - d) * 24, 2), "max": round(hi[1], 1), "max_UT_h": round((hi[0] - d) * 24, 2)} res[f"fig3_{name}_daily_min_max"] = {"figure": mm, "table2_paper": TABLE2[name]} res[f"fig3_{name}"] = {"hourly_UT": table, "same_hours_00_16UT_means": same, "11_vs_mean_9_10_pct": round(100 * (same["11"] / ((same["9"] + same["10"]) / 2) - 1), 1), "12_vs_11_pct": round(100 * (same["12"] / same["11"] - 1), 1), "10_vs_9_pct": round(100 * (same["10"] / same["9"] - 1), 1)} # 2. NM vs Dst ROW = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2});\s*([-+\d.eE]+)") def rd(p): ts, vs = [], [] for l in open(p, encoding="utf-8", errors="replace"): m = ROW.match(l.strip()) if m: ts.append(pd.Timestamp(m.group(1))) vs.append(float(m.group(2))) return pd.Series(vs, index=ts) ds = pd.read_csv(os.path.join(DL, "kyoto", "hour_dst_20240508_16.csv"), header=None, names=["t", "v", "c"]) ds["t"] = pd.to_datetime(ds["t"].str.replace("Z", "")) - pd.Timedelta(minutes=29, seconds=30) ds = ds.set_index("t").v cols = {"Dst_nT": ds} for st in ("PSNM", "MXCO", "SOPO"): s = rd(os.path.join(DL, "nmdb", f"nmdb_{st}_20240501_16_1h.html")) cols[f"{st}_pct"] = 100 * (s / s["2024-05-07":"2024-05-09"].mean() - 1) df = pd.DataFrame(cols).loc["2024-05-10 15:00":"2024-05-11 12:00"].round(2) res["nm_vs_dst_hourly"] = {str(k): v for k, v in df.to_dict(orient="index").items()} # 2b. every NM on 11 May relative to its 7-9 May mean (hourly table "1h") below = {} for st in ("PSNM", "MXCO", "AATB", "ROME", "JUNG1", "NEWK", "OULU", "SOPO", "DOMC"): s = rd(os.path.join(DL, "nmdb", f"nmdb_{st}_20240501_16_1h.html")) if s.empty: continue pc = 100 * (s / s["2024-05-07":"2024-05-09"].mean() - 1) d = pc["2024-05-11 00:00":"2024-05-11 23:00"] below[st] = {"min_pct": round(float(d.min()), 2), "min_hour_UT": f"{d.idxmin():%H}", "max_pct": round(float(d.max()), 2), "max_hour_UT": f"{d.idxmax():%H}", "hours_above_0": int((d > 0).sum()), "hours": int(d.notna().sum())} res["nm_11May_vs_7_9May"] = below # 3. winds wind = {} for st in ("RJTF", "RJAH"): for day in ("2024-05-09", "2024-05-10", "2024-05-11", "2024-05-12"): u = v = 0.0 n = 0 sp = [] for row in csv.DictReader(open(os.path.join(DL, "iem", "japan", f"{st}_202405.csv"), encoding="utf-8")): if row["valid"][:10] != day or row["drct"] in ("M", "") or row["sknt"] in ("M", ""): continue dd, s = float(row["drct"]), float(row["sknt"]) * 0.5144 u += -s * math.sin(math.radians(dd)) v += -s * math.cos(math.radians(dd)) n += 1 sp.append(s) if n: wind[f"{st} {day}"] = {"n": n, "vector_mean_dir_deg": round((math.degrees(math.atan2(-u / n, -v / n)) + 360) % 360), "mean_speed_ms": round(sum(sp) / n, 1), "n_above_8ms": sum(1 for s in sp if s > 8)} res["japan_wind"] = wind # 4. GOES 30-min on 11 May import netCDF4 # noqa: E402 p = os.path.join(DL, "goes", "g16_sgps_avg5m", "sci_sgps-l2-avg5m_g16_d20240511_v3-0-2.nc") nc = netCDF4.Dataset(p) t = pd.to_datetime([str(x) for x in netCDF4.num2date(nc["time"][:], nc["time"].units, only_use_cftime_datetimes=False)]) diff = np.ma.filled(nc["AvgDiffProtonFlux"][:].astype(float), np.nan) lo = np.array(nc["DiffProtonLowerEnergy"][:]) hi = np.array(nc["DiffProtonUpperEnergy"][:]) p11 = np.ma.filled(nc["AvgIntProtonFlux"][:].astype(float), np.nan) nc.close() rows = {} for u in (0, 1): for thr in (10, 50, 100): tot = np.zeros(len(t)) for c in range(diff.shape[2]): a, b = lo[u, c], hi[u, c] if b <= thr * 1000: continue tot = tot + diff[:, u, c] * (b - max(a, thr * 1000)) rows[f"unit{u}_gt{thr}"] = tot rows[f"unit{u}_P11"] = p11[:, u] g = pd.DataFrame(rows, index=t).resample("30min").mean().round(3) res["goes16_30min_11May"] = {str(k): v for k, v in g.to_dict(orient="index").items()} json.dump(res, open(os.path.join(OUT, "descriptive_post_hoc.json"), "w", encoding="utf-8", newline="\n"), indent=1, default=str) for k in ("fig3_KAK", "fig3_CHF"): print(k, res[k]["same_hours_00_16UT_means"], res[k]["11_vs_mean_9_10_pct"], res[k]["12_vs_11_pct"], res[k]["10_vs_9_pct"]) print(json.dumps(res["japan_wind"]))