#!/usr/bin/env python3 """Analysis (b), part 1, for march-2023-storm: did Dst return to its pre-storm level? Fact-Checked Science, "Our analysis". Standard library only. Follows RULES_recovery.txt (pre-registered). Run: python3 -I -X utf8 dst_recovery.py RULES_recovery.txt KYOTO_FOLDER OUT_FOLDER Reads KYOTO_FOLDER/dst_final_YYYYMM.html and dst_provisional_YYYYMM.html as data (no real-time month). Writes OUT_FOLDER/dst_recovery.json and dst_recovery.log (with SHA-256 of the rules and inputs). Kyoto's Dst: final and provisional values, for scientific, non-commercial use, with acknowledgement of the World Data Center for Geomagnetism, Kyoto, and of the observatories that supply the data. """ import datetime as dt import glob import hashlib import json import math import os import statistics import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from storm_rank import read_kyoto, dst_storms, sha, iso # our own module, same folder UTC = dt.timezone.utc H = dt.timedelta(hours=1) DAY = dt.timedelta(days=1) def hours(dst, lo, hi): out, t = [], lo while t < hi: out.append(dst[t]) t += H return out def percentile(sorted_vals, q): """Linear-interpolation percentile, q in 0..100.""" if not sorted_vals: return None k = (len(sorted_vals) - 1) * q / 100.0 f, c = math.floor(k), math.ceil(k) if f == c: return sorted_vals[int(k)] return sorted_vals[f] + (sorted_vals[c] - sorted_vals[f]) * (k - f) def recovery(dst, onset_day, lo_min, hi_min, last): """R1-R4 for a storm with onset day `onset_day` and minimum inside [lo_min, hi_min).""" base_lo = onset_day - 27 * DAY if base_lo not in dst: return None B = statistics.median(hours(dst, base_lo, onset_day)) cand = [(dst[t], t) for t in (lo_min + i * H for i in range(int((hi_min - lo_min) / H))) if t in dst] vmin = min(v for v, t in cand) tmin = min(t for v, t in cand if v == vmin) D = B - vmin def first_hour(level): t = tmin + H while t <= last: if dst[t] >= level: return t t += H return None t1, t2 = first_hour(B - D / math.e), first_hour(B - D / 2.0) def first_day(level): d = dt.datetime(tmin.year, tmin.month, tmin.day) + DAY while d + DAY - H <= last: if statistics.fmean(hours(dst, d, d + DAY)) >= level: return d d += DAY return None d3, d4 = first_day(B - 0.1 * D), first_day(B) day_min = dt.datetime(tmin.year, tmin.month, tmin.day) return {"onset_day": onset_day.date().isoformat(), "B_median_27d": B, "min": vmin, "t_min_hour_start": iso(tmin), "depth": D, "R1_efold_hours": int((t1 - tmin) / H) if t1 else None, "R2_half_hours": int((t2 - tmin) / H) if t2 else None, "R3_90pct_day": d3.date().isoformat() if d3 else None, "R3_days": (d3 - day_min).days if d3 else None, "R4_full_day": d4.date().isoformat() if d4 else None, "R4_days": (d4 - day_min).days if d4 else None, "_d3": d3, "_tmin": tmin} def main(): rules, kyoto_dir, outdir = sys.argv[1:4] log = [] def say(*a): s = " ".join(str(x) for x in a) print(s) log.append(s) say("dst_recovery.py run at", dt.datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")) say("rules ", sha(rules), os.path.basename(rules)) 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)") dst, status = read_kyoto(kyoto_dir) dst = {t: v for t, v in dst.items() if t >= dt.datetime(2017, 1, 1)} last = max(dst) say("Dst hours read:", iso(min(dst)), "to", iso(last)) onset = dt.datetime(2023, 3, 23) S1 = dt.datetime(2023, 3, 26) r = recovery(dst, onset, onset, S1, last) B, vmin, tmin, D = r["B_median_27d"], r["min"], r["_tmin"], r["depth"] B3 = statistics.fmean(hours(dst, dt.datetime(2023, 3, 20), onset)) # R4 against B3 d = dt.datetime(tmin.year, tmin.month, tmin.day) + DAY d4b = None while d + DAY - H <= last: if statistics.fmean(hours(dst, d, d + DAY)) >= B3: d4b = d break d += DAY post = hours(dst, dt.datetime(2023, 3, 31), dt.datetime(2023, 4, 23)) R5 = statistics.median(post) - B out = {"what": "Recovery of Dst after the storm of 23-24 March 2023 (factchecked.science, Our analysis; RULES_recovery.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 of the observatories that supply the data.", "storm": {k: v for k, v in r.items() if not k.startswith("_")}} out["storm"]["B3_mean_3d"] = round(B3, 2) out["storm"]["R4_full_day_vs_B3"] = d4b.date().isoformat() if d4b else None out["storm"]["R4_days_vs_B3"] = (d4b - dt.datetime(tmin.year, tmin.month, tmin.day)).days if d4b else None out["storm"]["post_median_31Mar_22Apr"] = statistics.median(post) out["storm"]["R5_offset"] = R5 say("\nTHE STORM") say(json.dumps(out["storm"])) # daily means around the storm dm = {} d = dt.datetime(2023, 2, 24) while d < dt.datetime(2023, 4, 23): dm[d.date().isoformat()] = round(statistics.fmean(hours(dst, d, d + DAY)), 1) d += DAY out["daily_mean_dst_2023-02-24_to_2023-04-22"] = dm say("daily mean Dst, 18 March to 5 April:", {k: v for k, v in dm.items() if "2023-03-18" <= k <= "2023-04-05"}) # (The hourly values behind the page's chart are read from Kyoto's pages by charts.py; they are not copied here.) # placebo for R5 plac = [] d = dt.datetime(2017, 4, 19) while d <= dt.datetime(2023, 2, 19): a = statistics.median(hours(dst, d + 8 * DAY, d + 31 * DAY)) b = statistics.median(hours(dst, d - 27 * DAY, d)) plac.append(a - b) d += DAY ps = sorted(plac) p025, p975, p50 = percentile(ps, 2.5), percentile(ps, 97.5), percentile(ps, 50) below = sum(1 for v in ps if v < R5) pct = 100.0 * below / len(ps) inside = p025 <= R5 <= p975 out["R5_placebo"] = {"n_days": len(ps), "p2.5": p025, "median": p50, "p97.5": p975, "min": ps[0], "max": ps[-1], "storm_R5": R5, "storm_percentile": round(pct, 1), "inside_central_95": inside, "result": "passes (no lasting offset beyond the ordinary)" if inside else ("FAILS: below the 2.5th percentile" if R5 < p025 else "above the 97.5th percentile")} say("\nTHE TEST THAT COULD FAIL (R5 against the placebo)") say(json.dumps(out["R5_placebo"])) # second check: three-month means def month_mean(y, m): lo = dt.datetime(y, m, 1) hi = dt.datetime(y + (m == 12), m % 12 + 1, 1) return statistics.fmean(hours(dst, lo, hi)), (hi - lo).days * 24 def three(y, m, step): """Mean over three calendar months starting (step=+1) at (y, m) or ending (step=-1) at (y, m).""" tot, n = 0.0, 0 for k in range(3): mm = m + step * k yy = y + (mm - 1) // 12 mm = (mm - 1) % 12 + 1 mean, hrs = month_mean(yy, mm) tot += mean * hrs n += hrs return tot / n def diff(y, m): """Mean of the three months after month (y, m) minus the mean of the three months before it.""" ya, ma = y + (m == 12), m % 12 + 1 yb, mb = y - (m == 1), (m - 2) % 12 + 1 return three(ya, ma, +1) - three(yb, mb, -1) storm_diff = diff(2023, 3) pl = [] y, m = 2017, 7 while (y, m) <= (2022, 11): pl.append(((y, m), diff(y, m))) m += 1 if m == 13: y, m = y + 1, 1 vals = sorted(v for k, v in pl) q025, q975 = percentile(vals, 2.5), percentile(vals, 97.5) out["three_month_check"] = {"after_AprMayJun_2023": round(three(2023, 4, +1), 2), "before_DecJanFeb": round(three(2023, 2, -1), 2), "storm_difference": round(storm_diff, 2), "n_placebo": len(vals), "p2.5": round(q025, 2), "median": round(percentile(vals, 50), 2), "p97.5": round(q975, 2), "min": round(vals[0], 2), "max": round(vals[-1], 2), "inside_central_95": q025 <= storm_diff <= q975} say("\nSECOND CHECK (three-month means)") say(json.dumps(out["three_month_check"])) # comparison: other storms at -100 nT or below storms = dst_storms(dst, -50, 24) rows = [] for i, s in enumerate(storms): vmin_s = min(v for t, v in s["items"]) if vmin_s > -100: continue t_first = s["items"][0][0] tmin_s = min(t for t, v in s["items"] if v == vmin_s) if not (dt.datetime(2017, 3, 23) <= tmin_s): continue od = dt.datetime(t_first.year, t_first.month, t_first.day) rr = recovery(dst, od, s["items"][0][0], s["items"][-1][0] + H, last) if rr is None: continue nxt = storms[i + 1]["items"][0][0] if i + 1 < len(storms) else None cut = bool(nxt and (rr["_d3"] is None or nxt < rr["_d3"])) row = {k: v for k, v in rr.items() if not k.startswith("_")} row["next_storm_begins"] = iso(nxt) if nxt else None row["cut_short_by_next_storm"] = cut rows.append(row) out["storms_at_minus100_or_below"] = rows say("\nCOMPARISON: storms at -100 nT or below since 23 March 2017 (24-h joining)") say("min_hour min B R1(h) R2(h) R3(d) R4(d) cut short?") for row in rows: say(f"{row['t_min_hour_start']} {row['min']:5d} {row['B_median_27d']:5.1f} {str(row['R1_efold_hours']):>5} " f"{str(row['R2_half_hours']):>5} {str(row['R3_days']):>5} {str(row['R4_days']):>5} {'yes' if row['cut_short_by_next_storm'] else 'no'}") clean = [row for row in rows if not row["cut_short_by_next_storm"]] def med(key, rs): v = [row[key] for row in rs if row[key] is not None] return statistics.median(v) if v else None out["comparison_summary"] = { "n_storms": len(rows), "n_not_cut_short": len(clean), "median_R1_all": med("R1_efold_hours", rows), "median_R2_all": med("R2_half_hours", rows), "median_R3_days_all": med("R3_days", rows), "median_R3_days_not_cut": med("R3_days", clean), "median_R4_days_all": med("R4_days", rows), "median_R4_days_not_cut": med("R4_days", clean), "range_R1_all": [min(row["R1_efold_hours"] for row in rows), max(row["R1_efold_hours"] for row in rows)]} say(json.dumps(out["comparison_summary"])) with open(os.path.join(outdir, "dst_recovery.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, "dst_recovery.log"), "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(log) + "\n") if __name__ == "__main__": main()