"""Method B of RULES_belts.txt: the same belt rule, written separately from method A (belts_a.py; no shared code). 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), BIRA-IASB, doi:10.18758/lu12i2kq (CC BY 4.0), and makes daily MEDIAN profiles (pandas), log10 with zeros as missing, an optional 3-bin running median in L, finds slots with a hand-written prominence routine, and keeps them if they persist for at least 6 days, by connected components (scipy.ndimage.label, 8-connectivity) in a day x L image of detections. It reports, for the paper's statements, the share of window days and the longest run with the stated number of belts, and (post hoc, labelled) the same for the paper's own slot L values. Needs Python 3.9+, numpy, scipy, pandas (1.5 or later), netCDF4 (with cftime). Run python3 belts_b.py [threshold_dec] [med3|none] The pre-registered run is threshold 0.10 with med3 (the defaults). Our report also used 0.05 med3, 0.20 med3, 0.10 none and 0.05 none. Writes, in the output folder belts_B_thr__summary.json and belts_B_thr__daily.csv """ import json import os import sys import datetime as dt import numpy as np import pandas as pd import netCDF4 from scipy import ndimage 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", } L_LO, L_HI = 1.2, 6.5 def read(path): ds = netCDF4.Dataset(path) t = ds["time_center"] stamps = pd.to_datetime([str(x) for x in netCDF4.num2date( t[:], t.units, only_use_cftime_datetimes=False, only_use_python_datetimes=True)]) flux = np.ma.filled(ds["data"][:].astype(float), np.nan) lcen = np.asarray(ds["L_center"][:], float) ds.close() return stamps, flux, lcen def day_medians(stamps, flux): step = (stamps[1] - stamps[0]).total_seconds() / 3600.0 minimum = int(24 / step) // 2 nt, nl, ne = flux.shape frame = pd.DataFrame(flux.reshape(nt, nl * ne), index=stamps) key = frame.index.normalize() med = frame.groupby(key).median() cnt = frame.notna().groupby(key).sum() med = med.where(cnt >= minimum) full = pd.date_range(med.index.min(), med.index.max(), freq="D") med = med.reindex(full) return [d.date() for d in full], med.to_numpy().reshape(len(full), nl, ne) def coarsen(arr, lcen): a = arr.reshape(arr.shape[0], arr.shape[1] // 2, 2, arr.shape[2]) with np.errstate(all="ignore"): import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") out = np.nanmean(a, axis=2) return out, 0.5 * (lcen[::2] + lcen[1::2]) def run_median3(y): z = y.copy() for i in range(1, len(y) - 1): z[i] = np.median(y[i - 1:i + 2]) return z def dips(y, thr): """Local minima and their depth: walk out to the first deeper point (or the end) on each side.""" found = [] n = len(y) for i in range(1, n - 1): if not (y[i] < y[i - 1] and y[i] <= y[i + 1]): continue j, left = i - 1, y[i - 1] while j >= 0 and y[j] >= y[i]: left = max(left, y[j]) j -= 1 k, right = i + 1, y[i + 1] while k < n and y[k] >= y[i]: right = max(right, y[k]) k += 1 depth = min(left, right) - y[i] if depth >= thr: found.append((i, depth)) return found def channel_counts(daily, lsel, thr, smooth): nd = daily.shape[0] nl = lsel.sum() image = np.zeros((nd, nl), dtype=bool) raw_hits = [[] for _ in range(nd)] ok = np.zeros(nd, dtype=bool) for d in range(nd): v = daily[d, lsel].astype(float) with np.errstate(divide="ignore", invalid="ignore"): y = np.where(v > 0, np.log10(v), np.nan) bad = np.isnan(y) if bad.sum() > 0.10 * nl: continue if bad.any(): idx = np.arange(nl) y[bad] = np.interp(idx[bad], idx[~bad], y[~bad]) ok[d] = True if smooth == "med3": y = run_median3(y) for i, depth in dips(y, thr): raw_hits[d].append((i, depth)) image[d, max(0, i - 1):i + 2] = True # bridge at most 2 days without a valid profile with the previous valid day's row filled = image.copy() last, gap = None, 0 for d in range(nd): if ok[d]: last, gap = d, 0 else: gap += 1 if last is not None and gap <= 2: filled[d] = filled[last] lab, nlab = ndimage.label(filled, structure=np.ones((3, 3), dtype=int)) persistent = set() for c in range(1, nlab + 1): days_c = np.unique(np.nonzero(lab == c)[0]) if len(days_c) >= 6: persistent.add(c) comp_count = np.zeros(nd, dtype=int) det_count = np.zeros(nd, dtype=int) present_L = [[] for _ in range(nd)] for d in range(nd): comps = set() for i, depth in raw_hits[d]: c = lab[d, i] if c in persistent: comps.add(c) det_count[d] += 1 present_L[d].append((i, depth)) comp_count[d] = len(comps) return ok, comp_count, det_count, present_L NAMED = { # post hoc: the slot L values the paper states, matched one to one within 0.25 L ((lo, hi) = a range) "T1a": [1.9, 2.4, 3.8], "T1e": [1.9, 2.4, 3.8], "T2": [(1.6, 2.4), 2.5], "T3": [2.0, 2.5], "T4": [1.9, 2.5], } def named_ok(Lvals, named): used = set() for st in named: best = None for j, L in enumerate(Lvals): if j in used: continue if isinstance(st, tuple): ok, dist = (st[0] <= L < st[1]), 0.0 else: dist = abs(L - st) ok = dist <= 0.25 + 1e-9 if ok and (best is None or dist < best[0]): best = (dist, j) if best is None: return False used.add(best[1]) return True WINDOWS = [ ("T1a", "2024may", [0, 1, 2, 3, 4], 3, dt.date(2024, 6, 1), dt.date(2024, 6, 30), (dt.date(2024, 5, 12), dt.date(2024, 6, 30))), ("T1e", "meped2024", [2], 3, dt.date(2024, 6, 1), dt.date(2024, 6, 30), (dt.date(2024, 5, 12), dt.date(2024, 6, 30))), ("T2", "2024oct", [0, 1, 2, 3, 4], 2, dt.date(2024, 10, 12), dt.date(2024, 11, 8), None), ("T3", "2025jun", [0, 1, 2, 3, 4], 2, dt.date(2025, 6, 10), dt.date(2025, 7, 15), None), ("T4", "2026jan", [0, 1, 2, 3, 4], 2, dt.date(2026, 2, 1), dt.date(2026, 2, 27), None), ("T5", "2026jul", [0, 1, 2, 3, 4], 2, dt.date(2026, 7, 5), dt.date(2026, 7, 15), None), ("C0_ept", "2024may", [0, 1, 2, 3, 4], 2, dt.date(2024, 5, 1), dt.date(2024, 5, 10), (dt.date(2024, 5, 1), dt.date(2024, 5, 10))), ("C0_meped", "meped2024", [2], 2, dt.date(2024, 5, 1), dt.date(2024, 5, 10), (dt.date(2024, 5, 1), dt.date(2024, 5, 10))), ] def longest(mask, days, lo, hi): best, cur, start, bstart = 0, 0, None, None for k, d in enumerate(days): if mask[k] and lo <= d <= hi: cur += 1 if cur == 1: start = d if cur > best: best, bstart = cur, start else: cur = 0 return best, bstart def main(): if len(sys.argv) < 3 or len(sys.argv) > 5: sys.exit("usage: python3 belts_b.py [threshold] [med3|none]") folder, out = sys.argv[1], sys.argv[2] os.makedirs(out, exist_ok=True) thr = float(sys.argv[3]) if len(sys.argv) > 3 else 0.10 smooth = sys.argv[4] if len(sys.argv) > 4 else "med3" cache = {} result = {"method": "B", "threshold_dec": thr, "smoothing": smooth, "tests": {}} rows = [] for key, fname in FILES.items(): stamps, flux, lcen = read(os.path.join(folder, fname)) days, daily = day_medians(stamps, flux) if key == "2026jul": daily, lcen = coarsen(daily, lcen) lsel = (lcen > L_LO) & (lcen < L_HI) Ls = lcen[lsel] per = [] for c in range(daily.shape[2]): ok, cc, dc, pres = channel_counts(daily[:, :, c], lsel, thr, smooth) per.append((ok, cc, dc, pres)) for k, d in enumerate(days): rows.append((key, c, d.isoformat(), int(ok[k]), int(cc[k]), int(dc[k]), ";".join(f"{Ls[i]:.2f}:{dep:.2f}" for i, dep in pres[k]))) cache[key] = (days, per, Ls) for tid, key, chans, need, w0, w1, within in WINDOWS: days, per, Ls = cache[key] res = {} for c in chans: ok, cc, dc, pres = per[c] have_c = cc >= need have_d = dc >= need idx = [k for k, d in enumerate(days) if w0 <= d <= w1] lo, hi = within if within else (w0 - dt.timedelta(days=7), w1 + dt.timedelta(days=7)) rl_c, st_c = longest(have_c, days, lo, hi) rl_d, st_d = longest(have_d, days, lo, hi) entry = dict( frac_window_components=round(float(np.mean(have_c[idx])), 3), frac_window_detections=round(float(np.mean(have_d[idx])), 3), longest_run_components=[rl_c, str(st_c)], longest_run_detections=[rl_d, str(st_d)]) if tid in NAMED: have_n = np.array([named_ok([Ls[i] for i, _ in pres[k]], NAMED[tid]) for k in range(len(days))]) rl_n, st_n = longest(have_n, days, lo, hi) entry["named_post_hoc"] = dict(frac_window=round(float(np.mean(have_n[idx])), 3), longest_run=[rl_n, str(st_n)]) res[f"ch{c + 1}" if key != "meped2024" else [">30", ">100", ">300"][c]] = entry result["tests"][tid] = res tag = f"B_thr{thr:.2f}_{smooth}" with open(os.path.join(out, f"belts_{tag}_summary.json"), "w", newline="\n", encoding="utf-8") as f: json.dump(result, f, indent=1) pd.DataFrame(rows, columns=["file", "channel_index", "date", "valid", "persistent_components", "persistent_detections", "slots_L:depth"]).to_csv( os.path.join(out, f"belts_{tag}_daily.csv"), index=False, lineterminator="\n") for tid, res in result["tests"].items(): print(tid, " | ".join(f"{k}: f={v['frac_window_components']}/{v['frac_window_detections']} " f"run={v['longest_run_components'][0]}/{v['longest_run_detections'][0]}" + (f" named f={v['named_post_hoc']['frac_window']} run={v['named_post_hoc']['longest_run'][0]}" if 'named_post_hoc' in v else "") for k, v in res.items())) if __name__ == "__main__": main()