"""RULES_meped.txt: the belt rule of RULES_belts.txt (method A, imported from belts_a.py) applied to NOAA's MEPED data. Fact-Checked Science ("Our analysis"), 16 November 2026, for the check of Pierrard et al. (2026), npj Space Exploration 2, 43 (doi:10.1038/s44453-026-00064-7). What it does Bins the >300 keV electron channel of MEPED's 90-degree telescope (NOAA POES/MetOp SEM-2, NOAA NCEI, public domain) into 6-hour x 0.1-L cells, as in the authors' own MEPED file, then applies method A of RULES_belts.txt to: the positive controls (MetOp-C and NOAA-15, May-June 2024) and the pre-registered NOAA-15 windows after every storm at or below -250 nT from 1998 to 2023 plus the two of 2015. For each window and its pre-storm baseline it reports the longest run of days with a split outer zone (two or more persistent slots at L >= 2.0, statistic S1) and with three or more and four or more belts anywhere (S2), under the pre-registered settings and setting X1 (no smoothing). For the MetOp-C control it also compares our daily profiles with the authors' MEPED file (check C1c). Needs Python 3.9+, numpy, scipy, netCDF4 (with cftime), and belts_a.py in the same folder as this script. Run python3 meped_test.py (fetch_inputs.py --meped saves the NOAA files in /meped/metop03, .../noaa15_proc, .../noaa15_txt; the authors' file poes_e90_6hav_0.1l_2024_may_jun.nc is in /bira/.) Writes, in the output folder meped_test_summary.json, meped_daily__.csv, and the 6-hour x 0.1-L bins as meped_bins_.npz (read by meped_robust.py). """ import csv import datetime as dt import json import os import sys import warnings import numpy as np import netCDF4 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import belts_a as A # noqa: E402 (our own method-A code) warnings.simplefilter("ignore", RuntimeWarning) LE = np.round(np.arange(1.0, 10.0001, 0.1), 4) LC = (LE[:-1] + LE[1:]) / 2 D = dt.date CASES = [ # name, satellite product, file period, window, baseline ("control_metop03_2024", "m03", (D(2024, 5, 1), D(2024, 6, 25)), (D(2024, 5, 11), D(2024, 6, 25)), (D(2024, 5, 1), D(2024, 5, 9))), ("control_noaa15_2024", "n15proc", (D(2024, 5, 1), D(2024, 6, 25)), (D(2024, 5, 11), D(2024, 6, 25)), (D(2024, 5, 1), D(2024, 5, 9))), ("W1_2000-04", "n15txt", (D(2000, 3, 28), D(2000, 5, 22)), (D(2000, 4, 8), D(2000, 5, 22)), (D(2000, 3, 28), D(2000, 4, 6))), ("W2_2000-07", "n15txt", (D(2000, 7, 5), D(2000, 8, 30)), (D(2000, 7, 16), D(2000, 8, 30)), (D(2000, 7, 5), D(2000, 7, 14))), ("W3_2001-03", "n15txt", (D(2001, 3, 20), D(2001, 5, 26)), (D(2001, 3, 31), D(2001, 5, 26)), (D(2001, 3, 20), D(2001, 3, 29))), ("W4_2001-11", "n15txt", (D(2001, 10, 26), D(2001, 12, 21)), (D(2001, 11, 6), D(2001, 12, 21)), (D(2001, 10, 26), D(2001, 11, 4))), ("W5_2003-10", "n15txt", (D(2003, 10, 18), D(2004, 1, 4)), (D(2003, 10, 30), D(2004, 1, 4)), (D(2003, 10, 18), D(2003, 10, 27))), ("W6_2004-11", "n15txt", (D(2004, 10, 28), D(2004, 12, 23)), (D(2004, 11, 8), D(2004, 12, 23)), (D(2004, 10, 28), D(2004, 11, 6))), ("W7_2015-03", "n15proc", (D(2015, 3, 6), D(2015, 5, 1)), (D(2015, 3, 17), D(2015, 5, 1)), (D(2015, 3, 6), D(2015, 3, 15))), ("W8_2015-06", "n15proc", (D(2015, 6, 11), D(2015, 8, 7)), (D(2015, 6, 23), D(2015, 8, 7)), (D(2015, 6, 11), D(2015, 6, 20))), ] def read_proc(path): with netCDF4.Dataset(path) as ds: ds.set_auto_mask(False) t = ds["time"][:].astype("int64") L = ds["L_IGRF"][:].astype(float) f = ds["mep_ele_tel90_flux_e3"][:].astype(float) ifc = ds["mep_IFC_on"][:] if "mep_IFC_on" in ds.variables else np.zeros_like(t) ok = np.isfinite(f) & (f >= 0) & np.isfinite(L) & (L > 0) & (np.asarray(ifc) != 1) & (f < 1e12) secs = t[ok] / 1000.0 return secs, L[ok], f[ok] def read_txt(path): rows = [] with open(path, encoding="ascii", errors="replace") as fh: head = fh.readline().split() iy, imo, idy, ihr, imi, isec = (head.index(k) for k in ("year", "mo", "dy", "hr", "mi", "second")) il, ie = head.index("lval"), head.index("mep90e3") for line in fh: p = line.split() if len(p) < len(head): continue try: when = dt.datetime(int(p[iy]), int(p[imo]), int(p[idy]), int(p[ihr]), int(p[imi])) + \ dt.timedelta(seconds=float(p[isec])) rows.append(((when - dt.datetime(1970, 1, 1)).total_seconds(), float(p[il]), float(p[ie]))) except ValueError: continue a = np.array(rows, dtype=float).reshape(-1, 3) ok = np.isfinite(a[:, 2]) & (a[:, 2] >= 0) & np.isfinite(a[:, 1]) & (a[:, 1] > 0) & (a[:, 2] < 1e12) return a[ok, 0], a[ok, 1], a[ok, 2] def bin6h(files, reader, d0, d1): nbin = ((d1 - d0).days + 1) * 4 s = np.zeros((nbin, len(LC))) n = np.zeros((nbin, len(LC))) t0 = (dt.datetime.combine(d0, dt.time()) - dt.datetime(1970, 1, 1)).total_seconds() for p in files: secs, L, f = reader(p) ti = np.floor((secs - t0) / 21600.0).astype(int) li = np.floor((L - 1.0) / 0.1 + 1e-9).astype(int) ok = (ti >= 0) & (ti < nbin) & (li >= 0) & (li < len(LC)) np.add.at(s, (ti[ok], li[ok]), f[ok]) np.add.at(n, (ti[ok], li[ok]), 1) with np.errstate(invalid="ignore", divide="ignore"): mean = np.where(n > 0, s / np.maximum(n, 1), np.nan) times = [dt.datetime.combine(d0, dt.time()) + dt.timedelta(hours=6 * k + 3) for k in range(nbin)] return times, mean, n def files_for(kind, folders, d0, d1): out = [] d = d0 while d <= d1: if kind == "m03": p = os.path.join(folders["m03"], f"poes_m03_{d:%Y%m%d}_proc.nc") elif kind == "n15proc": p = os.path.join(folders["n15proc"], f"poes_n15_{d:%Y%m%d}_proc.nc") else: p = os.path.join(folders["n15txt"], f"poes_n15_{d:%Y%m%d}.txt") if os.path.exists(p): out.append(p) d += dt.timedelta(days=1) return out def longest_run(mask, days, lo, hi): best, cur, start, bs = 0, 0, None, None for k, d in enumerate(days): if mask[k] and lo <= d <= hi: cur += 1 start = d if cur == 1 else start if cur > best: best, bs = cur, start else: cur = 0 return best, (str(bs) if bs else None) def stats(days, res, window, baseline): r = res[0] outer = np.array([sum(1 for tr in r["present"][t] if tr["Lmed"] >= 2.0) for t in range(len(days))]) allc = r["nslot"] out = {} for name, (lo, hi) in (("window", window), ("baseline", baseline)): out[name] = { "S1_outer_split_run": longest_run(outer >= 2, days, lo, hi), "S2_three_or_more_run": longest_run(allc >= 2, days, lo, hi), "S2_four_or_more_run": longest_run(allc >= 3, days, lo, hi), "valid_days": int(sum(1 for k, d in enumerate(days) if lo <= d <= hi and r["valid"][k])), "days": int(sum(1 for d in days if lo <= d <= hi)), } tracks = [dict(first=str(days[tr["first"]]), last=str(days[tr["last"]]), span=tr["span"], L=round(tr["Lmed"], 2), depth=round(tr["pmed"], 3)) for tr in r["slot_tracks"] if tr["persistent"]] out["persistent_slot_tracks"] = tracks return out, outer def main(): if len(sys.argv) != 6: sys.exit("usage: python3 meped_test.py " " ") folders = {"m03": sys.argv[1], "n15proc": sys.argv[2], "n15txt": sys.argv[3]} authors, outdir = sys.argv[4], sys.argv[5] os.makedirs(outdir, exist_ok=True) settings = {"primary": dict(A.PRIMARY), "X1_nosmooth": dict(A.PRIMARY, kernel=(1,))} summary = {"rules": "RULES_meped.txt", "cases": {}} for name, kind, (d0, d1), window, baseline in CASES: files = files_for(kind, folders, d0, d1) expected = (d1 - d0).days + 1 if not files: summary["cases"][name] = {"files": 0, "expected": expected, "note": "no files"} print(name, "no files") continue reader = read_txt if kind == "n15txt" else read_proc times, mean, n = bin6h(files, reader, d0, d1) np.savez_compressed(os.path.join(outdir, f"meped_bins_{name}.npz"), mean=mean, n=n, t0=str(times[0]), Lc=LC) data = mean[:, :, None] days, daily = A.daily_means(times, data, 6.0) case = {"files": len(files), "expected": expected} for sname, s in settings.items(): res = A.analyse(days, daily, LC, s, 1) st, outer = stats(days, res, window, baseline) case[sname] = st with open(os.path.join(outdir, f"meped_daily_{name}_{sname}.csv"), "w", newline="\n", encoding="utf-8") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["date", "valid_profile", "slots_detected_L:depth_dec", "persistent_slots_present", "persistent_slot_track_L", "persistent_slots_at_L>=2.0", "belts_count"]) r = res[0] for t, d in enumerate(days): w.writerow([d.isoformat(), int(r["valid"][t]), ";".join(f"{L:.2f}:{p:.3f}" for L, p in r["mins"][t]) if r["mins"][t] is not None else "", int(r["nslot"][t]), ";".join(f"{tr['Lmed']:.2f}" for tr in sorted(r["present"][t], key=lambda q: q["Lmed"])), int(outer[t]), int(r["belts"][t]) if r["belts"][t] >= 0 else ""]) if name == "control_metop03_2024": # C1(c): our daily log10 profiles against the authors' file, 1-25 June 2024, L 1.2-6.5 t2, d2, lc2, le2, st2 = A.load(authors) days2, daily2 = A.daily_means(t2, d2, st2) sel = (LC > 1.2) & (LC < 6.5) diffs = [] for k, d in enumerate(days): if D(2024, 6, 1) <= d <= D(2024, 6, 25) and d in days2: a = daily[k, sel, 0] b = daily2[days2.index(d), sel, 2] ok = (a > 0) & (b > 0) & np.isfinite(a) & np.isfinite(b) diffs.extend(list(np.abs(np.log10(a[ok]) - np.log10(b[ok])))) case["C1c_median_abs_log10_difference_vs_authors"] = round(float(np.median(diffs)), 4) if diffs else None case["C1c_n_cells"] = len(diffs) summary["cases"][name] = case print(name, json.dumps({k: (v if not isinstance(v, dict) else {kk: vv for kk, vv in v.items() if kk != "persistent_slot_tracks"}) for k, v in case.items()}, default=str)) with open(os.path.join(outdir, "meped_test_summary.json"), "w", newline="\n", encoding="utf-8") as fh: json.dump(summary, fh, indent=1, default=str) if __name__ == "__main__": main()