#!/usr/bin/env python """Later addition, RULES.txt entries 11, 13, 16, 19: chosen after seeing the results, a sensitivity check that decides nothing. Replays nulls A', B', C of the first run by seed and batch size, so the draws are the same ones, and adds what the first run did not keep: exact-period z for all ten sets, pairs of side-band windows, the mean z of each draw, and for B' the percentile curves from all draws. Also draws two further nulls, E and G (entry 13), and two rate-model variants of E for long periods. python -I 17_later_draws.py --store --null Bp [--w 7] [--draws 20000] [--workers 12] null: Ap, Bp, C (replayed); Ek, Gr (new); Ek180, Ekw (new, long periods only, 6,000 draws) Writes /later_N__W.npz. For W other than 7 it replays exact-period z only. """ import argparse import importlib.util import os import sys import time import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import rr_core as rr # noqa: E402 import rr_place # noqa: E402 spec = importlib.util.spec_from_file_location("null05", os.path.join(HERE, "05_null.py")) null05 = importlib.util.module_from_spec(spec) spec.loader.exec_module(null05) def event_regions(days, kinds, levels): """Active-region burst ids for family N, entry 13: one id per event.""" rows = [r for r in rr.read_csv(os.path.join(rr.OUT, "events_noaa_x.csv")) if r["date"] <= "2026-07-04"] by_day = {} for r in rows: try: cls = float(r["reported_class_X"]) except ValueError: cls = 1.0 by_day.setdefault(int(r["day_since_1955_12_31"]), []).append((cls, r["ar"].strip())) for v in by_day.values(): v.sort(key=lambda x: x[0]) # the largest of a day may have gone to the S-list, so the others take the smallest first tan = {int(r["day_since_1955_12_31"]): r["tan2025_ar"].strip() for r in rr.read_csv(os.path.join(rr.OUT, "events_sflares.csv"))} ar = [""] * days.size used = {} for i in np.argsort(days, kind="stable"): if kinds[i] == 1: continue d = int(days[i]) if levels[i] >= 10: ar[i] = tan.get(d, "") else: j = used.get(d, 0) lst = by_day.get(d, []) ar[i] = lst[j][1] if j < len(lst) else "" used[d] = j + 1 lab = -np.ones(days.size, dtype=np.int64) last = {} nxt = 0 numbered = lambda a: a not in ("", "0", "-", "None", "nan") for i in np.argsort(days, kind="stable"): # flares with a number if kinds[i] == 1 or not numbered(ar[i]): continue a = ar[i][-4:] if a in last and days[i] - last[a][1] <= 40: lab[i] = last[a][0] last[a] = (last[a][0], days[i]) else: lab[i] = nxt last[a] = (nxt, days[i]) nxt += 1 for i in np.argsort(days, kind="stable"): # flares with no number if kinds[i] == 1 or lab[i] >= 0: continue near = np.where((lab >= 0) & (np.abs(days - days[i]) <= 1))[0] if near.size: lab[i] = lab[near[np.argmin(np.abs(days[near] - days[i]))]] else: lab[i] = nxt nxt += 1 for i in np.where(kinds == 1)[0]: # GLEs near = np.where((lab >= 0) & (kinds == 0) & (np.abs(days - days[i]) <= 2))[0] if near.size: lab[i] = lab[near[np.argmin(np.abs(days[near] - days[i]))]] else: lab[i] = nxt nxt += 1 return lab class RegionMover: """G: bursts by active region, up to +-365 d, reflected at the ends, overlap allowed.""" def __init__(self, days, kinds, levels, seed): self.days = days self.cid = event_regions(days, kinds, levels) self.nc = int(self.cid.max()) + 1 self.anchor = np.array([days[self.cid == c].min() for c in range(self.nc)], dtype=np.int64) self.last = int(days.max()) self.rng = np.random.default_rng(seed) self.fails = 0 def shifts(self, n): sh = self.rng.integers(-365, 366, size=(n, self.nc)) new = self.anchor + sh new = np.where(new < 0, -new, new) new = np.where(new > self.last, 2 * self.last - new, new) return new - self.anchor class KernelMover: """E: a date in the burst's own cycle, from a Gaussian-smoothed rate of that cycle's real burst dates, no overlap. Whole days.""" def __init__(self, days, w, sigma, weighted, seed): self.days = days self.cid = rr.clusters(days, w) self.nc = int(self.cid.max()) + 1 first = np.concatenate(([0], np.where(np.diff(self.cid) > 0)[0] + 1)) lastev = np.concatenate((first[1:] - 1, [days.size - 1])) self.anchor = days[first].astype(np.int64) self.span = (days[lastev] - days[first]).astype(np.int64) self.w = int(w) self.last = int(days.max()) self.rng = np.random.default_rng(seed) self.fails = 0 cyc = null05.cycle_of(self.anchor) ucyc = np.unique(cyc) remap = {c: i for i, c in enumerate(ucyc)} self.cc = np.array([remap[c] for c in cyc], dtype=np.int64) starts = [rr.day_index(s) for _, s in rr.CYCLE_STARTS] + [self.last + 1] sizes = np.bincount(self.cid) offs, st_all, cdf_all = [0], [], [] for c in ucyc: a, b = max(starts[c], 1), starts[c + 1] d_ = np.arange(a, b, dtype=float) wgt = np.zeros(d_.size) for x, s in zip(self.anchor[cyc == c], sizes[cyc == c]): s_ = float(s) if weighted else 1.0 for xx in (x, 2 * a - x, 2 * b - x): # reflected at the cycle's edges wgt += s_ * np.exp(-0.5 * ((d_ - xx) / sigma) ** 2) wgt += 1e-6 * wgt.max() st_all.append(d_.astype(np.int64)) cdf_all.append(np.cumsum(wgt) / wgt.sum()) offs.append(offs[-1] + d_.size) self.c_off = np.array(offs, dtype=np.int64) self.m_start = np.concatenate(st_all) self.m_nd = np.ones(self.m_start.size, dtype=np.int64) self.m_cdf = np.concatenate(cdf_all) def shifts(self, n): sd = int(self.rng.integers(1, 2 ** 31 - 1)) out, f = rr_place.place_months(n, self.anchor, self.span, self.w, self.cc, self.c_off, self.m_start, self.m_nd, self.m_cdf, self.last, sd) self.fails += int(f) return out def pair_scores(M, centres, kmin): """M: running maximum (draws, KMAX+1). For each line, the best over core modulators of min(upper, lower). Shape (draws, 9).""" out = np.zeros((M.shape[0], centres.size), dtype=np.float32) for off in rr.CORE_BINS[1:6]: # the positive offsets up = M[:, np.clip(centres + off, 0, rr.KMAX)] lo_k = centres - off lo = np.where(lo_k >= kmin, M[:, np.clip(lo_k, 0, rr.KMAX)], 0.0) out = np.maximum(out, np.minimum(up, lo)) return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--family", default="N") ap.add_argument("--null", required=True) ap.add_argument("--w", type=int, default=7) ap.add_argument("--draws", type=int, default=None) ap.add_argument("--batch", type=int, default=200) ap.add_argument("--workers", type=int, default=12) ap.add_argument("--store", required=True) a = ap.parse_args() fam, null, W = a.family, a.null, a.w days, kinds, levels = rr.load_family(fam) masks = rr.set_masks(kinds, levels) dmasks = [rr.decluster_mask(days, m, W) for m in masks] allm = masks + dmasks replay = null in ("Ap", "Bp", "C", "A", "B") n = a.draws or (6000 if null in ("Ek180", "Ekw") else 10000 if W != 7 else 20000) if replay: seed = 20261104 + sum(ord(c) for c in fam + null) * 1000 + W # 05_null.py's seed mv = null05.Mover(days, W, null, seed) stored = np.load(os.path.join(a.store, f"null_{fam}_{null}_W{W}.npz")) assert int(stored["seed"]) == seed elif null == "Gr": mv = RegionMover(days, kinds, levels, 20261107) else: sigma = 180.0 if null == "Ek180" else 365.0 mv = KernelMover(days, W, sigma, null == "Ekw", 20261108 + (null == "Ek180") + 2 * (null == "Ekw")) print(a, "bursts moved", mv.nc, "draws", n, flush=True) nine = np.array([rr.PERIODS[nm] for nm in rr.NAMES]) centres = rr.line_bins(1 / nine) long_bins = rr.line_bins([1 / t for t in (2100.0, 2570.0, 3150.0, 4043.0, 7810.0)]) kmin = int(rr.NFFT / 1500.0) k700, k50, k850 = int(rr.NFFT / 700), int(rr.NFFT / 50), int(rr.NFFT / 850) cid, nc = mv.cid, mv.nc # resultant of each moved burst, per set and period rcs = np.zeros((10, 9, nc), dtype=complex) for i, m in enumerate(allm): d = days[m].astype(float) c = cid[m] for k, T in enumerate(nine): ph = np.exp(2j * np.pi * d / T) rcs[i, k] = np.bincount(c, weights=ph.real, minlength=nc) + 1j * np.bincount(c, weights=ph.imag, minlength=nc) Ns = np.array([m.sum() for m in allm], dtype=float) long_only = null in ("Ek180", "Ekw") do_fft = (W == 7) and not long_only new_null = null in ("Ek", "Gr") exact = np.zeros((n, 10, 9), dtype=np.float32) meanz = np.zeros((n, 5), dtype=np.float32) pairs1 = np.zeros((n, 9), dtype=np.float32) pairs2 = np.zeros((n, 9), dtype=np.float32) longp = np.zeros((n, 5, 5), dtype=np.float32) C = np.zeros((n, 10, 9), dtype=np.float32) if new_null else None B = np.zeros((n, 10, 9), dtype=np.float32) if new_null else None keep_env = (null == "Bp" and W == 7) env = {i: np.zeros((n, k50 - k850 + 1), dtype=np.float32) for i in (0, 4)} if keep_env else {} t0 = time.time() done = 0 checked = False while done < n: m_ = min(a.batch, n - done) sh = mv.shifts(m_) for k, T in enumerate(nine): rot = np.exp(2j * np.pi * sh / T) tot = (rcs[:, k, None, :] * rot[None, :, :]).sum(axis=2) # (10, m_) exact[done : done + m_, :, k] = ((tot.real ** 2 + tot.imag ** 2) / Ns[:, None]).T if do_fft or long_only: mat = days[None, :] + sh[:, cid] best1 = np.zeros((m_, 9), dtype=np.float32) best2 = np.zeros((m_, 9), dtype=np.float32) for i in range(10 if new_null else 5): z = rr.z_batch(mat, allm[i], workers=a.workers) M = rr.window_max(z) if i < 5: meanz[done : done + m_, i] = z[:, k700:k50].mean(axis=1) longp[done : done + m_, i] = M[:, long_bins] if not long_only: best1 = np.maximum(best1, pair_scores(M, centres, kmin)) M2 = rr.maximum_filter1d(z, size=41, axis=-1, mode="nearest") best2 = np.maximum(best2, pair_scores(M2, centres, kmin)) if new_null: c_, b_, _ = rr.scores_from_M(M, centres) C[done : done + m_, i] = c_ B[done : done + m_, i] = b_ if replay and not checked and i < 5: c_, _, _ = rr.scores_from_M(M, centres) diff = float(np.abs(c_ - stored["C"][: m_, i]).max()) assert diff < 1e-3, f"replay differs from the first run: set {i}, {diff}" if i in env: env[i][done : done + m_] = z[:, k850 : k50 + 1] if replay and not checked: checked = True print("replay matches the first run's central scores", flush=True) pairs1[done : done + m_] = best1 pairs2[done : done + m_] = best2 done += m_ if done % (a.batch * 25) == 0: print(done, round(time.time() - t0, 1), flush=True) save = dict(exact=exact, meanz=meanz, pairs1=pairs1, pairs2=pairs2, longp=longp, seed=(seed if replay else 0), fails=mv.fails, nc=nc) if new_null: save.update(C=C, B=B) for i, arr in env.items(): save[f"env{i}"] = np.percentile(arr, [50, 95, 99.9], axis=0).astype(np.float32) if env: save["env_k0"] = k850 if not (do_fft or long_only): for key in ("meanz", "pairs1", "pairs2", "longp"): save.pop(key) if long_only: for key in ("exact", "pairs1", "pairs2"): save.pop(key) np.savez(os.path.join(a.store, f"later_{fam}_{null}_W{W}.npz"), **save) print("saved", round(time.time() - t0, 1), "failed placements", mv.fails, flush=True) if __name__ == "__main__": main()