#!/usr/bin/env python
"""Later additions, RULES.txt entries 13, 17 and 18: chosen after seeing the results, sensitivity checks that decide nothing.
The whole-burst statistic by burst gap, dropping the largest bursts, later flares at other thresholds, what the bar means under C, peaks near
146 d, the walk at the tallest peak near 146 d, and long periods under other rate models.
python -I 19_later_checks.py --store
Writes ../out/later_checks.json. sets_R.npz is used if present.
"""
import argparse
import datetime as dt
import importlib.util
import json
import os
import sys
import numpy as np
from scipy.stats import norm
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
for name, fn in (("null05", "05_null.py"), ("later17", "17_later_draws.py")):
spec = importlib.util.spec_from_file_location(name, os.path.join(HERE, fn))
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
globals()[name] = mod
ap = argparse.ArgumentParser()
ap.add_argument("--store", required=True)
ap.add_argument("--draws", type=int, default=20000)
a = ap.parse_args()
days, kinds, levels = rr.load_family("N")
masks = rr.set_masks(kinds, levels)
W = 7
nine = np.array([rr.PERIODS[n] for n in rr.NAMES])
T0 = 629.29
out = dict(note="Later additions, RULES.txt entries 13, 17, 18. Chosen after seeing the results: sensitivity checks.")
cid = rr.clusters(days, W)
out["bursts"] = dict(X1_GLE=int(cid.max()) + 1, X10_GLE_own=int(rr.clusters(days[masks[0]], W).max()) + 1, X1_bursts_touched_by_X10_GLE=int(np.unique(cid[masks[0]]).size))
# ---- the whole-burst statistic by burst gap, entry 17 ------------------------------------------------------------
rng = np.random.default_rng(20261109)
def z_robust(d, c, T, draws=400000):
ph = np.exp(2j * np.pi * d / T)
Rc = np.bincount(c, weights=ph.real) + 1j * np.bincount(c, weights=ph.imag)
Rc = Rc[np.abs(Rc) > 0]
den = (np.abs(Rc) ** 2).sum()
zr = float(np.abs(Rc.sum()) ** 2 / den)
hits = 0
for start in range(0, draws, 20000):
th = rng.random((min(20000, draws - start), Rc.size)) * 2 * np.pi
hits += int(((np.abs((Rc * np.exp(1j * th)).sum(axis=1)) ** 2 / den) >= zr).sum())
return zr, (1 + hits) / (draws + 1), int(Rc.size)
d10 = days[masks[0]].astype(float)
rows = []
for w in (1, 3, 7, 14, 27):
c = rr.clusters(days[masks[0]], w)
zr, p, nb = z_robust(d10, c, T0)
first = rr.decluster_mask(days, masks[0], w)
rows.append(dict(gap=w, bursts=nb, z_first_event=round(float(rr.z_direct(days[first], T0)[0]), 2), z_whole_burst=round(zr, 2), p_random_phase=round(p, 5)))
reg = later17.event_regions(days, kinds, levels)
c_r = np.unique(reg[masks[0]], return_inverse=True)[1]
zr, p, nb = z_robust(d10, c_r, T0)
out["whole_burst_X10_GLE_629"] = dict(by_gap=rows, by_active_region=dict(bursts=nb, z_whole_burst=round(zr, 2), p_random_phase=round(p, 5)))
print(out["whole_burst_X10_GLE_629"], flush=True)
# ---- dropping the largest bursts and redrawing B', entry 17 --------------------------------------------------------
sizes = np.bincount(cid)
order = np.argsort(-sizes, kind="stable")
first_of = np.concatenate(([0], np.where(np.diff(cid) > 0)[0] + 1))
drop_rows = []
# Three bursts tie for fifth place at 12 events, and which of them go matters, so the ties are reported both ways.
tied = [int(b) for b in order if sizes[b] == sizes[order[5]]]
choices = [(str(k), [int(b) for b in order[:k]], 20261110 + k) for k in (0, 1, 2, 4, 6)]
choices.append(("6, the other two of the tie", [int(b) for b in order[:4]] + tied[-2:], 20261170))
choices.append(("7, all of the tie", [int(b) for b in order[:4]] + tied, 20261180))
for k, dropping, seed_k in choices:
keep = ~np.isin(cid, dropping)
d_, ki, le = days[keep], kinds[keep], levels[keep]
ms = rr.set_masks(ki, le)
mv = null05.Mover(d_, W, "Bp", seed_k)
c_ = mv.cid
nc = mv.nc
Eo = np.array([rr.z_direct(d_[m], nine) for m in ms])
rcs = np.zeros((5, 9, nc), dtype=complex)
Ns = np.array([m.sum() for m in ms], dtype=float)
for i, m in enumerate(ms):
for j, T in enumerate(nine):
ph = np.exp(2j * np.pi * d_[m] / T)
rcs[i, j] = np.bincount(c_[m], weights=ph.real, minlength=nc) + 1j * np.bincount(c_[m], weights=ph.imag, minlength=nc)
En = np.zeros((a.draws, 5, 9), dtype=np.float32)
done = 0
while done < a.draws:
m_ = min(500, a.draws - done)
sh = mv.shifts(m_)
for j, T in enumerate(nine):
rot = np.exp(2j * np.pi * sh / T)
tot = (rcs[:, j, None, :] * rot[None, :, :]).sum(axis=2)
En[done : done + m_, :, j] = ((tot.real ** 2 + tot.imag ** 2) / Ns[:, None]).T
done += m_
En = En.astype(float)
n = En.shape[0]
p = (1 + (En >= Eo).sum(axis=0)) / (n + 1)
med = np.median(En, axis=0)
rd, ro = (En / med).max(axis=1), (Eo / med).max(axis=0)
wd, wo = En.max(axis=1), Eo.max(axis=0)
pf = lambda s, o: round(float((1 + (s >= o).sum()) / (n + 1)), 5)
ix = {nm: i for i, nm in enumerate(rr.SET_NAMES)}
drop_rows.append(
dict(
dropped=k,
dropped_starts=[str(rr.EPOCH + dt.timedelta(days=int(days[cid == b].min()))) for b in dropping],
dropped_events=int(sizes[dropping].sum()) if dropping else 0,
events_by_set=[int(x) for x in Ns],
z_629={s: round(float(Eo[ix[s], 0]), 2) for s in ("X10+GLE", "X6+GLE", "X1+GLE")},
p_629={s: round(float(p[ix[s], 0]), 5) for s in ("X10+GLE", "X6+GLE", "X1+GLE")},
z_74={s: round(float(Eo[ix[s], 7]), 2) for s in ("X10+GLE", "X6+GLE", "X1+GLE")},
p_74={s: round(float(p[ix[s], 7]), 5) for s in ("X10+GLE", "X6+GLE", "X1+GLE")},
group_exact=dict(ratio=pf(rd.sum(axis=1), ro.sum()), raw=pf(wd.sum(axis=1), wo.sum()), ratio_without_629=pf(rd[:, 1:].sum(axis=1), ro[1:].sum()), raw_without_629=pf(wd[:, 1:].sum(axis=1), wo[1:].sum())),
)
)
print(drop_rows[-1], flush=True)
out["dropping_largest_bursts"] = dict(draws=a.draws, null="Bp, redrawn", largest=[dict(events=int(sizes[i]), start=str(rr.EPOCH + dt.timedelta(days=int(days[cid == i].min())))) for i in order[:6]], rows=drop_rows)
# ---- later flares at other thresholds, exploratory, entry 17 ---------------------------------------------------------
first_idx = np.concatenate(([0], np.where(np.diff(cid) > 0)[0] + 1))
anchor = days[first_idx]
ev_anchor = anchor[cid]
last_idx = np.concatenate((first_idx[1:] - 1, [days.size - 1]))
span = (days[last_idx] - days[first_idx]).astype(np.int64)
last_day = int(days.max())
cut = rr.day_index(dt.date(2018, 1, 1))
idx_part = np.where((anchor >= cut) & (anchor <= last_day))[0]
sh_part, _ = rr_place.place_jitter(10000, anchor[idx_part].astype(np.int64), span[idx_part], W, cut, last_day, 20261111, 0.0, 1.0, 0.0, 365)
f0 = 1 / T0
def v_test(sel, phi):
d = days[sel].astype(float)
c = cid[sel]
uniq, inv = np.unique(c, return_inverse=True)
ph = np.exp(2j * np.pi * f0 * 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 * phi)).real / den)
pos = np.searchsorted(idx_part, uniq)
Vb = ((Rc[None, :] * np.exp(2j * np.pi * f0 * sh_part[:, pos])).sum(axis=1) * np.exp(-1j * phi)).real / den
return dict(V=round(V, 3), p=round(float((1 + (Vb >= V).sum()) / 10001), 4), p_normal=round(float(norm.sf(V)), 4), events=int(d.size), bursts=int(uniq.size))
pre = ev_anchor < cut
post = ev_anchor >= cut
later = {}
for label, base in (("GLE + flares above X10, before 2018", masks[0] & pre), ("GLE alone, before 2018", (kinds == 1) & pre)):
phi = float(np.angle(rr.resultant(days[base], f0)))
row = dict(phase_deg=round(float(np.degrees(phi) % 360), 1))
for th, nm in ((6, "X6+"), (3, "X3+"), (2, "X2+"), (1, "X1+")):
row[nm] = v_test((kinds == 0) & (levels >= th) & post, phi)
later[label] = row
out["later_flares_by_threshold"] = later
print(later, flush=True)
# ---- what the bar means under C, entry 18 ---------------------------------------------------------------------------
ev = json.load(open(os.path.join(rr.OUT, "eval_N.json"), encoding="utf-8"))
split = json.load(open(os.path.join(rr.OUT, "split_N.json"), encoding="utf-8"))
lat = np.load(os.path.join(a.store, "later_N_C_W7.npz"))
pstar = ev["nulls"]["C"]["clustered"]["raw_p_that_clears_5pct"]
bar = {}
for s, i in (("X10+GLE", 0), ("X1+GLE", 4)):
aligned = split["phasors"][s]["P629"]["z_if_all_aligned"]
z_ex = float(np.percentile(lat["exact"][:, i, 0], 100 * (1 - pstar)))
z_c = ev["nulls"]["C"]["clustered"]["central_z_needed"][i][0]
bar[s] = dict(z_if_all_aligned=aligned, observed=split["phasors"][s]["P629"]["z_total"], exact_z_at_bar=round(z_ex, 2), exact_share=round(z_ex / aligned, 3), central_z_at_bar=z_c, central_share=round(z_c / aligned, 3), observed_share=round(split["phasors"][s]["P629"]["z_total"] / aligned, 3))
out["bar_under_C"] = dict(raw_p=pstar, rows=bar)
print(out["bar_under_C"], flush=True)
# ---- peaks near 146 d and 199 d, and the walk at the tallest peak near 146 d, entry 18 --------------------------------
def local_maxima(z, tlo, thi):
k0, k1 = int(rr.NFFT / thi), int(rr.NFFT / tlo)
seg = z[k0 - 1 : k1 + 2]
lm = (seg[1:-1] > seg[:-2]) & (seg[1:-1] >= seg[2:])
return [dict(T=round(rr.NFFT / (i + k0), 2), z=round(float(z[i + k0]), 2)) for i in np.where(lm)[0]]
peaks = {}
fams = ["N"] + (["R"] if os.path.exists(os.path.join(rr.OUT, "sets_R.npz")) else [])
for fam in fams:
d_, ki, le = rr.load_family(fam)
ms = rr.set_masks(ki, le)
row = {}
for s, i in (("X10+GLE", 0), ("X6+GLE", 1), ("X3+GLE", 2), ("X2+GLE", 3), ("X1+GLE", 4)):
z = rr.z_grid(d_[ms[i]])
row[s] = dict(z_at_145_99=round(float(rr.z_direct(d_[ms[i]], 145.99)[0]), 2), maxima_145_148=local_maxima(z, 145.0, 148.0))
peaks[fam] = row
tol_146 = 145.99 ** 2 / rr.TSPAN
tol_199 = 199.43 ** 2 / rr.TSPAN
out["peaks_near_146"] = dict(by_family=peaks, tolerance_days_at_145_99=round(tol_146, 3), tolerance_days_at_199_43=round(tol_199, 3))
print(out["peaks_near_146"], flush=True)
starts = np.array([rr.day_index(s) for _, s in rr.CYCLE_STARTS])
ev_cycle = np.searchsorted(starts, ev_anchor, side="right") - 1
z1 = rr.z_grid(days[masks[4]])
k0, k1 = int(rr.NFFT / 148), int(rr.NFFT / 141)
kp = k0 + int(np.argmax(z1[k0 : k1 + 1]))
Tp = rr.NFFT / kp
walk = {}
Rs = []
for c, (cn, _) in enumerate(rr.CYCLE_STARTS):
sel = masks[4] & (ev_cycle == c)
if sel.sum() == 0:
continue
R = rr.resultant(days[sel], 1 / Tp)
Rs.append(R)
walk[cn] = dict(N=int(sel.sum()), phase_deg=int(round(float(np.degrees(np.angle(R)) % 360))))
Rs = np.array(Rs)
out["walk_at_tallest_peak"] = dict(T=round(Tp, 2), z=round(float(z1[kp]), 2), share_of_lined_up=round(float(abs(Rs.sum()) / np.abs(Rs).sum()), 3), distance_from_145_99_percent=round(abs(Tp - 145.99) / 145.99 * 100, 2), cycles=walk)
print(out["walk_at_tallest_peak"], flush=True)
# ---- long periods under other rate models, entry 13 ---------------------------------------------------------------------
long_bins = rr.line_bins([1 / t for t in (2100.0, 2570.0, 3150.0, 4043.0, 7810.0)])
lo = np.array([rr.window_max(rr.z_grid(days[m]))[long_bins] for m in masks])
longs = dict(T=[2100, 2570, 3150, 4043, 7810], observed=np.round(lo, 1).tolist())
for null in ("Ek", "Ek180", "Ekw"):
path = os.path.join(a.store, f"later_N_{null}_W7.npz")
if not os.path.exists(path):
continue
lp = np.load(path)["longp"].astype(float)
longs[null] = dict(draws=int(lp.shape[0]), mean=np.round(lp.mean(axis=0), 1).tolist(), p=np.round((1 + (lp >= lo).sum(axis=0)) / (lp.shape[0] + 1), 4).tolist())
longs["Ap"] = dict(draws=ev["nulls"]["Ap"]["draws"], mean=ev["nulls"]["Ap"]["long_periods"]["null_mean"], p=ev["nulls"]["Ap"]["long_periods"]["p"])
out["long_periods_by_rate_model"] = longs
print({k: (v["p"] if isinstance(v, dict) else v) for k, v in longs.items()}, flush=True)
rr.save_json(os.path.join(rr.OUT, "later_checks.json"), out)
print("written")