#!/usr/bin/env python3 """Independent check for march-2023-storm: the recovery measures of RULES_recovery.txt (amendment 2) on DTU Space's RC index instead of Kyoto's Dst. Fact-Checked Science, "Our analysis". Standard library only. Run: python3 -I -X utf8 rc_check.py RULES_recovery.txt RC_FILE OUT_FOLDER RC_FILE RC_1997-2026_Sept26_v4_allLT.dat, part of the CHAOS-8.7 release (DTU Space, CC BY 4.0; Olsen et al. 2014, Geophys. J. Int. 197, 815-827). Hourly; MJD2000 gives the middle of each hour. """ import datetime as dt import json import os import statistics import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from storm_rank import sha, iso # our own modules, same folder from dst_recovery import recovery, percentile, hours, H, DAY UTC = dt.timezone.utc def read_rc(path): out, flags = {}, {} t0 = dt.datetime(2000, 1, 1) for line in open(path, encoding="ascii", errors="replace"): if line.startswith("#") or not line.strip(): continue f = line.split() mjd, rc, flag = float(f[0]), float(f[1]), f[4] t = t0 + dt.timedelta(days=mjd) - dt.timedelta(minutes=30) t = (t + dt.timedelta(seconds=30)).replace(second=0, microsecond=0) # round to the minute if t.minute != 0: raise SystemExit("unexpected time stamp: " + line) flags[flag] = flags.get(flag, 0) + 1 out[t] = rc return out, flags def main(): rules, rc_path, outdir = sys.argv[1:4] log = [] def say(*a): s = " ".join(str(x) for x in a) print(s) log.append(s) say("rc_check.py run at", dt.datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")) say("rules ", sha(rules), os.path.basename(rules)) say("RC ", sha(rc_path), os.path.basename(rc_path)) rc_all, flags = read_rc(rc_path) say("hours:", len(rc_all), iso(min(rc_all)), "to", iso(max(rc_all)), "flags:", flags) rc = {t: v for t, v in rc_all.items() if t >= dt.datetime(2017, 1, 1)} # completeness from 2017 on t, missing = dt.datetime(2017, 1, 1), 0 last = max(rc) while t <= last: if t not in rc: missing += 1 t += H say("missing hours since 2017-01-01:", missing) if missing: raise SystemExit("gaps in RC: the placebo needs handling of missing hours") onset, S1 = dt.datetime(2023, 3, 23), dt.datetime(2023, 3, 26) r = recovery(rc, onset, onset, S1, last) B = r["B_median_27d"] post = hours(rc, dt.datetime(2023, 3, 31), dt.datetime(2023, 4, 23)) R5 = statistics.median(post) - B out = {"what": "The recovery measures on DTU's RC index (factchecked.science, Our analysis; RULES_recovery.txt, amendment 2)", "storm": {k: (round(v, 2) if isinstance(v, float) else v) for k, v in r.items() if not k.startswith("_")}} out["storm"]["post_median_31Mar_22Apr"] = round(statistics.median(post), 2) out["storm"]["R5_offset"] = round(R5, 2) say("\nTHE STORM on RC") say(json.dumps(out["storm"])) plac, d = [], dt.datetime(2017, 4, 19) while d <= dt.datetime(2023, 2, 19): plac.append(statistics.median(hours(rc, d + 8 * DAY, d + 31 * DAY)) - statistics.median(hours(rc, d - 27 * DAY, d))) d += DAY ps = sorted(plac) p025, p975 = percentile(ps, 2.5), percentile(ps, 97.5) below = sum(1 for v in ps if v < R5) out["R5_placebo"] = {"n_days": len(ps), "p2.5": round(p025, 2), "median": round(percentile(ps, 50), 2), "p97.5": round(p975, 2), "storm_R5": round(R5, 2), "storm_percentile": round(100.0 * below / len(ps), 1), "inside_central_95": p025 <= R5 <= p975} say("R5 against the placebo:", json.dumps(out["R5_placebo"])) # lowest RC of W6 against the storm's w6 = [(v, t) for t, v in rc.items() if dt.datetime(2017, 3, 23) <= t < onset] lo = min(w6) storm_min = r["min"] deeper = sorted([(v, t) for v, t in w6 if v <= storm_min]) # group the deeper hours by day days = {} for v, t in deeper: days.setdefault(t.date().isoformat(), []).append(v) out["W6_lowest_RC"] = {"value": round(lo[0], 1), "hour_start": iso(lo[1]), "storm_min": round(storm_min, 1), "days_with_RC_at_or_below_storm_min": {k: round(min(v), 1) for k, v in days.items()}} say("W6 lowest RC:", json.dumps(out["W6_lowest_RC"])) dm = {} d = dt.datetime(2023, 3, 18) while d < dt.datetime(2023, 4, 6): dm[d.date().isoformat()] = round(statistics.fmean(hours(rc, d, d + DAY)), 1) d += DAY out["daily_mean_RC_18Mar_5Apr"] = dm say("daily mean RC:", dm) with open(os.path.join(outdir, "rc_check.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, "rc_check.log"), "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(log) + "\n") if __name__ == "__main__": main()