"""Test 2, corrected after review (RULES_post_review.txt): the thesis's reading of its superposed epoch analyses at the 95th percentile, as its figures show its lists of peaks were made, with the 97.5th percentile of our first run alongside; and three sensitivity variants of the null. usage: py -3.12 -I sea_null_p95.py [n_series] part: mean | median | trend | phi06 | flat | shift Needs numpy and scipy. Reads the crossing list written by make_lists.py and the fitted model written by sea_null.py (out/sea_null_.json); writes out/sea_null_p95__.json. The model, the random dates and the seeds are sea_null.py's, so at the 97.5th percentile the first series reproduce that script's counts. Written for factchecked.science, 2026-11-15. """ 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 PARTS = {'mean': ('mean', False, 'cos', None, 'thesis', 1000, 1), 'median': ('median', False, 'cos', None, 'thesis', 200, 2), 'trend': ('mean', True, 'cos', None, 'thesis', 200, 3), 'phi06': ('mean', False, 'cos', 0.6, 'thesis', 200, 4), 'flat': ('mean', False, 'flat', None, 'thesis', 200, 5), 'shift': ('mean', False, 'cos', None, 'shift', 200, 6)} outdir, tag, part = sys.argv[1], sys.argv[2], sys.argv[3] STAT, TREND, SEASON, PHI_OVERRIDE, DATES, N_SERIES, SEED = PARTS[part] if len(sys.argv) > 4: N_SERIES = int(sys.argv[4]) 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] panels[name] = {'epochs': full[elig[mask]], 'gaps': np.diff(full)} model = json.load(open(os.path.join(outdir, f'sea_null_{tag}.json'), encoding='utf-8'))['synthetic_model'] A, PHI, SIG = float(model['A']), float(model['phi']), float(model['sigma']) if PHI_OVERRIDE is not None: PHI = PHI_OVERRIDE 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]) phase = np.cos(2 * np.pi * (doy - 196) / 365.25) if SEASON == 'cos': season = A * phase else: # flat-topped season: tanh-shaped, amplitude tuned like sea_null.py's A to the 78% summer share shape = np.tanh(3 * phase) / np.tanh(3) def share(b): s = np.exp(b * shape) return s[summer].sum() / s.sum() Bs = np.arange(0.3, 2.01, 0.01) B = float(Bs[np.argmin([abs(share(b) - 0.78) for b in Bs])]) season = B * shape def random_epochs(gaps, n, rng_): """Thesis-style fake epochs, exactly as sea_null.py makes them.""" 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)]) def shift_sets(name, k=1000, seed=1): """Sensitivity: the real list shifted circularly by a random offset (spacing kept, season not).""" r = np.random.default_rng(seed) lo, hi = MARGIN, N - 1 - MARGIN span = hi - lo + 1 ep = panels[name]['epochs'] return np.array([np.sort(lo + (ep - lo + int(r.integers(0, span))) % span) for _ in range(k)]) if DATES == 'thesis': MC = {name: make_sets(name, 1000, i + 7) for i, name in enumerate(panels)} else: MC = {name: shift_sets(name, 1000, i + 500) for i, name in enumerate(panels)} def simulate(r_): eps = r_.standard_normal((1, N + 500)) * SIG * np.sqrt(1 - PHI ** 2) a = lfilter([1.0], [1.0, -PHI], eps, axis=1)[:, 500:] # 500-day burn-in, as sea_null.py x = np.exp(season[None, :] + a) if TREND: x = x * np.linspace(1.0, 1.6, N)[None, :] return x[0] def sea_sets(x, sets, stat): out = np.empty((sets.shape[0], len(LAGS))) for j, l in enumerate(LAGS): v = x[sets + l] out[:, j] = v.mean(axis=1) if stat == 'mean' else np.median(v, axis=1) return out WINDOWS = [(-29, -25), (-15, -12), (-2, 2), (12, 15), (25, 29)] W0 = (LAGS >= -2) & (LAGS <= 2) PCTS = (95.0, 97.5) def counts(obs, mc): out = {} for q in PCTS: ex = obs > np.percentile(mc, q, axis=0) H = sum(bool(ex[(LAGS >= a) & (LAGS <= b)].any()) for (a, b) in WINDOWS) out[q] = (int(ex.sum()), int(H), bool(ex[W0].any())) return out rec = {q: {'E': [], 'H': [], 'H_All': [], 'any0': []} for q in PCTS} desc = {'mean_over_median': [], 'max_over_mean': [], 'r1': [], 'summer_share': []} r_ = np.random.default_rng(SEED) for s in range(N_SERIES): x = simulate(r_) if s < 50: desc['mean_over_median'].append(x.mean() / np.median(x)) desc['max_over_mean'].append(x.max() / x.mean()) desc['r1'].append(np.corrcoef(x[:-1], x[1:])[0, 1]) desc['summer_share'].append(x[summer].sum() / x.sum()) tot = {q: [0, 0, 0, False] for q in PCTS} for name in ('All', 'T-A', 'A-T'): ep = panels[name]['epochs'] v = x[ep[:, None] + LAGS[None, :]] obs = v.mean(axis=0) if STAT == 'mean' else np.median(v, axis=0) c = counts(obs, sea_sets(x, MC[name], STAT)) for q in PCTS: E_, H_, z = c[q] tot[q][0] += E_ tot[q][1] += H_ if name == 'All': tot[q][2] = H_ tot[q][3] = tot[q][3] or z for q in PCTS: rec[q]['E'].append(tot[q][0]) rec[q]['H'].append(tot[q][1]) rec[q]['H_All'].append(tot[q][2]) rec[q]['any0'].append(tot[q][3]) def summary(d): E, H, HA, z = (np.array(d[k]) for k in ('E', 'H', 'H_All', 'any0')) return {'E_tot_mean': round(float(E.mean()), 2), 'E_tot_p95': float(np.percentile(E, 95)), 'H_tot_mean': round(float(H.mean()), 2), 'H_tot_p95': float(np.percentile(H, 95)), 'H_tot_hist': {int(k): int(v) for k, v in zip(*np.unique(H, return_counts=True))}, 'n_H_tot_ge_10': int(np.sum(H >= 10)), 'P_H_tot_ge_10': round(float(np.mean(H >= 10)), 4), 'n_H_tot_ge_7': int(np.sum(H >= 7)), 'P_H_tot_ge_7': round(float(np.mean(H >= 7)), 4), 'P_H_All_ge_4': round(float(np.mean(HA >= 4)), 4), 'P_E_tot_ge_30': round(float(np.mean(E >= 30)), 4), 'P_E_tot_ge_33': round(float(np.mean(E >= 33)), 4), 'P_any_panel_hit_in_minus2_plus2': round(float(np.mean(z)), 4)} res = {'list': tag, 'part': part, 'n_series': N_SERIES, 'stat': STAT, 'trend': TREND, 'season': SEASON, 'random_dates': DATES, 'seed': SEED, 'n_epochs': {k: int(len(v['epochs'])) for k, v in panels.items()}, 'model': {'A': A, 'phi': PHI, 'sigma': SIG, 'season_amplitude': (A if SEASON == 'cos' else B), 'season_shape': ('cosine in log' if SEASON == 'cos' else 'tanh(3 cos)/tanh(3) in log')}, 'simulated_series_first_50': {k: round(float(np.mean(v)), 3) for k, v in desc.items()}, 'at_95th_percentile': summary(rec[95.0]), 'at_97_5th_percentile': summary(rec[97.5])} with open(os.path.join(outdir, f'sea_null_p95_{tag}_{part}.json'), 'w', encoding='utf-8', newline='\n') as f: json.dump(res, f, indent=1) print(json.dumps(res, indent=1))