#!/usr/bin/env python
"""Draws under the nulls of rule 9. Writes one .npz per family, null and W into --store.
python -I 05_null.py --family N --null A --w 7 --draws 20000 --store
Saved: C, B, F scores with shape (draws, 10 sets, 9 periods); the first five sets are clustered, the
last five declustered at this W. gmax with shape (draws, 10, 2): highest z in 50-850 d and 50-350 d.
longp with shape (draws, 5, 5): z in the windows at 2100, 2570, 3150, 4043, 7810 d for the five clustered
sets. mean_z with shape (10, KMAX+1). env with percentile curves for X10+GLE and X1+GLE from the first 2000 draws.
"""
import argparse
import csv
import datetime as dt
import os
import sys
import time
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import rr_core as rr # noqa: E402
import rr_place # noqa: E402
def months_table():
"""(year, month) -> sunspot weight: 13-month smoothed where given, monthly mean after that."""
d = os.path.join(rr.DL, "silso-sunspots")
ms = {}
for r in csv.reader(open(os.path.join(d, "SN_ms_tot_V2.0.csv")), delimiter=";"):
ms[(int(r[0]), int(r[1]))] = float(r[3])
mm = {}
for r in csv.reader(open(os.path.join(d, "SN_m_tot_V2.0.csv")), delimiter=";"):
mm[(int(r[0]), int(r[1]))] = float(r[3])
out = {}
for k in mm:
out[k] = ms[k] if ms.get(k, -1) >= 0 else mm[k]
return out
def cycle_of(day):
starts = np.array([rr.day_index(s) for _, s in rr.CYCLE_STARTS])
return np.searchsorted(starts, day, side="right") - 1
def month_grid(cycle, last_day):
"""Arrays (start day, days in month, weight) for one cycle's months inside the record."""
starts = [s for _, s in rr.CYCLE_STARTS]
a = starts[cycle]
b = starts[cycle + 1] if cycle + 1 < len(starts) else (rr.EPOCH + dt.timedelta(days=int(last_day) + 1))
a = max(a, dt.date(1956, 1, 1))
tab = months_table()
st, nd, w = [], [], []
y, m = a.year, a.month
while dt.date(y, m, 1) < b:
s = dt.date(y, m, 1)
e = dt.date(y + (m == 12), m % 12 + 1, 1)
di = rr.day_index(s)
n = (e - s).days
st.append(di)
nd.append(n)
w.append(max(tab[(y, m)], 0.0) * n)
y, m = y + (m == 12), m % 12 + 1
w = np.array(w, dtype=float)
return np.array(st), np.array(nd), w / w.sum()
class Mover:
def __init__(self, days, w, null, seed):
self.days = days
self.null = null
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))
self.anchor = days[first]
self.last = int(days.max())
self.ccycle = cycle_of(self.anchor)
self.rng = np.random.default_rng(seed)
self.w = int(w)
self.fails = 0
lastev = np.concatenate((first[1:] - 1, [days.size - 1]))
self.span = (days[lastev] - days[first]).astype(np.int64)
if null == "A":
self.grid = {c: month_grid(c, self.last) for c in np.unique(self.ccycle)}
if null == "Ap":
cyc = np.unique(self.ccycle)
remap = {c: i for i, c in enumerate(cyc)}
self.cc = np.array([remap[c] for c in self.ccycle], dtype=np.int64)
offs, st_all, nd_all, cdf_all = [0], [], [], []
for c in cyc:
st, nd, wgt = month_grid(c, self.last)
st_all.append(st)
nd_all.append(nd)
cdf_all.append(np.cumsum(wgt))
offs.append(offs[-1] + st.size)
self.c_off = np.array(offs, dtype=np.int64)
self.m_start = np.concatenate(st_all).astype(np.int64)
self.m_nd = np.concatenate(nd_all).astype(np.int64)
self.m_cdf = np.concatenate(cdf_all)
def shifts(self, n):
"""Cluster shifts, shape (n, clusters)."""
rng = self.rng
if self.null == "Bp":
sd = int(rng.integers(1, 2 ** 31 - 1))
out, f = rr_place.place_jitter(n, self.anchor.astype(np.int64), self.span, self.w, 0, self.last, sd, 0.0, 1.0, 0.0, 365)
self.fails += int(f)
return out
if self.null == "Ap":
sd = int(rng.integers(1, 2 ** 31 - 1))
out, f = rr_place.place_months(n, self.anchor.astype(np.int64), 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
if self.null == "A":
s = np.zeros((n, self.nc), dtype=np.int64)
for c, (st, nd, w) in self.grid.items():
idx = np.where(self.ccycle == c)[0]
if idx.size == 0:
continue
pick = rng.choice(w.size, size=(n, idx.size), p=w)
new = st[pick] + np.floor(rng.random((n, idx.size)) * nd[pick]).astype(np.int64)
s[:, idx] = new - self.anchor[idx]
return s
if self.null == "B":
sh = 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
if self.null == "C":
per = rng.integers(-2000, 2001, size=(n, len(rr.CYCLE_STARTS)))
return per[:, self.ccycle]
raise ValueError(self.null)
def matrix(self, n):
return self.days[None, :] + self.shifts(n)[:, self.cid]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--family", required=True)
ap.add_argument("--null", required=True)
ap.add_argument("--w", type=int, default=7)
ap.add_argument("--draws", type=int, default=20000)
ap.add_argument("--batch", type=int, default=200)
ap.add_argument("--workers", type=int, default=24)
ap.add_argument("--store", required=True)
a = ap.parse_args()
seed = 20261104 + sum(ord(c) for c in a.family + a.null) * 1000 + a.w
days, kinds, levels = rr.load_family(a.family)
masks = rr.set_masks(kinds, levels)
dmasks = [rr.decluster_mask(days, m, a.w) for m in masks]
allm = masks + dmasks
mv = Mover(days, a.w, a.null, seed)
print(a, "clusters", mv.nc, "events", days.size, "seed", seed, flush=True)
centres = rr.line_bins([1 / rr.PERIODS[n] for n in rr.NAMES])
long_bins = rr.line_bins([1 / t for t in (2100.0, 2570.0, 3150.0, 4043.0, 7810.0)])
k850, k350, k50 = int(rr.NFFT / 850), int(rr.NFFT / 350), int(rr.NFFT / 50)
n = a.draws
C = np.zeros((n, 10, 9), dtype=np.float32)
B = np.zeros((n, 10, 9), dtype=np.float32)
F = np.zeros((n, 10, 9), dtype=np.float32)
gmax = np.zeros((n, 10, 2), dtype=np.float32)
longp = np.zeros((n, 5, 5), dtype=np.float32)
mean_z = np.zeros((10, rr.KMAX + 1))
env_n = min(2000, n)
env = {0: np.zeros((env_n, rr.KMAX + 1), dtype=np.float32), 4: np.zeros((env_n, rr.KMAX + 1), dtype=np.float32)}
t0 = time.time()
done = 0
while done < n:
m = min(a.batch, n - done)
mat = mv.matrix(m)
for i, mask in enumerate(allm):
z = rr.z_batch(mat, mask, workers=a.workers)
mean_z[i] += z.sum(axis=0)
M = rr.window_max(z)
c, b, f = rr.scores_from_M(M, centres)
C[done : done + m, i] = c
B[done : done + m, i] = b
F[done : done + m, i] = f
gmax[done : done + m, i, 0] = z[:, k850 : k50 + 1].max(axis=1)
gmax[done : done + m, i, 1] = z[:, k350 : k50 + 1].max(axis=1)
if i < 5:
longp[done : done + m, i] = M[:, long_bins]
if i in env and done < env_n:
keep = min(m, env_n - done)
env[i][done : done + keep] = z[:keep]
done += m
if done % (a.batch * 10) == 0:
print(done, round(time.time() - t0, 1), flush=True)
mean_z /= n
pct = {}
for i, arr in env.items():
pct[f"env{i}"] = np.percentile(arr, [50, 95, 99.9], axis=0).astype(np.float32)
os.makedirs(a.store, exist_ok=True)
np.savez(
os.path.join(a.store, f"null_{a.family}_{a.null}_W{a.w}.npz"),
C=C,
B=B,
F=F,
gmax=gmax,
longp=longp,
mean_z=mean_z.astype(np.float32),
seed=seed,
nclusters=mv.nc,
**pct,
)
print("saved", round(time.time() - t0, 1), "placements that failed the no-overlap rule:", mv.fails, flush=True)
if __name__ == "__main__":
main()