#!/usr/bin/env python """Rule 12: split-record tests, per-cycle phasors, leave-one-cycle-out, the held-out test of P629, and rule 15's cycle-by-cycle look at 130 to 190 days. python -I 07_split.py --family N Writes ../out/split_.json """ import argparse import datetime as dt import json import os import sys import numpy as np from scipy.stats import norm sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import rr_core as rr # noqa: E402 import rr_place # noqa: E402 ap = argparse.ArgumentParser() ap.add_argument("--family", default="N") ap.add_argument("--draws", type=int, default=10000) a = ap.parse_args() fam = a.family days, kinds, levels = rr.load_family(fam) masks = rr.set_masks(kinds, levels) W = 7 cid_all = rr.clusters(days, W) first_idx = np.concatenate(([0], np.where(np.diff(cid_all) > 0)[0] + 1)) anchor_all = days[first_idx] ev_anchor = anchor_all[cid_all] last_idx = np.concatenate((first_idx[1:] - 1, [days.size - 1])) span_all = (days[last_idx] - days[first_idx]).astype(np.int64) nine_T = np.array([rr.PERIODS[n] for n in rr.NAMES]) last_day = int(days.max()) rng = np.random.default_rng(20261105) centres = rr.line_bins(1 / nine_T) out = dict(family=fam, W=W) K50, K1000 = int(rr.NFFT / 50), int(rr.NFFT / 1000) def med_level(z): return float(np.median(z[K1000 : K50 + 1])) _cache = {} def part_shifts(lo, hi, draws, rng): """Null B' confined to [lo, hi]: all clusters whose first event lies there, no overlap. One set of draws per interval, so tests on the same part share it.""" key = (lo, hi, draws) if key not in _cache: idx = np.where((anchor_all >= lo) & (anchor_all <= hi))[0] sd = int(rng.integers(1, 2 ** 31 - 1)) sh, f = rr_place.place_jitter(draws, anchor_all[idx].astype(np.int64), span_all[idx], W, lo, hi, sd, 0.0, 1.0, 0.0, 365) _cache[key] = (idx, sh, int(f)) return _cache[key] def v_test(d_idx, f, phi1, lo, hi, draws, rng): """V for the events d_idx (indices into days) at frequency f against phase phi1. Clusters are the family's W = 7 clusters. Null B' confined to [lo, hi].""" if d_idx.size == 0: return dict(V=None, p=None, p_normal=None, N=0) idx, sh, fails = part_shifts(lo, hi, draws, rng) d = days[d_idx].astype(float) cid = cid_all[d_idx] uniq, inv = np.unique(cid, return_inverse=True) ph = np.exp(2j * np.pi * f * d) Rc = np.bincount(inv, weights=ph.real) + 1j * np.bincount(inv, weights=ph.imag) den = np.sqrt((np.abs(Rc) ** 2).sum() / 2) V = float((Rc.sum() * np.exp(-1j * phi1)).real / den) pos = np.searchsorted(idx, uniq) Vb = (Rc[None, :] * np.exp(2j * np.pi * f * sh[:, pos])).sum(axis=1) Vb = (Vb * np.exp(-1j * phi1)).real / den p = float((1 + (Vb >= V).sum()) / (draws + 1)) return dict(V=round(V, 3), p=round(p, 4), p_normal=round(float(norm.sf(V)), 4), N=int(d_idx.size), clusters=int(uniq.size)) def part_masks(boundary): return ev_anchor < boundary, ev_anchor >= boundary splits = {"S1_midpoint": (int(days.min()) + last_day) // 2, "S2_1996": rr.day_index(dt.date(1996, 1, 1))} out["splits"] = {k: dict(boundary_day=v, date=str(rr.EPOCH + dt.timedelta(days=v))) for k, v in splits.items()} res = {} for sname, boundary in splits.items(): p1, p2 = part_masks(boundary) z1s = [rr.z_grid(days[m & p1]) for m in masks] meds = [med_level(z) for z in z1s] tab = {} for k, nm in enumerate(rr.NAMES): c = centres[k] # (i) selected: best set and frequency in central + core windows of part 1 best = (-1, None, None) for j, z in enumerate(z1s): for off in rr.CORE_BINS: lo_, hi_ = c + off - rr.HALF, c + off + rr.HALF seg = z[lo_ : hi_ + 1] / meds[j] i = int(np.argmax(seg)) if seg[i] > best[0]: best = (float(seg[i]), j, lo_ + i) j_sel = best[1] f_sel = best[2] * rr.DF d1 = days[masks[j_sel] & p1] phi1 = float(np.angle(rr.resultant(d1, f_sel))) idx2 = np.where(masks[j_sel] & p2)[0] sel = v_test(idx2, f_sel, phi1, boundary, last_day, a.draws, rng) sel.update(set=rr.SET_NAMES[j_sel], T=round(1 / f_sel, 2), z_part1=round(float(rr.z_direct(d1, 1 / f_sel)[0]), 2), z_part2=round(float(rr.z_direct(days[idx2], 1 / f_sel)[0]), 2) if idx2.size else None) # (ii) exact: set chosen in part 1 at the theoretical period, no search in frequency f0 = 1 / nine_T[k] vals = [float(rr.z_direct(days[m & p1], nine_T[k])[0]) / meds[i] for i, m in enumerate(masks)] j_ex = int(np.argmax(vals)) d1 = days[masks[j_ex] & p1] phi1 = float(np.angle(rr.resultant(d1, f0))) idx2 = np.where(masks[j_ex] & p2)[0] ex = v_test(idx2, f0, phi1, boundary, last_day, a.draws, rng) ex.update(set=rr.SET_NAMES[j_ex], z_part1=round(float(rr.z_direct(d1, nine_T[k])[0]), 2), z_part2=round(float(rr.z_direct(days[idx2], nine_T[k])[0]), 2) if idx2.size else None, phase_part1_deg=round(np.degrees(phi1) % 360, 1)) if idx2.size: ex["phase_part2_deg"] = round(float(np.degrees(np.angle(rr.resultant(days[idx2], f0))) % 360), 1) tab[nm] = dict(selected=sel, exact=ex) res[sname] = tab out["split"] = res surv = {} for nm in rr.NAMES: s = {} for ver in ("selected", "exact"): s[ver] = [res[sp][nm][ver]["p"] for sp in splits] s["passes"] = any(all(x is not None and x <= 0.05 for x in s[ver]) for ver in ("selected", "exact")) surv[nm] = s out["split_pass"] = surv # ---- the same test on decoy lines (addition, DEVIATIONS 7): how often does a line no planet predicts pass? ---- rng_d = np.random.default_rng(20261104) pairs = [] tol2 = 2 / rr.TSPAN real_f2, real_f3 = 1 / 199.43, 1 / 291.96 while len(pairs) < 20000: T2 = np.exp(rng_d.uniform(np.log(140), np.log(280), 400000)) T3 = np.exp(rng_d.uniform(np.log(200), np.log(420), 400000)) f2, f3 = 1 / T2, 1 / T3 dl = f2 - f3 keep = (dl >= 1 / 1200.0) & (dl <= 1 / 350.0) & (2 * f2 + 2 * f3 <= 1 / 45.0) keep &= ~((np.abs(f2 - real_f2) <= tol2) & (np.abs(f3 - real_f3) <= tol2)) pairs.extend(zip(f2[keep].tolist(), f3[keep].tolist())) pairs = np.array(pairs[:20000]) dlines = (pairs[:, 0, None] * rr.COEF_ARR[:, 0][None, :] + pairs[:, 1, None] * rr.COEF_ARR[:, 1][None, :]).ravel() sample = rng_d.choice(dlines[(dlines <= 1 / 50.0) & (dlines >= 1 / 1000.0)], size=3000, replace=False) def normal_v(idx2, f, phi1): if idx2.size == 0: return np.nan ph = np.exp(2j * np.pi * f * days[idx2]) inv = np.unique(cid_all[idx2], return_inverse=True)[1] Rc = np.bincount(inv, weights=ph.real) + 1j * np.bincount(inv, weights=ph.imag) return float((Rc.sum() * np.exp(-1j * phi1)).real / np.sqrt((np.abs(Rc) ** 2).sum() / 2)) decoy_v = {sp: {"selected": np.zeros(sample.size), "exact": np.zeros(sample.size)} for sp in splits} for sname, boundary in splits.items(): p1, p2 = part_masks(boundary) z1s = [rr.z_grid(days[m & p1]) for m in masks] meds = [med_level(z) for z in z1s] for i_, f0 in enumerate(sample): c = int(round(f0 / rr.DF)) best = (-1, None, None) for j, z in enumerate(z1s): for off in rr.CORE_BINS: lo_, hi_ = max(c + off - rr.HALF, 1), min(c + off + rr.HALF, rr.KMAX) seg = z[lo_ : hi_ + 1] / meds[j] i = int(np.argmax(seg)) if seg[i] > best[0]: best = (float(seg[i]), j, lo_ + i) j_sel, f_sel = best[1], best[2] * rr.DF phi1 = float(np.angle(rr.resultant(days[masks[j_sel] & p1], f_sel))) decoy_v[sname]["selected"][i_] = normal_v(np.where(masks[j_sel] & p2)[0], f_sel, phi1) vals = [z1s[j][c] / meds[j] for j in range(5)] j_ex = int(np.argmax(vals)) phi1 = float(np.angle(rr.resultant(days[masks[j_ex] & p1], f0))) decoy_v[sname]["exact"][i_] = normal_v(np.where(masks[j_ex] & p2)[0], f0, phi1) pv = {sp: {k: norm.sf(v) for k, v in d_.items()} for sp, d_ in decoy_v.items()} sp_names = list(splits) pass_sel = (pv[sp_names[0]]["selected"] <= 0.05) & (pv[sp_names[1]]["selected"] <= 0.05) pass_ex = (pv[sp_names[0]]["exact"] <= 0.05) & (pv[sp_names[1]]["exact"] <= 0.05) out["split_decoys"] = dict( lines=int(sample.size), share_pass_selected=round(float(pass_sel.mean()), 4), share_pass_exact=round(float(pass_ex.mean()), 4), share_pass_either=round(float((pass_sel | pass_ex).mean()), 4), ) # rank of the real lines on the exact version: the weaker of the two V values weaker_dec = np.minimum(decoy_v[sp_names[0]]["exact"], decoy_v[sp_names[1]]["exact"]) out["split_decoys"]["rank_of_real_exact"] = {} for nm in rr.NAMES: v1 = res[sp_names[0]][nm]["exact"]["V"] v2 = res[sp_names[1]][nm]["exact"]["V"] w_ = min(v1, v2) out["split_decoys"]["rank_of_real_exact"][nm] = dict(weaker_V=w_, share_of_decoys_at_least=round(float((weaker_dec >= w_).mean()), 4)) # ---- per-cycle phasors, leave-one-cycle-out -------------------------------------------------------- starts = np.array([rr.day_index(s) for _, s in rr.CYCLE_STARTS]) names_c = [n for n, _ in rr.CYCLE_STARTS] ev_cycle = np.searchsorted(starts, ev_anchor, side="right") - 1 ph_out = {} for setname, m in (("X10+GLE", masks[0]), ("X1+GLE", masks[4]), ("X1+GLE declustered", rr.decluster_mask(days, masks[4], W))): ph_out[setname] = {} for k, nm in enumerate(rr.NAMES): T = nine_T[k] row = {} for c, cn in enumerate(names_c): sel = m & (ev_cycle == c) if sel.sum() == 0: row[cn] = dict(N=0) continue R = rr.resultant(days[sel], 1 / T) # what a cycle alone gives: its own z, and its phase row[cn] = dict(N=int(sel.sum()), z=round(float(abs(R) ** 2 / sel.sum()), 2), phase_deg=round(float(np.degrees(np.angle(R)) % 360), 1), Rx=round(float(R.real), 3), Ry=round(float(R.imag), 3)) # how aligned: z total against the sum if all cycles lined up, and against the mean with random phases Rs = np.array([complex(row[c]["Rx"], row[c]["Ry"]) for c in names_c if row[c]["N"] > 0]) N = int(m.sum()) row["z_total"] = round(float(abs(Rs.sum()) ** 2 / N), 2) row["z_if_all_aligned"] = round(float(np.abs(Rs).sum() ** 2 / N), 2) row["z_mean_random_phases"] = round(float((np.abs(Rs) ** 2).sum() / N), 2) row["coherence"] = round(float(abs(Rs.sum()) / np.abs(Rs).sum()), 3) ph_out[setname][nm] = row out["phasors"] = ph_out loo = {} for setname, m in (("X10+GLE", masks[0]), ("X1+GLE", masks[4])): loo[setname] = {} for k, nm in enumerate(rr.NAMES): T = nine_T[k] loo[setname][nm] = {cn: round(float(rr.z_direct(days[m & (ev_cycle != c)], T)[0]), 2) for c, cn in enumerate(names_c)} out["leave_one_cycle_out"] = loo # ---- held-out test of P629 ---------------------------------------------------------------------- cut = rr.day_index(dt.date(2018, 1, 1)) T = 629.29 f = 1 / T kinds_g = kinds == 1 pre = ev_anchor < cut post = ev_anchor >= cut held = {} for label, base in (("GLE + S-list before 2018", masks[0] & pre), ("GLE alone before 2018", kinds_g & pre)): phi = float(np.angle(rr.resultant(days[base], f))) row = dict(N_base=int(base.sum()), phase_deg=round(np.degrees(phi) % 360, 1), z_base=round(float(rr.z_direct(days[base], T)[0]), 2)) idx = np.where(kinds_g & post)[0] row["GLE from 2018"] = v_test(idx, f, phi, cut, last_day, a.draws, rng) dm = rr.decluster_mask(days, (kinds == 0) & post, W) row["X1+ flares from 2018, declustered"] = v_test(np.where(dm)[0], f, phi, cut, last_day, a.draws, rng) idx = np.where((kinds == 0) & post)[0] row["X1+ flares from 2018, all"] = v_test(idx, f, phi, cut, last_day, a.draws, rng) held[label] = row # phase from GLEs, tested on X1+ flares of all years, flares within 3 days of a GLE removed g = days[kinds_g] far = np.array([np.abs(g - d).min() > 3 for d in days]) phi = float(np.angle(rr.resultant(g, f))) held["GLE phase on X1+ flares of all years, none within 3 days of a GLE"] = dict( phase_deg=round(np.degrees(phi) % 360, 1), all_flares=v_test(np.where((kinds == 0) & far)[0], f, phi, int(days.min()), last_day, a.draws, rng), declustered=v_test(np.where(rr.decluster_mask(days, (kinds == 0) & far, W))[0], f, phi, int(days.min()), last_day, a.draws, rng), ) # the same for phases at each theoretical period: GLE phase on flares gle_on_flares = {} for k, nm in enumerate(rr.NAMES): fk = 1 / nine_T[k] ph = float(np.angle(rr.resultant(g, fk))) gle_on_flares[nm] = dict( z_gle=round(float(rr.z_direct(g, nine_T[k])[0]), 2), declustered=v_test(np.where(rr.decluster_mask(days, (kinds == 0) & far, W))[0], fk, ph, int(days.min()), last_day, a.draws, rng), ) held["GLE phase on declustered flares, all nine"] = gle_on_flares out["held_out_P629"] = held # ---- cycle by cycle, 130 to 190 d -------------------------------------------------------------- rieger = {} fl = (kinds == 0) for c, cn in enumerate(names_c): sel = fl & (ev_cycle == c) if sel.sum() < 5: rieger[cn] = dict(N=int(sel.sum())) continue z = rr.z_grid(days[sel]) k0, k1 = int(rr.NFFT / 190), int(rr.NFFT / 130) i = int(np.argmax(z[k0 : k1 + 1])) + k0 dm = rr.decluster_mask(days, sel, W) zd = rr.z_grid(days[dm]) id_ = int(np.argmax(zd[k0 : k1 + 1])) + k0 rieger[cn] = dict(N=int(sel.sum()), peak_T=round(rr.NFFT / i, 1), z=round(float(z[i]), 2), N_declustered=int(dm.sum()), peak_T_declustered=round(rr.NFFT / id_, 1), z_declustered=round(float(zd[id_]), 2), z_at_145_99=round(float(rr.z_direct(days[sel], 145.99)[0]), 2), z_at_154=round(float(rr.z_direct(days[sel], 154.0)[0]), 2), phase_at_145_99=round(float(np.degrees(np.angle(rr.resultant(days[sel], 1 / 145.99))) % 360), 1), phase_at_154=round(float(np.degrees(np.angle(rr.resultant(days[sel], 1 / 154.0))) % 360), 1)) out["rieger_by_cycle"] = rieger rr.save_json(os.path.join(rr.OUT, f"split_{fam}.json"), out) print(json.dumps(out["split_pass"], indent=0)) print(json.dumps(out["split_decoys"], indent=0)) print(json.dumps(out["held_out_P629"], indent=0)[:3500]) print(json.dumps(out["rieger_by_cycle"], indent=0)) for s in ("X10+GLE", "X1+GLE", "X1+GLE declustered"): print(s, {nm: (ph_out[s][nm]["z_total"], ph_out[s][nm]["z_mean_random_phases"], ph_out[s][nm]["z_if_all_aligned"], ph_out[s][nm]["coherence"]) for nm in rr.NAMES})