"""Shared arithmetic for the rieger-tidal-periods re-run. See RULES.txt. Eq. (1) of Stefani et al. (2026), arXiv 2610.16428: z(T) = (1/N) * [ (sum cos(2 pi t_i / T))^2 + (sum sin(2 pi t_i / T))^2 ] The grid is uniform in frequency: f_k = k / NFFT cycles per day. z on the grid comes from the FFT of the daily event counts, which is the same sum evaluated at those frequencies. """ import csv import datetime as dt import json import os import numpy as np import scipy.fft as sfft from scipy.ndimage import maximum_filter1d from scipy.stats import rankdata HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) DL = os.path.join(ROOT, "downloads") OUT = os.path.join(ROOT, "out") EPOCH = dt.date(1955, 12, 31) NFFT = 2 ** 18 DF = 1.0 / NFFT KMAX = int(0.05 * NFFT) # T = 20 d KMIN = int(np.ceil((1.0 / 9000.0) * NFFT)) # T = 9000 d TSPAN = 25000.0 # the paper's T_t (its Section 3) HALF = 10 # window half-width in bins: 10 * DF = 3.81e-5 per day, about 1/25000 (4.0e-5) OFFSET = 2100 # days added to every index so that shifted events stay in the array LTOTAL = 26000 + 2 * OFFSET # The nine periods as the paper lists them (days), with their integer coefficients on the two # base frequencies f2 = 1/P199 and f3 = 1/P292. PERIODS = { "P629": 629.29, "P292": 291.96, "P199": 199.43, "P146": 145.99, "P118": 118.50, "P100": 99.72, "P84": 84.29, "P74": 74.33, "P59": 59.25, } NAMES = list(PERIODS) COEF = { "P629": (1, -1), "P292": (0, 1), "P199": (1, 0), "P146": (0, 2), "P118": (1, 1), "P100": (2, 0), "P84": (1, 2), "P74": (2, 1), "P59": (2, 2), } COEF_ARR = np.array([COEF[n] for n in NAMES], dtype=float) # Side-band rule sets, as offsets in cycles per day around each line. _core = [1 / 4043.0, 1 / 2570.0, 1 / 2695.0, 1 / 7750.0, 1 / 8086.0] _full = _core + [1 / 2100.0, 1 / 3120.0, 1 / 3150.0, 2 / 2570.0, 3 / 2570.0] CORE_OFF = np.array([0.0] + _core + [-x for x in _core]) FULL_OFF = np.array([0.0] + _full + [-x for x in _full]) CORE_BINS = np.round(CORE_OFF / DF).astype(int) FULL_BINS = np.round(FULL_OFF / DF).astype(int) SET_NAMES = ["X10+GLE", "X6+GLE", "X3+GLE", "X2+GLE", "X1+GLE"] SET_LEVELS = [10, 6, 3, 2, 1] CYCLE_STARTS = [ # first day of each cycle: SILSO smoothed minima (month of the minimum) ("SC19", dt.date(1954, 4, 1)), ("SC20", dt.date(1964, 10, 1)), ("SC21", dt.date(1976, 3, 1)), ("SC22", dt.date(1986, 9, 1)), ("SC23", dt.date(1996, 5, 1)), ("SC24", dt.date(2008, 12, 1)), ("SC25", dt.date(2019, 12, 1)), ] def day_index(d): return (d - EPOCH).days def read_csv(path): with open(path, newline="", encoding="utf-8") as f: return list(csv.DictReader(f)) def master_events(flares, sflares, gle, cutoff, scale=None): """Master table of events: arrays day, is_gle, level. flares: list of dicts with date (date), mag (float), g16 (bool). An S-flare is the same flare as a catalogue flare of class X5 or above within one day, the same date first and the strongest first. That flare takes the S-list date and level 10. An S-flare with no such flare is added. Other flares get level 6, 3, 2 or 1 from their class. scale: if given, multiply the class of GOES-R flares by this before thresholding (legacy scale). """ cat = [] for r in flares: if r["date"] > cutoff: continue m = r["mag"] * (scale if (scale is not None and r.get("g16")) else 1.0) cat.append(dict(date=r["date"], mag=m)) used = set() days, kinds, levels = [], [], [] added = [] for d, di in sflares: near = [(i, c) for i, c in enumerate(cat) if abs((c["date"] - d).days) <= 1 and i not in used and c["mag"] >= 5] if near: i, _ = max(near, key=lambda x: (x[1]["date"] == d, x[1]["mag"])) used.add(i) else: added.append(d.isoformat()) days.append(di) kinds.append(0) levels.append(10) for i, c in enumerate(cat): if i in used: continue if c["mag"] < 1: continue lev = 6 if c["mag"] >= 6 else 3 if c["mag"] >= 3 else 2 if c["mag"] >= 2 else 1 days.append(day_index(c["date"])) kinds.append(0) levels.append(lev) for _, _d, di in gle: days.append(di) kinds.append(1) levels.append(99) days = np.array(days, dtype=np.int64) kinds = np.array(kinds, dtype=np.int64) levels = np.array(levels, dtype=np.int64) o = np.lexsort((kinds, days)) return days[o], kinds[o], levels[o], added def set_masks(kinds, levels): """Boolean masks for the five merged data sets, in SET_NAMES order. Same-day GLE and flare pairs both count, as in the paper's merger (72 + 37 = 109).""" return [(kinds == 1) | (levels >= lv) & (kinds == 0) for lv in SET_LEVELS] def clusters(days, w): """Single-linkage clusters on sorted days with gap <= w. Returns integer ids.""" gaps = np.diff(days) return np.concatenate(([0], np.cumsum(gaps > w))) def decluster_mask(days, mask, w): """Mask of first events of clusters, with clusters built among the events of this set alone.""" idx = np.where(mask)[0] cid = clusters(days[idx], w) first = np.concatenate(([True], np.diff(cid) > 0)) out = np.zeros_like(mask) out[idx[first]] = True return out def z_direct(days, T): """Eq. (1) at one period, or an array of periods.""" days = np.asarray(days, dtype=float) T = np.atleast_1d(T).astype(float) ph = 2 * np.pi * np.outer(days, 1.0 / T) return (np.cos(ph).sum(axis=0) ** 2 + np.sin(ph).sum(axis=0) ** 2) / days.size def resultant(days, f): return np.exp(2j * np.pi * f * np.asarray(days, dtype=float)).sum() def z_grid(days): """z on the frequency grid k = 0..KMAX for one list of integer days (events may repeat).""" arr = np.bincount(np.asarray(days, dtype=np.int64) + OFFSET, minlength=LTOTAL).astype(float) F = sfft.rfft(arr, n=NFFT)[: KMAX + 1] return (F.real ** 2 + F.imag ** 2) / len(days) def z_batch(day_matrix, mask, workers=8): """z on the grid for a batch: day_matrix has shape (draws, events), integer days. mask picks the events of a set. Returns (draws, KMAX+1) float64.""" sub = day_matrix[:, mask] + OFFSET n, m = sub.shape if sub.min() < 0 or sub.max() >= LTOTAL: raise ValueError("event index outside array") idx = sub + (np.arange(n)[:, None] * LTOTAL) arr = np.bincount(idx.ravel(), minlength=n * LTOTAL).reshape(n, LTOTAL).astype(float) F = sfft.rfft(arr, n=NFFT, axis=1, workers=workers)[:, : KMAX + 1] return (F.real ** 2 + F.imag ** 2) / m def window_max(z): """Running maximum over +-HALF bins, along the last axis.""" return maximum_filter1d(z, size=2 * HALF + 1, axis=-1, mode="nearest") def line_bins(freqs): return np.round(np.asarray(freqs) / DF).astype(int) def scores_from_M(M, centres, kmin=0): """M: running maximum, shape (..., KMAX+1). centres: integer bins, shape (L,). Returns C, B, F with shape (..., L): central, core side-band, full side-band scores. Windows centred below bin kmin are dropped (a side band of a short period should not reach the long-period peaks of the solar cycle). The default keeps them, clipped at bin 0.""" centres = np.asarray(centres) C = M[..., centres] cb = centres[:, None] + CORE_BINS[None, :] fb = centres[:, None] + FULL_BINS[None, :] if kmin: cm, fm = cb >= kmin, fb >= kmin B = (np.take(M, np.clip(cb, 0, KMAX), axis=-1) * cm).max(axis=-1) Fu = (np.take(M, np.clip(fb, 0, KMAX), axis=-1) * fm).max(axis=-1) return C, B, Fu cb = np.clip(cb, 0, KMAX) fb = np.clip(fb, 0, KMAX) B = M[..., cb].max(axis=-1) Fu = M[..., fb].max(axis=-1) return C, B, Fu def load_family(name): d = np.load(os.path.join(OUT, f"sets_{name}.npz")) return d["days"], d["kinds"], d["levels"] def rank_p_obs(null, obs): """(1 + #null >= obs) / (n + 1), element-wise over all but the first axis of null.""" return (1.0 + (null >= obs).sum(axis=0)) / (null.shape[0] + 1.0) def rank_p_null(null): """For each draw the fraction of draws at least as high, along axis 0 (ties share the larger p).""" return rankdata(-null, axis=0, method="max") / null.shape[0] def save_json(path, obj): with open(path, "w", newline="\n", encoding="utf-8") as f: json.dump(obj, f, indent=1, sort_keys=False, default=lambda o: o.tolist() if hasattr(o, "tolist") else str(o)) f.write("\n")