#!/usr/bin/env python """Rule 5: reproduction of the group's published z values and of the paper's curves and peak lists. Run: python -I 03_reproduce.py Writes ../out/reproduce.json. The figures are read as pixels for this check only. """ import datetime as dt import json import os import re import sys import numpy as np from PIL import Image sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import rr_core as rr # noqa: E402 out = {} gle = np.array([int(r["day_since_1955_12_31"]) for r in rr.read_csv(os.path.join(rr.OUT, "events_gle.csv"))]) sfl = np.array([int(r["day_since_1955_12_31"]) for r in rr.read_csv(os.path.join(rr.OUT, "events_sflares.csv"))]) merged = np.concatenate([gle, sfl]) # ---- published numbers from Stefani et al. 2026 ------------------------------------------------ tt = np.arange(560, 700, 0.01) rep = {} for name, d, z_th, z_opt in (("72 GLE", gle, 6.65, 6.66), ("37 S-flares", sfl, 7.27, 11.04), ("109 merged", merged, 10.78, 11.47)): zt = float(rr.z_direct(d, 629.29)[0]) zz = rr.z_direct(d, tt) i = int(np.argmax(zz)) rep[name] = dict(z_629_29=round(zt, 3), published=z_th, diff_pct=round(100 * (zt / z_th - 1), 2), best_T=round(float(tt[i]), 2), best_z=round(float(zz[i]), 3), published_best=z_opt) print(name, rep[name]) out["published_values"] = rep # ---- z at the nine for every family ------------------------------------------------------------ nine = np.array([rr.PERIODS[n] for n in rr.NAMES]) tab = {} for fam in ("R", "N", "L"): days, kinds, levels = rr.load_family(fam) masks = rr.set_masks(kinds, levels) tab[fam] = {} for nm, m in zip(rr.SET_NAMES, masks): tab[fam][nm] = dict(N=int(m.sum()), z=[round(float(x), 2) for x in rr.z_direct(days[m], nine)]) fl = (kinds == 0) tab[fam]["X1+ flares alone"] = dict(N=int(fl.sum()), z=[round(float(x), 2) for x in rr.z_direct(days[fl], nine)]) tab["GLE alone"] = dict(N=72, z=[round(float(x), 2) for x in rr.z_direct(gle, nine)]) tab["S-list alone"] = dict(N=37, z=[round(float(x), 2) for x in rr.z_direct(sfl, nine)]) out["z_at_nine"] = tab print(rr.NAMES) for fam in ("R", "N"): for k, v in tab[fam].items(): print(fam, k, v["N"], v["z"]) print("GLE", tab["GLE alone"]["z"]) print("S", tab["S-list alone"]["z"]) # ---- digitize the paper's figures ---------------------------------------------------------------- COL = {"X10+GLE": (0xE5, 0x1E, 0x10), "X6+GLE": (0x94, 0x00, 0xD3), "X3+GLE": (0x56, 0xB4, 0xE9), "X2+GLE": (0xE6, 0x9F, 0x00), "X1+GLE": (0x00, 0x72, 0xB2)} SHIFT = {"X10+GLE": 80, "X6+GLE": 60, "X3+GLE": 40, "X2+GLE": 20, "X1+GLE": 0} FIGDIR = os.path.join(rr.DL, "arxiv-2610.16428", "src-extracted") # panels: file, label, approximate box in pixels of the 4021 x 2829 image, x tick values PANELS = [ ("figure1.png", "1c", (300, 1570, 1900, 2540), list(range(100, 900, 100))), ("figure1.png", "1d", (2320, 1570, 3920, 2540), list(range(50, 350, 50))), ("figure2.png", "2a", (300, 150, 1900, 1120), list(range(500, 900, 50))), ("figure2.png", "2b", (2320, 150, 3920, 1120), list(range(240, 380, 20))), ("figure2.png", "2c", (300, 1570, 1900, 2540), list(range(180, 230, 10))), ("figure2.png", "2d", (2320, 1570, 3920, 2540), list(range(130, 170, 5))), ("figure3.png", "3a", (300, 150, 1900, 1120), list(range(110, 135, 5))), ("figure3.png", "3b", (2320, 150, 3920, 1120), [95, 100, 105]), ("figure3.png", "3c", (300, 1570, 1900, 2540), [75, 80, 85]), ("figure3.png", "3d", (2320, 1570, 3920, 2540), [55, 60, 65]), ] XLEFT = {"1c": 0, "1d": 0, "2a": 450, "2b": 230, "2c": 170, "2d": 128, "3a": 106, "3b": 90, "3c": 70, "3d": 50} def comb_fit(det, n): """Equally spaced comb of n ticks that best matches the detected positions.""" best = None det = np.asarray(det, dtype=float) for i in range(det.size): for j in range(i + 1, det.size): for m in range(1, n): dx = (det[j] - det[i]) / m if dx < 40: continue for i0 in range(0, n - m): x0 = det[i] - i0 * dx pos = x0 + dx * np.arange(n) d = np.abs(det[:, None] - pos[None, :]).min(axis=0) cnt = int((d <= 2.0).sum()) res = float(d[d <= 2.0].sum()) if best is None or cnt > best[0] or (cnt == best[0] and res < best[1]): best = (cnt, res, x0, dx) return best def find_frame(a, box): x0, y0, x1, y1 = box sub = a[y0:y1, x0:x1].sum(axis=2) < 150 cols = np.where(sub.mean(axis=0) > 0.6)[0] + x0 rows = np.where(sub.mean(axis=1) > 0.6)[0] + y0 return cols.min(), cols.max(), rows.min(), rows.max() def ticks(a, frame, axis): L, R, T, B = frame if axis == "x": band = a[B - 14 : B - 6, L + 8 : R - 7].sum(axis=2) < 200 hits = np.where(band.mean(axis=0) > 0.8)[0] + L + 8 else: band = a[T + 8 : B - 7, L + 8 : L + 14].sum(axis=2) < 200 hits = np.where(band.mean(axis=1) > 0.8)[0] + T + 8 groups = np.split(hits, np.where(np.diff(hits) > 2)[0] + 1) return np.array([g.mean() for g in groups if g.size]) def digitize(file, box, xticks): im = Image.open(os.path.join(FIGDIR, file)).convert("RGB") a = np.asarray(im).astype(int) frame = find_frame(a, box) xt = ticks(a, frame, "x") yt = ticks(a, frame, "y") # x calibration: if ticks fall exactly on the frame they are not seen, so match from the values return a, frame, xt, yt def curves_on_panel(a, frame, x_of_col, z_of_row, row_of_z): L, R, T, B = frame res = {} for nm, col in COL.items(): s = SHIFT[nm] d = np.abs(a[T + 3 : B - 2, L + 3 : R - 2] - np.array(col)).sum(axis=2) <= 60 rows = np.arange(T + 3, B - 2) # threshold lines of this colour sit at z = 4.61 and 6.91: blank those rows blank = np.zeros_like(rows, dtype=bool) for th in (4.61, 6.91): r0 = row_of_z(s + th) blank |= np.abs(rows - r0) <= 3 # rows allowed for this curve: z from s to s + 19 (s + 30 for the lowest two) top = s + (17 if s >= 60 else 28) allowed = (z_of_row(rows) <= top) & (z_of_row(rows) >= s - 1) ok_rows = allowed sub = d[ok_rows, :] | blank[ok_rows, None] # blanked rows may be part of a run rr_ = rows[ok_rows] real = d[ok_rows, :] & ~blank[ok_rows, None] zcol = np.full(sub.shape[1], np.nan) for c in range(sub.shape[1]): # walk up from the lowest allowed row: first real pixel, then up while pixels continue colr = real[:, c] if not colr.any(): continue i = len(rr_) - 1 - np.argmax(colr[::-1]) # lowest real pixel top = i gap = 0 j = i - 1 while j >= 0: if colr[j]: top = j gap = 0 elif sub[j, c]: gap += 0 else: gap += 1 if gap > 6: break j -= 1 zcol[c] = z_of_row(rr_[top]) - s res[nm] = zcol return res panel_results = {} all_r = {"R": [], "N": []} grid_T = rr.NFFT / np.arange(1, rr.KMAX + 1) fam_curves = {} for fam in ("R", "N"): days, kinds, levels = rr.load_family(fam) masks = rr.set_masks(kinds, levels) fam_curves[fam] = {nm: rr.z_grid(days[m]) for nm, m in zip(rr.SET_NAMES, masks)} for file, label, box, xvals in PANELS: a, frame, xt, yt = digitize(file, box, xvals) L, R, T, B = frame cnt, res_, x0, dx = comb_fit(xt, len(xvals)) dv = (xvals[-1] - xvals[0]) / (len(xvals) - 1) # the comb can slip by whole ticks: anchor it on the value printed at the frame's left edge x_at_L = xvals[0] + (L - x0) / dx * dv x0 = x0 + round((x_at_L - XLEFT[label]) / dv) * dx x_of_col = lambda c: xvals[0] + (c - x0) / dx * dv if label == "3b": # only three inner ticks: use the frame, whose edges carry the labels 90 and 110 x_of_col = lambda c: 90.0 + (c - L) / (R - L) * 20.0 cnty, resy, y0, dy = comb_fit(yt, 5) # z = 100, 80, 60, 40, 20 from the top z_of_row = lambda r: 100.0 - (r - y0) / dy * 20.0 row_of_z = lambda z: y0 + (100.0 - z) / 20.0 * dy curves = curves_on_panel(a, frame, x_of_col, z_of_row, row_of_z) cols = np.arange(L + 3, R - 2) Tcol = x_of_col(cols) res = dict(x_ticks_matched=cnt, x_ticks_wanted=len(xvals), y_ticks_matched=cnty, x_range=[round(float(Tcol.min()), 2), round(float(Tcol.max()), 2)], sets={}) for nm in rr.SET_NAMES: dg = curves[nm] keep = ~np.isnan(dg) & (Tcol > 20) row = dict(n=int(keep.sum())) for fam in ("R", "N"): zz = fam_curves[fam][nm] # highest of our z within the pixel column, since the figure shows the top of the line edges = x_of_col(cols[keep] - 0.5), x_of_col(cols[keep] + 0.5) k_hi = np.clip(np.ceil(1 / edges[0] / rr.DF).astype(int), 1, rr.KMAX) k_lo = np.clip(np.floor(1 / edges[1] / rr.DF).astype(int), 1, rr.KMAX) ours = np.array([zz[a_ : b_ + 1].max() for a_, b_ in zip(k_lo, k_hi)]) # compare where the digitized curve clears the blanked threshold rows hi = dg[keep] > 7.5 r_all = float(np.corrcoef(dg[keep], ours)[0, 1]) r_hi = float(np.corrcoef(dg[keep][hi], ours[hi])[0, 1]) if hi.sum() > 20 else float("nan") row[fam] = dict(r=round(r_all, 3), r_above_7_5=round(r_hi, 3), rms=round(float(np.sqrt(np.mean((dg[keep] - ours) ** 2))), 2)) all_r[fam].append(r_all) res["sets"][nm] = row panel_results[label] = res print(label, res["x_range"], {nm: (res["sets"][nm]["R"]["r"], res["sets"][nm]["N"]["r"]) for nm in rr.SET_NAMES}) out["figure_check"] = panel_results out["figure_check_median_r"] = {k: round(float(np.nanmedian(v)), 3) for k, v in all_r.items()} print("median r over panels and sets:", out["figure_check_median_r"]) # ---- the paper's listed peaks -------------------------------------------------------------------- LISTED = { "P629": [633, 508, 848, 800, 748], "P292": [244, 262, 330, 275, 309, 285, 300], "P199": [201, 182.5, 218, 191.5, 207.5], "P146": [147, 129.5, 134, 159, 136.7, 156, 141.5, 152.7, 144.3, 149.8], "P118": [111.9, 113.6, 125.4, 116.0, 122.8, 129.5], "P100": [97, 103.5], "P84": [84.0, 85.0, 82.1, 85.8, 86.7], "P74": [74.33, 73.4, 75.7], "P59": [57.0, 61.1, 55.7, 62.0, 54.5, 63.1], } peaks_out = {} for fam in ("R", "N"): rows = [] z_arr = fam_curves[fam] for per, lst in LISTED.items(): for T in lst: tol = T ** 2 / 25000 f0, f1 = 1 / (T + tol), 1 / (T - tol) k0, k1 = int(f0 / rr.DF), int(np.ceil(f1 / rr.DF)) row = dict(group=per, T=T) best = 0.0 for nm in rr.SET_NAMES: z = z_arr[nm] seg = z[k0 : k1 + 1] lm = (z[k0 : k1 + 1] >= z[k0 - 1 : k1]) & (z[k0 : k1 + 1] >= z[k0 + 1 : k1 + 2]) v = float(seg[lm].max()) if lm.any() else 0.0 row[nm] = round(v, 1) best = max(best, v) row["best"] = round(best, 1) rows.append(row) peaks_out[fam] = rows vals = np.array([r["best"] for r in rows]) print(fam, "listed peaks:", len(rows), "with a local max in tolerance at z>=4.61:", int((vals >= 4.61).sum()), "z>=6.91:", int((vals >= 6.91).sum())) out["listed_peaks"] = peaks_out rr.save_json(os.path.join(rr.OUT, "reproduce.json"), out)