"""Test 2 (RULES_sea_null.txt): echo overlap and the false-positive rate of the thesis's reading of its superposed epoch analyses, using series with no link to the crossings. usage: py -3.12 -I sea_null.py [n_mean] [n_median] [n_trend] Needs numpy and scipy. Reads the crossing list written by make_lists.py. """ import datetime as dt import json import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import numpy as np # noqa: E402 from scipy.signal import lfilter # noqa: E402 import common as C # noqa: E402 outdir, tag = sys.argv[1], sys.argv[2] N_MEAN = int(sys.argv[3]) if len(sys.argv) > 3 else 200 N_MED = int(sys.argv[4]) if len(sys.argv) > 4 else 100 N_TREND = int(sys.argv[5]) if len(sys.argv) > 5 else 100 rng = np.random.default_rng(20261115) D0, D1 = dt.date(2010, 1, 1), dt.date(2023, 12, 31) dates = C.daterange(D0, D1) N = len(dates) LAGS = np.arange(-40, 41) MARGIN = 40 rows = C.read_crossings_csv(os.path.join(outdir, f'crossings_P2_{tag}.csv')) idx_all = np.array([(d - D0).days for d, _ in rows]) dir_all = np.array([r for _, r in rows]) elig = (idx_all >= MARGIN) & (idx_all <= N - 1 - MARGIN) panels = {} for name, mask in (('All', np.ones(len(rows), bool)), ('T-A', dir_all == 'T-A'), ('A-T', dir_all == 'A-T')): full = idx_all[mask] gaps = np.diff(full) panels[name] = {'epochs': full[elig[mask]], 'gaps': gaps} res = {'list': tag, 'n_epochs': {k: int(len(v['epochs'])) for k, v in panels.items()}} # ---------------- Part A: echo overlap e = panels['All']['epochs'] dset_all = set(idx_all.tolist()) dirmap = dict(zip(idx_all.tolist(), dir_all.tolist())) def frac_with(offsets, same=None): k = 0 for t in e: hit = False for o in offsets: u = t + o if u in dset_all: if same is None or (same and dirmap[u] == dirmap[t]) or (same is False and dirmap[u] != dirmap[t]): hit = True break k += hit return round(k / len(e), 3) res['echo_overlap'] = { 'frac_with_crossing_25_29_days_later_any': frac_with(range(25, 30)), 'frac_with_crossing_25_29_days_later_same_direction': frac_with(range(25, 30), True), 'frac_with_crossing_25_29_days_earlier_any': frac_with(range(-29, -24)), 'frac_with_opposite_crossing_12_15_days_later': frac_with(range(12, 16), False), 'frac_with_opposite_crossing_12_15_days_earlier': frac_with(range(-15, -11), False), } def random_epochs(gaps, n, rng_): """Thesis-style fake epochs: random start, intervals resampled from observed gaps, wrapped circularly inside the eligible range.""" lo, hi = MARGIN, N - 1 - MARGIN span = hi - lo + 1 L = int(gaps.max()) t = lo + int(rng_.integers(0, L)) out = [t] while len(out) < n: t = t + int(rng_.choice(gaps)) out.append(t) out = np.array(out) return np.sort(lo + (out - lo) % span) def make_sets(name, k=1000, seed=1): r = np.random.default_rng(seed) p = panels[name] return np.array([random_epochs(p['gaps'], len(p['epochs']), r) for _ in range(k)]) MC = {name: make_sets(name, 1000, i + 7) for i, name in enumerate(panels)} def sea_mean(x, ep): return x[ep[:, None] + LAGS[None, :]].mean(axis=0) def sea_mean_sets(x, sets): # sets: (k, n) -> (k, 81) out = np.empty((sets.shape[0], len(LAGS))) for j, l in enumerate(LAGS): out[:, j] = x[sets + l].mean(axis=1) return out def sea_median_sets(x, sets): out = np.empty((sets.shape[0], len(LAGS))) for j, l in enumerate(LAGS): out[:, j] = np.median(x[sets + l], axis=1) return out # white-noise correlation between SEA(0) and SEA(+27) k0, k27, km27 = list(LAGS).index(0), list(LAGS).index(27), list(LAGS).index(-27) a0, a27, r0, r27 = [], [], [], [] for s in range(2000): w = rng.standard_normal(N) sv = sea_mean(w, panels['All']['epochs']) a0.append(sv[k0]); a27.append(sv[k27]) rs = MC['All'][s % 1000] sr = sea_mean(w, rs) r0.append(sr[k0]); r27.append(sr[k27]) res['echo_whitenoise_corr_lag0_lag27'] = {'real_crossings': round(float(np.corrcoef(a0, a27)[0, 1]), 3), 'thesis_style_random_sets': round(float(np.corrcoef(r0, r27)[0, 1]), 3)} # ---------------- synthetic lightning-like model, tuned once doy = np.array([d.timetuple().tm_yday for d in dates]) summer = np.array([C.in_season(d, (3, 15), (9, 15)) for d in dates]) def share(A): s = np.exp(A * np.cos(2 * np.pi * (doy - 196) / 365.25)) return s[summer].sum() / s.sum() As = np.arange(0.6, 2.01, 0.01) A = float(As[np.argmin([abs(share(a) - 0.78) for a in As])]) def simulate(phi, sigma, r_, n_series=1, trend=False): s = A * np.cos(2 * np.pi * (doy - 196) / 365.25) eps = r_.standard_normal((n_series, N + 500)) * sigma * np.sqrt(1 - phi ** 2) a = lfilter([1.0], [1.0, -phi], eps, axis=1)[:, 500:] # 500-day burn-in x = np.exp(s[None, :] + a) if trend: x = x * np.linspace(1.0, 1.6, N)[None, :] return x def stats(x): r1 = np.mean([np.corrcoef(v[:-1], v[1:])[0, 1] for v in x]) mm = np.mean([v.mean() / np.median(v) for v in x]) sh = np.mean([v[summer].sum() / v.sum() for v in x]) return r1, mm, sh best = None tr = np.random.default_rng(99) for phi in np.arange(0.30, 0.91, 0.05): for sigma in np.arange(0.30, 1.51, 0.05): x = simulate(phi, sigma, tr, 20) r1, mm, sh = stats(x) loss = ((r1 - 0.717) / 0.717) ** 2 + ((mm - 1.29) / 1.29) ** 2 + ((sh - 0.78) / 0.78) ** 2 if best is None or loss < best[0]: best = (loss, phi, sigma, r1, mm, sh) # fine search around the best _, phi0, sig0 = best[0], best[1], best[2] for phi in np.arange(phi0 - 0.05, phi0 + 0.051, 0.01): for sigma in np.arange(sig0 - 0.05, sig0 + 0.051, 0.01): if not (0 < phi < 1 and sigma > 0): continue x = simulate(phi, sigma, tr, 30) r1, mm, sh = stats(x) loss = ((r1 - 0.717) / 0.717) ** 2 + ((mm - 1.29) / 1.29) ** 2 + ((sh - 0.78) / 0.78) ** 2 if loss < best[0]: best = (loss, phi, sigma, r1, mm, sh) PHI, SIG = float(best[1]), float(best[2]) res['synthetic_model'] = {'A': A, 'phi': PHI, 'sigma': SIG, 'fit_r1': round(float(best[3]), 3), 'fit_mean_over_median': round(float(best[4]), 3), 'fit_summer_share': round(float(best[5]), 3), 'targets': {'r1': 0.717, 'mean_over_median': 1.29, 'summer_share': 0.78}} WINDOWS = [(-29, -25), (-15, -12), (-2, 2), (12, 15), (25, 29)] def read_counts(obs, mc): """obs: (81,), mc: (k,81) -> exceedance mask, E, H""" hi = np.percentile(mc, 97.5, axis=0) ex = obs > hi E = int(ex.sum()) H = 0 for (w0, w1) in WINDOWS: sel = (LAGS >= w0) & (LAGS <= w1) H += bool(ex[sel].any()) return ex, E, H def counts_from_lags(lags): ex = np.isin(LAGS, lags) H = sum(bool(ex[(LAGS >= w0) & (LAGS <= w1)].any()) for (w0, w1) in WINDOWS) return int(ex.sum()), H thesis = { 'USA_mean': {'All': [-27, -7, 0, 11, 12, 16, 27, 39, 40], 'T-A': [-27, -14, 11, 12, 13, 24, 39, 40], 'A-T': [-27, -9, 2, 4, 16, 27, 28, 30, 31, 33, 34, 36, 37]}, 'USA_median': {'All': [-27, -23, -7, 2, 9, 11, 12, 15, 16, 27, 30, 37, 39, 40], 'T-A': [-3, 11, 13, 39, 40], 'A-T': [-35, -38, -9, 2, 4, 16, 27, 28, 30, 31, 33, 34, 36, 37]}, } tc = {} for key, d in thesis.items(): tc[key] = {} Et = Ht = 0 for p, lags in d.items(): E_, H_ = counts_from_lags(lags) tc[key][p] = {'E': E_, 'H': H_} Et += E_; Ht += H_ tc[key]['E_tot'] = Et; tc[key]['H_tot'] = Ht res['thesis_counts_under_our_rule'] = tc def run(n_series, stat='mean', trend=False, seed=2024): r_ = np.random.default_rng(seed) Etot, Htot, HAll, any0, E_panels = [], [], [], [], [] for s in range(n_series): x = simulate(PHI, SIG, r_, 1, trend)[0] Et = Ht = 0 h_all = 0 z = False for name in ('All', 'T-A', 'A-T'): ep = panels[name]['epochs'] if stat == 'mean': obs = sea_mean(x, ep) mc = sea_mean_sets(x, MC[name]) else: obs = np.median(x[ep[:, None] + LAGS[None, :]], axis=0) mc = sea_median_sets(x, MC[name]) ex, E_, H_ = read_counts(obs, mc) Et += E_; Ht += H_ if name == 'All': h_all = H_ if ex[(LAGS >= -2) & (LAGS <= 2)].any(): z = True Etot.append(Et); Htot.append(Ht); HAll.append(h_all); any0.append(z) Etot, Htot, HAll = np.array(Etot), np.array(Htot), np.array(HAll) return {'n_series': n_series, 'stat': stat, 'trend': trend, 'E_tot_mean': round(float(Etot.mean()), 2), 'E_tot_p95': float(np.percentile(Etot, 95)), 'H_tot_mean': round(float(Htot.mean()), 2), 'H_tot_p95': float(np.percentile(Htot, 95)), 'H_tot_hist': {int(k): int(v) for k, v in zip(*np.unique(Htot, return_counts=True))}, 'P_H_All_ge_4': round(float(np.mean(HAll >= 4)), 3), 'P_H_tot_ge_10': round(float(np.mean(Htot >= 10)), 3), 'P_H_tot_ge_7': round(float(np.mean(Htot >= 7)), 3), 'P_E_tot_ge_30': round(float(np.mean(Etot >= 30)), 3), 'P_E_tot_ge_33': round(float(np.mean(Etot >= 33)), 3), 'P_any_panel_hit_in_minus2_plus2': round(float(np.mean(any0)), 3)} # diagnostics: seasonal composition of the real epochs against the thesis-style random sets. # "seasonal level" = mean over the epochs of the model's expected seasonal factor exp(s(t)), # i.e. the SEA level a series with this seasonal cycle and no crossing effect would show. sfac = np.exp(A * np.cos(2 * np.pi * (doy - 196) / 365.25)) diag = {} for name in panels: ep = panels[name]['epochs'] real = float(sfac[ep].mean()) rnd = sfac[MC[name]].mean(axis=1) diag[name] = {'real_level': round(real, 4), 'random_mean': round(float(rnd.mean()), 4), 'random_sd': round(float(rnd.std()), 4), 'z': round(float((real - rnd.mean()) / rnd.std()), 2), 'pct_of_epochs_Jun_Sep': round(100 * float(np.mean([dates[i].month in (6, 7, 8, 9) for i in ep])), 1)} res['seasonal_composition'] = diag # echo dependence under an autocorrelated null: does a window hit at [-2,2] make one at [25,29] likelier? r_ = np.random.default_rng(77) both = only0 = only27 = neither = 0 both_r = only0_r = only27_r = neither_r = 0 w0 = (LAGS >= -2) & (LAGS <= 2) w27 = (LAGS >= 25) & (LAGS <= 29) for s in range(60): x = simulate(PHI, SIG, r_, 1, False)[0] mc = sea_mean_sets(x, MC['All']) hi = np.percentile(mc, 97.5, axis=0) ex = sea_mean(x, panels['All']['epochs']) > hi h0, h27 = ex[w0].any(), ex[w27].any() both += h0 and h27; only0 += h0 and not h27; only27 += h27 and not h0; neither += not (h0 or h27) exr = mc[:200] > hi[None, :] h0r, h27r = exr[:, w0].any(axis=1), exr[:, w27].any(axis=1) both_r += int(np.sum(h0r & h27r)); only0_r += int(np.sum(h0r & ~h27r)) only27_r += int(np.sum(h27r & ~h0r)); neither_r += int(np.sum(~(h0r | h27r))) res['echo_window_cooccurrence_autocorrelated_null'] = { 'real_crossings_60_series': {'both': int(both), 'only_0': int(only0), 'only_27': int(only27), 'neither': int(neither)}, 'random_sets_60x200': {'both': both_r, 'only_0': only0_r, 'only_27': only27_r, 'neither': neither_r}} res['null_mean_stationary'] = run(N_MEAN, 'mean', False, 1) res['null_median_stationary'] = run(N_MED, 'median', False, 2) res['null_mean_trend'] = run(N_TREND, 'mean', True, 3) with open(os.path.join(outdir, f'sea_null_{tag}.json'), 'w', encoding='utf-8', newline='\n') as f: json.dump(res, f, indent=1) print(json.dumps(res, indent=1))