#!/usr/bin/env python
"""Rule 14: power of the tests, by injecting a phase-stable signal into the real clusters.
Clusters of X1+GLE (family N, W = 7) are placed by null B''s jitter with no overlap, with acceptance weight
1 + 2 r cos(2 pi t / P - phase). Every catalogue then goes through tests (a) to (d), with the null
tables of the real run. r = 0 gives the empirical false-alarm rate of the whole procedure.
python -I 08_power.py --store
--catalogues 200
Writes ../out/power.json. Its last part, a lock confined to the strongest events, is a later addition (RULES.txt entry 14).
"""
import argparse
import datetime as dt
import json
import os
import sys
import time
import numpy as np
from numba import njit
from scipy.stats import norm, rankdata
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("--store", required=True)
ap.add_argument("--catalogues", type=int, default=200)
ap.add_argument("--strong", type=int, default=300)
ap.add_argument("--zero", type=int, default=500)
ap.add_argument("--ndecoy", type=int, default=20000)
ap.add_argument("--pool", type=int, default=2500)
a = ap.parse_args()
days, kinds, levels = rr.load_family("N")
masks = rr.set_masks(kinds, levels)
W = 7
dmasks = [rr.decluster_mask(days, m, W) for m in masks]
allm = masks + dmasks
cid = rr.clusters(days, W)
first_idx = np.concatenate(([0], np.where(np.diff(cid) > 0)[0] + 1))
anchor = days[first_idx]
last_idx = np.concatenate((first_idx[1:] - 1, [days.size - 1]))
span = (days[last_idx] - days[first_idx]).astype(np.int64)
nc = anchor.size
last_day = int(days.max())
nine_T = np.array([rr.PERIODS[n] for n in rr.NAMES])
centres = rr.line_bins(1 / nine_T)
K50, K1000 = int(rr.NFFT / 50), int(rr.NFFT / 1000)
# ---- null tables ---------------------------------------------------------------------------------
tables = {}
for null in ("Ap", "Bp", "C"):
d = np.load(os.path.join(a.store, f"null_N_{null}_W{W}.npz"))
tb = {}
for label, idx in (("clustered", list(range(5))), ("declustered", list(range(5, 10)))):
C = np.sort(d["C"][:, idx, :].astype(float), axis=0)
B = np.sort(d["B"][:, idx, :].astype(float), axis=0)
n = C.shape[0]
# min-p of each draw over the 90 tests (rank within the sorted table)
Cn = d["C"][:, idx, :].astype(float)
Bn = d["B"][:, idx, :].astype(float)
from scipy.stats import rankdata
minp = np.minimum(
(rankdata(-Cn, axis=0, method="max") / n).min(axis=(1, 2)),
(rankdata(-Bn, axis=0, method="max") / n).min(axis=(1, 2)),
)
tb[label] = dict(C=C, B=B, n=n, minp=np.sort(minp))
tables[null] = tb
def adj_p(obs_c, obs_b, tb):
"""obs_*: (5, 9). Returns the adjusted p per line."""
n = tb["n"]
best = np.ones(9)
for i in range(5):
for k in range(9):
pc = (1 + n - np.searchsorted(tb["C"][:, i, k], obs_c[i, k], side="left")) / (n + 1)
pb = (1 + n - np.searchsorted(tb["B"][:, i, k], obs_b[i, k], side="left")) / (n + 1)
best[k] = min(best[k], pc, pb)
return (1 + np.searchsorted(tb["minp"], best, side="right")) / (n + 1)
# ---- decoy pools, same generator as 06_evaluate.py ------------------------------------------------
rng0 = np.random.default_rng(20261104)
real_f2, real_f3 = 1 / 199.43, 1 / 291.96
tol2 = 2 / rr.TSPAN
pairs = []
while len(pairs) < a.ndecoy:
T2 = np.exp(rng0.uniform(np.log(140), np.log(280), 400000))
T3 = np.exp(rng0.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[: a.ndecoy])
lines = (pairs[:, 0, None] * rr.COEF_ARR[:, 0][None, :] + pairs[:, 1, None] * rr.COEF_ARR[:, 1][None, :]).ravel()
pools = []
rng_pool = np.random.default_rng(99)
for k in range(9):
P = nine_T[k]
T = 1 / lines
idx = np.where((T >= P / 1.5) & (T <= P * 1.5) & (np.abs(lines - 1 / P) > tol2))[0]
if idx.size > a.pool:
idx = rng_pool.choice(idx, a.pool, replace=False)
pools.append(rr.line_bins(lines[idx]))
KMIN_DECOY = int(rr.NFFT / 1500.0) # windows at T > 1500 d are dropped for real and decoy lines alike, RULES.txt entries 9 and 14
def decoy_p(MM, line):
"""Rank of a real line in its pool, the set choice paid for. Returns min over C, B of adjusted p."""
from scipy.stats import rankdata as rd
out = 1.0
c0 = centres[[line]]
pool = pools[line]
Cs, Bs, co, bo = [], [], [], []
for M in MM:
c, b, _ = rr.scores_from_M(M, pool, kmin=KMIN_DECOY)
Cs.append(c)
Bs.append(b)
cc, bb, _ = rr.scores_from_M(M, c0, kmin=KMIN_DECOY)
co.append(cc[0])
bo.append(bb[0])
for ds, ob in ((np.array(Cs), np.array(co)), (np.array(Bs), np.array(bo))):
pr = np.maximum((ds >= ob[:, None]).sum(axis=1), 1) / ds.shape[1]
pn = rd(-ds, axis=1, method="max") / ds.shape[1]
minp_pool = pn.min(axis=0)
adj = (1 + (minp_pool <= pr.min()).sum()) / (ds.shape[1] + 1)
out = min(out, adj)
return out
def split_cache(d, anch_ev):
"""Part 1 curves for both splits, once per catalogue."""
cache = {}
for sname, boundary in {"S1": (int(d.min()) + last_day) // 2, "S2": rr.day_index(dt.date(1996, 1, 1))}.items():
p1 = anch_ev < boundary
zs = [rr.z_grid(d[m & p1]) if (m & p1).sum() > 1 else np.zeros(rr.KMAX + 1) for m in masks]
meds = [max(float(np.median(z[K1000 : K50 + 1])), 1e-9) for z in zs]
cache[sname] = (p1, zs, meds)
return cache
def split_p(d, cache, line):
"""Selected and exact versions in both splits, normal approximation for V (cluster-robust)."""
k0 = centres[line]
passes_sel, passes_ex = [], []
for sname, (p1, zs, meds) in cache.items():
p2 = ~p1
best = (-1, 0, 0)
for j, z in enumerate(zs):
for off in rr.CORE_BINS:
lo_, hi_ = k0 + off - rr.HALF, k0 + 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)
vals = [zs[j][k0] / meds[j] for j in range(5)]
for version, (j, f) in (("sel", (best[1], best[2] * rr.DF)), ("ex", (int(np.argmax(vals)), 1 / nine_T[line]))):
base = d[masks[j] & p1]
phi = np.angle(np.exp(2j * np.pi * f * base).sum()) if base.size else 0.0
sel2 = masks[j] & p2
if sel2.sum() == 0:
pv = 1.0
else:
ph = np.exp(2j * np.pi * f * d[sel2])
inv = np.unique(cid[sel2], return_inverse=True)[1]
Rc = np.bincount(inv, weights=ph.real) + 1j * np.bincount(inv, weights=ph.imag)
V = (Rc.sum() * np.exp(-1j * phi)).real / np.sqrt((np.abs(Rc) ** 2).sum() / 2)
pv = float(norm.sf(V))
(passes_sel if version == "sel" else passes_ex).append(pv <= 0.05)
return all(passes_sel) or all(passes_ex)
def make_catalogue(P, r, rng):
phase = rng.uniform(0, 2 * np.pi)
sd = int(rng.integers(1, 2 ** 31 - 1))
sh, f = rr_place.place_jitter(1, anchor.astype(np.int64), span, W, 0, last_day, sd, float(r), float(P), float(phase), 365)
shift = sh[0]
return days + shift[cid], anchor[cid] + shift[cid]
def evaluate(d, anch_ev, lines_to_check):
Zs = [rr.z_grid(d[m]) for m in allm]
MM = [rr.window_max(z) for z in Zs]
cc = np.array([rr.scores_from_M(M, centres)[0] for M in MM])
bb = np.array([rr.scores_from_M(M, centres)[1] for M in MM])
passed = {}
adj = {}
for label, idx in (("clustered", range(5)), ("declustered", range(5, 10))):
worst = np.zeros(9)
for null in tables:
worst = np.maximum(worst, adj_p(cc[list(idx)], bb[list(idx)], tables[null][label]))
adj[label] = worst
res = {}
cache = split_cache(d, anch_ev)
for k in lines_to_check:
a_ok = adj["declustered"][k] <= 0.05
b_ok = adj["clustered"][k] <= 0.05
c_ok = decoy_p(MM, k) <= 0.05
d_ok = split_p(d, cache, k)
res[k] = (a_ok, b_ok, c_ok, d_ok)
return res
out = {}
rng = np.random.default_rng(424242)
t0 = time.time()
# r = 0, all nine lines checked, the false-alarm rate of the procedure
cnt = np.zeros((a.zero, 9, 4), dtype=bool)
for i in range(a.zero):
d, anch = make_catalogue(100.0, 0.0, rng)
r = evaluate(d, anch, range(9))
for k, v in r.items():
cnt[i, k] = v
if (i + 1) % 50 == 0:
print("r=0", i + 1, round(time.time() - t0, 1), flush=True)
out["r0"] = dict(
catalogues=a.zero,
any_line_passes=dict(a=float(cnt[:, :, 0].any(axis=1).mean()), b=float(cnt[:, :, 1].any(axis=1).mean()), c=float(cnt[:, :, 2].any(axis=1).mean()), d=float(cnt[:, :, 3].any(axis=1).mean()), all_four=float(cnt.all(axis=2).any(axis=1).mean())),
per_line_mean=dict(a=float(cnt[:, :, 0].mean()), b=float(cnt[:, :, 1].mean()), c=float(cnt[:, :, 2].mean()), d=float(cnt[:, :, 3].mean())),
)
print(out["r0"], flush=True)
for P, line in ((629.29, 0), (145.99, 3)):
for r_ in (0.1, 0.2, 0.3, 0.4):
c = np.zeros((a.catalogues, 4), dtype=bool)
for i in range(a.catalogues):
d, anch = make_catalogue(P, r_, rng)
c[i] = evaluate(d, anch, [line])[line]
row = dict(a=float(c[:, 0].mean()), b=float(c[:, 1].mean()), c=float(c[:, 2].mean()), d=float(c[:, 3].mean()), all_four=float(c.all(axis=1).mean()))
out[f"P{P}_r{r_}"] = row
print(P, r_, row, round(time.time() - t0, 1), flush=True)
# ---- a lock confined to the strongest events, RULES.txt entry 14: a later addition and a sensitivity check -----------------
@njit
def place_jitter_some(n, anchor_, span_, w, lo, hi, seed, r, period, phase, jit, strong):
"""rr_place.place_jitter, except that only the bursts flagged in strong prefer the phase."""
np.random.seed(seed)
nc_ = anchor_.size
out_ = np.zeros((n, nc_), dtype=np.int64)
off = 1000
size = hi + 3000 + off
for b in range(n):
occ = np.zeros(size, dtype=np.bool_)
order = np.random.permutation(nc_)
for c in order:
x = anchor_[c]
for _ in range(2000):
x = anchor_[c] + np.random.randint(-jit, jit + 1)
if x < lo:
x = 2 * lo - x
if x > hi:
x = 2 * hi - x
if strong[c] and r > 0.0:
if np.random.random() > (1.0 + 2.0 * r * np.cos(2.0 * np.pi * x / period - phase)) / (1.0 + 2.0 * r):
continue
if not occ[max(x - w + off, 0) : x + span_[c] + w + off + 1].any():
break
occ[x + off : x + span_[c] + off + 1] = True
out_[b, c] = x - anchor_[c]
return out_
strong_mask = np.zeros(nc, dtype=np.bool_)
strong_mask[np.unique(cid[masks[0]])] = True
exact_tables = {}
for null in ("Ap", "Bp", "C"):
lat_path = os.path.join(a.store, f"later_N_{null}_W{W}.npz")
if os.path.exists(lat_path):
ex = np.load(lat_path)["exact"][:, :, 0].astype(float) # (draws, 10) at 629.29 d
n_ = ex.shape[0]
rk = rankdata(-ex, axis=0, method="max") / n_
exact_tables[null] = dict(srt=np.sort(ex, axis=0), n=n_, kept=np.sort(rk[:, :5].min(axis=1)), once=np.sort(rk[:, 5:].min(axis=1)))
def within_exact(d):
"""The within-period test at the exact period, worst of the nulls: (bursts kept passes, bursts once passes)."""
zs = np.array([rr.z_direct(d[m], 629.29)[0] for m in allm])
worst = [0.0, 0.0]
for tb in exact_tables.values():
n_ = tb["n"]
ps = (1 + n_ - np.array([np.searchsorted(tb["srt"][:, i], zs[i], side="left") for i in range(10)])) / (n_ + 1)
worst[0] = max(worst[0], (1 + np.searchsorted(tb["kept"], ps[:5].min(), side="right")) / (n_ + 1))
worst[1] = max(worst[1], (1 + np.searchsorted(tb["once"], ps[5:].min(), side="right")) / (n_ + 1))
return worst[0] <= 0.05, worst[1] <= 0.05
rng_s = np.random.default_rng(424243)
strong_rows = {}
for r_ in (0.2, 0.25, 0.3, 0.4, 0.5, 0.6):
c = np.zeros((a.strong, 6), dtype=bool)
ach = np.zeros(a.strong)
for i in range(a.strong):
phase = rng_s.uniform(0, 2 * np.pi)
sd = int(rng_s.integers(1, 2 ** 31 - 1))
sh = place_jitter_some(1, anchor.astype(np.int64), span, W, 0, last_day, sd, float(r_), 629.29, float(phase), 365, strong_mask)
shift = sh[0]
d = days + shift[cid]
anch = anchor[cid] + shift[cid]
c[i, :4] = evaluate(d, anch, [0])[0]
if exact_tables:
c[i, 4:] = within_exact(d)
ach[i] = abs(np.exp(2j * np.pi * d[rr.decluster_mask(days, masks[0], W)] / 629.29).mean())
strong_rows[str(r_)] = dict(
a=float(c[:, 0].mean()),
b=float(c[:, 1].mean()),
c=float(c[:, 2].mean()),
d=float(c[:, 3].mean()),
a_and_b=float((c[:, 0] & c[:, 1]).mean()),
all_four=float(c[:, :4].all(axis=1).mean()),
exact_within_kept=float(c[:, 4].mean()),
exact_within_once=float(c[:, 5].mean()),
achieved_r_in_X10_GLE_bursts=round(float(ach.mean()), 3),
)
print("strongest only", r_, strong_rows[str(r_)], round(time.time() - t0, 1), flush=True)
out["strongest_only_P629"] = dict(catalogues=a.strong, bursts_preferring_the_phase=int(strong_mask.sum()), rows=strong_rows)
# observed r of the clusters at the nine, for comparison
obs = {}
for label, m in (("X1+GLE declustered", dmasks[4]), ("X10+GLE declustered", dmasks[0]), ("GLE alone", kinds == 1)):
row = []
for T in nine_T:
row.append(round(float(np.abs(np.exp(2j * np.pi * days[m] / T).mean())), 3))
obs[label] = row
out["observed_r"] = obs
rr.save_json(os.path.join(rr.OUT, "power.json"), out)
print(obs)