"""Method A of RULES_belts.txt: electron belts and slots, day by day, in the authors' own L-time averaged 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 Reads the six netCDF files of Winant, Pierrard & Botek (2026), "L-Time average of EPT and MEPED electron observations following strong geomagnetic storms", BIRA-IASB, doi:10.18758/lu12i2kq (CC BY 4.0). For every UT day, energy channel and file it makes a daily-mean flux profile in L, finds local minima (slots) and maxima (belts) by their prominence in log10 flux, links them from day to day and keeps those that persist for more than 5 days (the paper's rule), counts belts per day (1 + persistent slots) and tests the paper's statements, event by event, under the pre-registered settings of RULES_belts.txt ("primary"), its robustness settings R1-R6 and the post-hoc no-smoothing settings X1-X4 (labelled as such: they test the rules' ordinary explanation (5), smoothing). Needs Python 3.9+, numpy, scipy, netCDF4 (with cftime). Run python3 belts_a.py (fetch_inputs.py saves the six files in /bira/.) Writes, in the output folder belts_A__daily.csv, belts_A__tracks.csv pre-registered settings belts_A-X1nosmooth__daily.csv, ..._tracks.csv post-hoc setting X1 (no smoothing) belts_A_summary.json every test under every setting above belts_A-G2__daily.csv, belts_A-G3__daily.csv, ..._tracks.csv, belts_A_G_summary.json post-hoc settings G2 and G3 of RULES_belts_amendment1.txt (X1 with up to 2 or 3 missed days tolerated in tracking), with the primary and X1 settings evaluated beside them on the amendment's questions (all five channels for every event, and the pre-storm baselines) and prints one line per test and setting. """ import csv import datetime as dt import json import os import sys import warnings import netCDF4 import numpy as np from scipy.signal import find_peaks FILES = { "2024may": "electrons_3h_0.1_lt_2024_may_jul.nc", "2024oct": "electrons_3h_0.1_lt_2024_oct_dec.nc", "2025jun": "electrons_3h_lt_2025_jun_jul.nc", "2026jan": "electrons_3h_lt_2026_jan_feb.nc", "2026jul": "electrons_3h_0.05_lt_2026_jul_aug.nc", "meped2024": "poes_e90_6hav_0.1l_2024_may_jun.nc", } EPT_CH = ["ch1 0.5-0.6 MeV", "ch2 0.6-0.7 MeV", "ch3 0.7-0.8 MeV", "ch4 0.8-1.0 MeV", "ch5 1.0-2.4 MeV", "ch6 2.4-8 MeV"] MEPED_CH = [">30 keV", ">100 keV", ">300 keV"] PRIMARY = dict(P=0.10, kernel=(1, 2, 1), Lmin=1.2, Lmax=6.5, tol=0.2, max_miss=1, min_span=6, min_det=5, rebin=True) ROBUST = { "R1_P0.05": dict(P=0.05), "R2_P0.20": dict(P=0.20), "R3_kernel5": dict(kernel=(1, 4, 6, 4, 1)), "R4_strict": dict(max_miss=0), "R5_L1.3-6.0": dict(Lmin=1.3, Lmax=6.0), "R6_native0.05": dict(rebin=False, kernel=(1, 4, 6, 4, 1)), # E5 only # Post hoc, NOT pre-registered as robustness settings: they test ordinary explanation (5) of RULES_belts.txt # (smoothing), after the daily profiles showed slots one or two 0.1-L bins wide that the [1,2,1]/4 kernel flattens. "X1_nosmooth_P0.10": dict(kernel=(1,)), "X2_nosmooth_P0.05": dict(kernel=(1,), P=0.05), "X3_nosmooth_P0.20": dict(kernel=(1,), P=0.20), "X4_nosmooth_native0.05": dict(kernel=(1,), rebin=False), # E5 only } POST_HOC = {"X1_nosmooth_P0.10", "X2_nosmooth_P0.05", "X3_nosmooth_P0.20", "X4_nosmooth_native0.05"} # Post hoc, after the fresh review (RULES_belts_amendment1.txt): setting X1 with a looser tracker, which tolerates up to # 2 or 3 consecutive missed valid days. They run after everything above and write separate files (belts_A-G2_*, # belts_A-G3_*, belts_A_G_summary.json), so every earlier output stays byte-identical. GAP_SETTINGS = { "G2_nosmooth_miss2": dict(kernel=(1,), max_miss=2), "G3_nosmooth_miss3": dict(kernel=(1,), max_miss=3), } GAP_TAGS = {"G2_nosmooth_miss2": "-G2", "G3_nosmooth_miss3": "-G3"} D = dt.date warnings.simplefilter("ignore", RuntimeWarning) # nanmean of all-NaN cells -> NaN, as intended def load(path): with netCDF4.Dataset(path, "r") as ds: tc = ds.variables["time_center"] times = netCDF4.num2date(tc[:], tc.units, getattr(tc, "calendar", "standard"), only_use_cftime_datetimes=False, only_use_python_datetimes=True) data = np.array(ds.variables["data"][:], dtype=float) lc = np.array(ds.variables["L_center"][:], dtype=float) le = np.array(ds.variables["L_edges"][:], dtype=float) step_h = float(tc[1] - tc[0]) return list(times), data, lc, le, step_h def daily_means(times, data, step_h): per_day = int(round(24 / step_h)) need = per_day // 2 days = sorted({t.date() for t in times}) out = np.full((len(days), data.shape[1], data.shape[2]), np.nan) nbins = np.zeros((len(days), data.shape[1], data.shape[2]), dtype=int) idx = {d: i for i, d in enumerate(days)} groups = {} for k, t in enumerate(times): groups.setdefault(idx[t.date()], []).append(k) for i, ks in groups.items(): block = data[ks] n = np.sum(np.isfinite(block), axis=0) with np.errstate(invalid="ignore"): m = np.nanmean(np.where(np.isfinite(block), block, np.nan), axis=0) if len(ks) else np.nan m = np.where(n >= need, m, np.nan) out[i] = m nbins[i] = n # fill calendar gaps (days with no bins at all) so that the day axis is continuous full = [days[0] + dt.timedelta(days=j) for j in range((days[-1] - days[0]).days + 1)] if len(full) != len(days): o2 = np.full((len(full),) + out.shape[1:], np.nan) for i, d in enumerate(days): o2[(d - days[0]).days] = out[i] out, days = o2, full return days, out def rebin_01(daily, lc): """0.05-L daily values -> 0.1-L bins (mean of the available pair).""" assert len(lc) % 2 == 0 pairs = daily.reshape(daily.shape[0], len(lc) // 2, 2, daily.shape[2]) with np.errstate(invalid="ignore"): m = np.nanmean(pairs, axis=2) newc = (lc[0::2] + lc[1::2]) / 2.0 return m, newc def smooth(y, kernel): k = np.array(kernel, dtype=float) h = len(k) // 2 out = np.empty_like(y) n = len(y) for i in range(n): lo, hi = max(0, i - h), min(n, i + h + 1) w = k[(lo - i + h):(hi - i + h)] out[i] = np.sum(w * y[lo:hi]) / np.sum(w) return out def profiles(daily_ch, lc, s): """Return list (per day) of (valid, L array, smoothed log10 profile).""" sel = (lc >= s["Lmin"] - 1e-9) & (lc <= s["Lmax"] + 1e-9) L = lc[sel] block = daily_ch[:, sel] pos = block[np.isfinite(block) & (block > 0)] floor = float(pos.min()) if pos.size else np.nan nfloor = int(np.sum(block == 0)) res = [] for row in block: r = row.copy() r = np.where(r == 0, floor, r) miss = ~np.isfinite(r) nmiss = int(miss.sum()) run, longest = 0, 0 for m in miss: run = run + 1 if m else 0 longest = max(longest, run) if nmiss > 0.10 * len(r) or longest > 2: res.append((False, L, None)) continue y = np.log10(r, where=~miss, out=np.full_like(r, np.nan)) if nmiss: good = ~miss y = np.interp(np.arange(len(y)), np.flatnonzero(good), y[good]) res.append((True, L, smooth(y, s["kernel"]))) return res, floor, nfloor def detect(prof, P): valid, L, y = prof if not valid: return None, None imin, pmin = find_peaks(-y, prominence=P) imax, pmax = find_peaks(y, prominence=P) mins = [(float(L[i]), float(p)) for i, p in zip(imin, pmin["prominences"])] maxs = [(float(L[i]), float(p)) for i, p in zip(imax, pmax["prominences"])] return mins, maxs def track(dets, valid, s): """dets[t] = list of (L, prom) or None (no valid profile). Returns list of tracks.""" tracks, open_ = [], [] nodata_run = 0 for t, det in enumerate(dets): if not valid[t]: nodata_run += 1 if nodata_run > 3: tracks.extend(open_) open_ = [] continue nodata_run = 0 pairs = [] for ti, tr in enumerate(open_): for di, (L, p) in enumerate(det): dist = abs(tr["L"][-1] - L) if dist <= s["tol"] + 1e-9: pairs.append((dist, ti, di)) pairs.sort() used_t, used_d = set(), set() for dist, ti, di in pairs: if ti in used_t or di in used_d: continue used_t.add(ti) used_d.add(di) tr = open_[ti] tr["t"].append(t) tr["L"].append(det[di][0]) tr["p"].append(det[di][1]) tr["miss"] = 0 still = [] for ti, tr in enumerate(open_): if ti not in used_t: tr["miss"] += 1 if tr["miss"] > s["max_miss"]: tracks.append(tr) continue still.append(tr) open_ = still for di, (L, p) in enumerate(det): if di not in used_d: open_.append({"t": [t], "L": [L], "p": [p], "miss": 0}) tracks.extend(open_) for tr in tracks: tr["first"], tr["last"] = tr["t"][0], tr["t"][-1] tr["span"] = tr["last"] - tr["first"] + 1 tr["ndet"] = len(tr["t"]) tr["persistent"] = tr["span"] >= s["min_span"] and tr["ndet"] >= s["min_det"] tr["Lmed"] = float(np.median(tr["L"])) tr["pmed"] = float(np.median(tr["p"])) return tracks def analyse(days, daily, lc, s, nch): """Per channel: profiles, detections, tracks, daily counts.""" out = [] for c in range(nch): profs, floor, nfloor = profiles(daily[:, :, c], lc, s) valid = [p[0] for p in profs] mins, maxs = [], [] for p in profs: a, b = detect(p, s["P"]) mins.append(a) maxs.append(b) st = track(mins, valid, s) bt = track(maxs, valid, s) nd = len(days) nslot = np.zeros(nd, dtype=int) nbelt = np.zeros(nd, dtype=int) present = [[] for _ in range(nd)] for tr in st: if tr["persistent"]: for t in range(tr["first"], tr["last"] + 1): nslot[t] += 1 present[t].append(tr) for tr in bt: if tr["persistent"]: for t in range(tr["first"], tr["last"] + 1): nbelt[t] += 1 belts = np.where(np.array(valid) | (nslot > 0), 1 + nslot, -1) # -1: unknown (no data, no span) out.append(dict(valid=valid, mins=mins, maxs=maxs, slot_tracks=st, belt_tracks=bt, nslot=nslot, nbelt=nbelt, belts=belts, present=present, floor=floor, nfloor=nfloor)) return out def runs(mask): """List of (start, end) inclusive index runs where mask is True.""" res, start = [], None for i, m in enumerate(mask): if m and start is None: start = i if not m and start is not None: res.append((start, i - 1)) start = None if start is not None: res.append((start, len(mask) - 1)) return res def match_L(run_tracks, stated): """Greedy one-to-one matching of stated L values (numbers or (lo, hi) ranges) to track median L values.""" used, result = set(), [] for st in stated: best = None for i, tr in enumerate(run_tracks): if i in used: continue L = tr["Lmed"] if isinstance(st, tuple): ok, dist = st[0] <= L < st[1], 0.0 if st[0] <= L < st[1] else 9 else: dist = abs(L - st) ok = dist <= 0.25 + 1e-9 if ok and (best is None or dist < best[0]): best = (dist, i) if best is None: result.append((st, None)) else: used.add(best[1]) result.append((st, run_tracks[best[1]]["Lmed"])) return result def evaluate(days, res_ch, need_slots, win, run_within=None, stated_L=None, run_days_needed=None): """Outcome for one channel. need_slots: 3 for four belts, 2 for three belts or more.""" di = {d: i for i, d in enumerate(days)} w0, w1 = win widx = [di[d] for d in days if w0 <= d <= w1] have = res_ch["nslot"] >= need_slots frac = float(np.mean(have[widx])) if widx else float("nan") ndays = int(np.sum(have[widx])) unknown = int(np.sum(res_ch["belts"][widx] < 0)) ext0, ext1 = w0 - dt.timedelta(days=7), w1 + dt.timedelta(days=7) allruns = runs(have) if run_within: r0, r1 = run_within sub = np.zeros_like(have) for i, d in enumerate(days): sub[i] = have[i] and r0 <= d <= r1 allruns_w = runs(sub) else: allruns_w = allruns overl = [(a, b) for a, b in allruns if days[b] >= ext0 and days[a] <= ext1] longest_ext = max(overl, key=lambda r: r[1] - r[0]) if overl else None longest_w = max(allruns_w, key=lambda r: r[1] - r[0]) if allruns_w else None best = longest_w if run_within else longest_ext run_len = (best[1] - best[0] + 1) if best else 0 # L values: slot tracks present on at least half of the days of the best run Lm, Ls = None, [] if best: cnt, obj = {}, {} for t in range(best[0], best[1] + 1): for tr in res_ch["present"][t]: cnt[id(tr)] = cnt.get(id(tr), 0) + 1 obj[id(tr)] = tr half = (best[1] - best[0] + 1) / 2.0 rt = sorted([obj[k] for k, n in cnt.items() if n >= half], key=lambda tr: tr["Lmed"]) Ls = [(round(tr["Lmed"], 3), round(tr["pmed"], 3), tr["span"]) for tr in rt] if stated_L: Lm = match_L(rt, stated_L) Lok = (Lm is None) or all(v is not None for _, v in Lm) # Post hoc refinement: the paper's own configuration, day by day -- every stated slot matched (within 0.25 L, one to # one) by a persistent slot track present that day. Slots elsewhere (noise or old features) are not counted. named = None if stated_L: hv = np.zeros(len(days), dtype=bool) for t in range(len(days)): m = match_L(sorted(res_ch["present"][t], key=lambda q: q["Lmed"]), stated_L) hv[t] = all(v is not None for _, v in m) if run_within: inside = np.array([run_within[0] <= d <= run_within[1] for d in days]) nr = runs(hv & inside) else: nr = [(a, b) for a, b in runs(hv) if days[b] >= ext0 and days[a] <= ext1] nb = max(nr, key=lambda r: r[1] - r[0]) if nr else None named = dict(frac_window=round(float(np.mean(hv[widx])), 3), days_in_window=int(np.sum(hv[widx])), longest_run=[str(days[nb[0]]), str(days[nb[1]]), nb[1] - nb[0] + 1] if nb else None, dates=[str(days[t]) for t in range(len(days)) if hv[t]]) if run_days_needed: repro = run_len >= run_days_needed else: repro = frac >= 0.75 ext_ok = longest_ext is not None and (longest_ext[1] - longest_ext[0] + 1) >= 6 if repro and Lok: outcome = "Reproduced" elif ext_ok or (run_len >= 6): outcome = "Partly" else: outcome = "Not reproduced" return dict(outcome=outcome, frac_window=round(frac, 3), days_in_window=ndays, window_days=len(widx), unknown_days_in_window=unknown, best_run=[str(days[best[0]]), str(days[best[1]])] if best else None, best_run_len=run_len, longest_run_overlapping_window_pm7=( [str(days[longest_ext[0]]), str(days[longest_ext[1]]), longest_ext[1] - longest_ext[0] + 1] if longest_ext else None), slots_on_best_run=Ls, L_match=[(str(a), b) for a, b in Lm] if Lm else None, named_configuration_post_hoc=named) EVENTS = [ # name, file key, channels tested (indices), need_slots, window, run_within, stated L, run_days_needed, expect dict(id="T1a", key="2024may", chans=[0, 1, 2, 3, 4], need=3, win=(D(2024, 6, 1), D(2024, 6, 30)), run_within=(D(2024, 5, 12), D(2024, 6, 30)), L=[1.9, 2.4, 3.8], run_days=29, expect=True, text="Four belts in June 2024 for more than 4 weeks, ch1-ch5, slots near L 1.9, 2.4, 3.8"), dict(id="T1d", key="2024may", chans=[5], need=3, win=(D(2024, 6, 1), D(2024, 6, 30)), run_within=(D(2024, 5, 12), D(2024, 6, 30)), L=None, run_days=29, expect=False, text="No four belts in ch6 (2.4-8 MeV) in June 2024"), dict(id="T1e", key="meped2024", chans=[2], need=3, win=(D(2024, 6, 1), D(2024, 6, 30)), run_within=(D(2024, 5, 12), D(2024, 6, 30)), L=[1.9, 2.4, 3.8], run_days=29, expect=True, text="MEPED >300 keV (MetOp-C, 90 deg) also shows the four belts"), dict(id="T2", key="2024oct", chans=[0], need=2, win=(D(2024, 10, 12), D(2024, 11, 8)), run_within=None, L=[(1.6, 2.4), 2.5], run_days=None, expect=True, text="Three belts 12 Oct - 8 Nov 2024 in ch1, slots at L<2.4 and L=2.5"), dict(id="T3", key="2025jun", chans=[0, 1, 2, 3, 4], need=2, win=(D(2025, 6, 10), D(2025, 7, 15)), run_within=None, L=[2.0, 2.5], run_days=None, expect=True, text="Three belts 10 June - mid-July 2025 in ch1-ch5, slots near L 2 and 2.5"), dict(id="T3x", key="2025jun", chans=[5], need=2, win=(D(2025, 6, 10), D(2025, 7, 15)), run_within=None, L=None, run_days=None, expect=False, text="No three belts in ch6, June-July 2025"), dict(id="T4", key="2026jan", chans=[0, 1, 2, 3, 4], need=2, win=(D(2026, 2, 1), D(2026, 2, 27)), run_within=None, L=[1.9, 2.5], run_days=None, expect=True, text="Three belts in February 2026 in ch1-ch5, slots near L 1.9 and 2.5"), dict(id="T4x", key="2026jan", chans=[5], need=2, win=(D(2026, 2, 1), D(2026, 2, 27)), run_within=None, L=None, run_days=None, expect=False, text="No three belts in ch6, February 2026"), dict(id="T5", key="2026jul", chans=[0], need=2, win=(D(2026, 7, 5), D(2026, 7, 15)), run_within=None, L=None, run_days=None, expect=True, text="Three belts 5 - mid-July 2026 in ch1"), # context (not statements of the paper): the same counts before the May 2024 storm dict(id="C0_ept", key="2024may", chans=[0, 1, 2, 3, 4], need=2, win=(D(2024, 5, 1), D(2024, 5, 10)), run_within=(D(2024, 5, 1), D(2024, 5, 10)), L=None, run_days=None, expect=True, text="Context: three belts or more in EPT ch1-ch5 before the storm, 1-10 May 2024"), dict(id="C0_meped", key="meped2024", chans=[2], need=2, win=(D(2024, 5, 1), D(2024, 5, 10)), run_within=(D(2024, 5, 1), D(2024, 5, 10)), L=None, run_days=None, expect=True, text="Context: three belts or more in MEPED >300 keV before the storm, 1-10 May 2024"), ] def combine(outcomes, expect): if expect: if all(o == "Reproduced" for o in outcomes): return "Reproduced" if any(o in ("Reproduced", "Partly") for o in outcomes): return "Partly" return "Not reproduced" # statement that the channel(s) show no such structure return "Reproduced" if all(o == "Not reproduced" for o in outcomes) else ( "Partly" if any(o == "Not reproduced" for o in outcomes) else "Not reproduced") def run_setting(folder, s, keys): cache = {} for key in keys: times, data, lc, le, step = load(os.path.join(folder, FILES[key])) days, daily = daily_means(times, data, step) if key == "2026jul" and s["rebin"]: daily, lc = rebin_01(daily, lc) cache[key] = (days, daily, lc, analyse(days, daily, lc, s, data.shape[2])) return cache def write_primary(cache, outdir, tag=""): for key, (days, daily, lc, res) in cache.items(): chn = MEPED_CH if key == "meped2024" else EPT_CH with open(os.path.join(outdir, f"belts_A{tag}_{key}_daily.csv"), "w", newline="\n", encoding="utf-8") as f: w = csv.writer(f, lineterminator="\n") w.writerow(["date", "channel", "valid_profile", "slots_detected_L:depth_dec", "belts_detected_L:prom_dec", "persistent_slots_present", "persistent_slot_track_L", "belts_count", "persistent_belts_present"]) for c, r in enumerate(res): for t, d in enumerate(days): mins = r["mins"][t] maxs = r["maxs"][t] w.writerow([d.isoformat(), chn[c], int(r["valid"][t]), ";".join(f"{L:.2f}:{p:.3f}" for L, p in mins) if mins is not None else "", ";".join(f"{L:.2f}:{p:.3f}" for L, p in maxs) if maxs 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(r["belts"][t]) if r["belts"][t] >= 0 else "", int(r["nbelt"][t])]) with open(os.path.join(outdir, f"belts_A{tag}_{key}_tracks.csv"), "w", newline="\n", encoding="utf-8") as f: w = csv.writer(f, lineterminator="\n") w.writerow(["channel", "type", "first_date", "last_date", "span_days", "detection_days", "median_L", "min_L", "max_L", "median_prominence_dec", "persistent"]) for c, r in enumerate(res): for typ, trs in (("slot", r["slot_tracks"]), ("belt", r["belt_tracks"])): for tr in sorted(trs, key=lambda q: (q["first"], q["Lmed"])): if tr["ndet"] < 2: continue w.writerow([chn[c], typ, days[tr["first"]].isoformat(), days[tr["last"]].isoformat(), tr["span"], tr["ndet"], f"{tr['Lmed']:.3f}", f"{min(tr['L']):.3f}", f"{max(tr['L']):.3f}", f"{tr['pmed']:.3f}", int(tr["persistent"])]) def main(): if len(sys.argv) != 3: sys.exit("usage: python3 belts_a.py ") folder, outdir = sys.argv[1], sys.argv[2] os.makedirs(outdir, exist_ok=True) keys = list(FILES) settings = {"primary": dict(PRIMARY)} for name, ch in ROBUST.items(): s = dict(PRIMARY) s.update(ch) settings[name] = s summary = {"rules": "RULES_belts.txt", "method": "A", "settings": settings, "post_hoc_settings": sorted(POST_HOC), "tests": {}, "floors": {}} for name, s in settings.items(): ks = ["2026jul"] if name in ("R6_native0.05", "X4_nosmooth_native0.05") else keys cache = run_setting(folder, s, ks) if name == "X1_nosmooth_P0.10": write_primary(cache, outdir, tag="-X1nosmooth") if name == "primary": write_primary(cache, outdir) for key, (days, daily, lc, res) in cache.items(): summary["floors"][key] = [dict(floor=r["floor"], n_zero_cells_floored=r["nfloor"], valid_days=int(sum(r["valid"])), days=len(days)) for r in res] for ev in EVENTS: if ev["key"] not in cache: continue days, daily, lc, res = cache[ev["key"]] per = {} for c in ev["chans"]: per[c] = evaluate(days, res[c], ev["need"], ev["win"], ev["run_within"], ev["L"], ev["run_days"]) outcomes = [per[c]["outcome"] for c in ev["chans"]] summary["tests"].setdefault(ev["id"], {"text": ev["text"]})[name] = { "combined": combine(outcomes, ev["expect"]), "per_channel": {(MEPED_CH if ev["key"] == "meped2024" else EPT_CH)[c]: per[c] for c in ev["chans"]}} # all channels, for context: three-or-more and four belts days per event window for ev in EVENTS: if ev["key"] not in cache or ev["id"] in ("T1d", "T3x", "T4x"): continue days, daily, lc, res = cache[ev["key"]] ctx = {} nch = len(res) for c in range(nch): ctx[(MEPED_CH if ev["key"] == "meped2024" else EPT_CH)[c]] = { "three_or_more": evaluate(days, res[c], 2, ev["win"], ev["run_within"], None, None), "four_or_more": evaluate(days, res[c], 3, ev["win"], ev["run_within"], None, None)} summary["tests"][ev["id"]].setdefault("all_channels_context", {})[name] = ctx with open(os.path.join(outdir, "belts_A_summary.json"), "w", newline="\n", encoding="utf-8") as f: json.dump(summary, f, indent=1, default=str) # short printout for tid, t in summary["tests"].items(): print(tid, "|", t["text"]) for name in settings: if name in t: pc = t[name]["per_channel"] print(f" {name:22s} {t[name]['combined']:15s} " + " | ".join( f"{k.split()[0]}:{v['outcome'][:5]} f={v['frac_window']} run={v['best_run_len']}" + (f" named f={v['named_configuration_post_hoc']['frac_window']} " f"run={(v['named_configuration_post_hoc']['longest_run'] or [0, 0, 0])[2]}" if v.get('named_configuration_post_hoc') else "") for k, v in pc.items())) run_gap_settings(folder, outdir, keys) # ---- Post hoc, RULES_belts_amendment1.txt: questions Q1-Q4 under primary, X1, G2 and G3 (separate files) ---- G_QUESTIONS = [ # id, file key, window, run_within (None: longest run overlapping the window +-7 days), stated slot L, belts needed ("Q1_June2024_four_belts", "2024may", (D(2024, 6, 1), D(2024, 6, 30)), (D(2024, 5, 12), D(2024, 6, 30)), [1.9, 2.4, 3.8], 3), ("Q2_baseline_1-10May2024", "2024may", (D(2024, 5, 1), D(2024, 5, 10)), (D(2024, 5, 1), D(2024, 5, 10)), [1.9, 2.4, 3.8], 3), ("Q3_Oct2024_three_belts", "2024oct", (D(2024, 10, 12), D(2024, 11, 8)), None, [(1.6, 2.4), 2.5], 2), ("Q3_baseline_2-6Oct2024", "2024oct", (D(2024, 10, 2), D(2024, 10, 6)), (D(2024, 10, 2), D(2024, 10, 6)), [(1.6, 2.4), 2.5], 2), ("Q3_Jun2025_three_belts", "2025jun", (D(2025, 6, 10), D(2025, 7, 15)), None, [2.0, 2.5], 2), ("Q3_Feb2026_three_belts", "2026jan", (D(2026, 2, 1), D(2026, 2, 27)), None, [1.9, 2.5], 2), ("Q3_baseline_2-18Jan2026", "2026jan", (D(2026, 1, 2), D(2026, 1, 18)), (D(2026, 1, 2), D(2026, 1, 18)), [1.9, 2.5], 2), ("Q3_Jul2026_three_belts", "2026jul", (D(2026, 7, 5), D(2026, 7, 15)), None, None, 2), ("Q3_baseline_1-3Jul2026", "2026jul", (D(2026, 7, 1), D(2026, 7, 3)), (D(2026, 7, 1), D(2026, 7, 3)), None, 2), ("Q4_MEPED_June2024", "meped2024", (D(2024, 6, 1), D(2024, 6, 30)), (D(2024, 5, 12), D(2024, 6, 30)), [1.9, 2.4, 3.8], 3), ("Q4_MEPED_baseline_1-10May2024", "meped2024", (D(2024, 5, 1), D(2024, 5, 10)), (D(2024, 5, 1), D(2024, 5, 10)), [1.9, 2.4, 3.8], 3), ] def g_entry(days, r, win, run_within, stated, need): """Named configuration (if slots are stated), three or more and four or more belts (any L): days in the window and the longest run.""" e = {} if stated: v = evaluate(days, r, need, win, run_within, stated, None) n = v["named_configuration_post_hoc"] e["named"] = dict(days_in_window=n["days_in_window"], window_days=v["window_days"], longest_run=n["longest_run"], dates=n["dates"]) for k, nd in (("three_or_more", 2), ("four_or_more", 3)): v = evaluate(days, r, nd, win, run_within, None, None) e[k] = dict(days_in_window=v["days_in_window"], window_days=v["window_days"], longest_run=(v["best_run"] + [v["best_run_len"]]) if v["best_run"] else None) return e def run_gap_settings(folder, outdir, keys): settings = {"primary": dict(PRIMARY), "X1_nosmooth_P0.10": dict(PRIMARY, kernel=(1,))} for name, ch in GAP_SETTINGS.items(): s = dict(PRIMARY) s.update(ch) settings[name] = s out = {"rules": "RULES_belts_amendment1.txt (post hoc, after the fresh review)", "settings": settings, "questions": {}} for name, s in settings.items(): cache = run_setting(folder, s, keys) if name in GAP_TAGS: write_primary(cache, outdir, tag=GAP_TAGS[name]) for qid, key, win, within, stated, need in G_QUESTIONS: days, daily, lc, res = cache[key] chans = [2] if key == "meped2024" else [0, 1, 2, 3, 4] names = MEPED_CH if key == "meped2024" else EPT_CH out["questions"].setdefault(qid, {})[name] = { names[c]: g_entry(days, res[c], win, within, stated, need) for c in chans} with open(os.path.join(outdir, "belts_A_G_summary.json"), "w", newline="\n", encoding="utf-8") as f: json.dump(out, f, indent=1, default=str) for qid, q in out["questions"].items(): print(qid) for name, per in q.items(): cells = [] for ch, e in per.items(): main_ = e.get("named") or e["three_or_more"] lr = main_["longest_run"] cells.append(f"{ch.split()[0]}:{main_['days_in_window']}/{main_['window_days']} " f"run={lr[2] if lr else 0}" + (f" ({lr[0][5:]}..{lr[1][5:]})" if lr else "") + f" 3+:{e['three_or_more']['days_in_window']} 4+:{e['four_or_more']['days_in_window']}") print(f" {name:18s} " + " | ".join(cells)) if __name__ == "__main__": main()