"""Diagnostic (post hoc, descriptive): where in lag does the crossings' seasonal spread push a superposed epoch analysis of a seasonal series, relative to the thesis-style random epochs? For each lag, the "seasonal level" is the mean, over the epochs, of a seasonal factor: (a) the synthetic lightning model's exp(A cos(2 pi (doy-196)/365.25)), and (b) R1 USA-box precipitation climatology (mean + 4 harmonics). z(lag) = (real-list level - mean of 1000 random sets) / sd of the random sets. usage: py -3.12 -I seasonal_bias.py Needs numpy and netCDF4. """ 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 import common as C # noqa: E402 dl, outdir, tag = sys.argv[1], sys.argv[2], sys.argv[3] 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) par = json.load(open(os.path.join(outdir, 'sea_null_RC.json'), encoding='utf-8'))['synthetic_model'] doy = np.array([d.timetuple().tm_yday for d in dates], dtype=float) sfac = np.exp(par['A'] * np.cos(2 * np.pi * (doy - 196) / 365.25)) _, pr = C.read_r1_box(os.path.join(dl, 'ncep-r1'), 'prate', range(2010, 2024)) pclim = pr - C.harmonic_anomaly(dates, pr) def random_epochs(gaps, n, r): lo, hi = MARGIN, N - 1 - MARGIN span = hi - lo + 1 t = lo + int(r.integers(0, int(gaps.max()))) out = [t] while len(out) < n: t += int(r.choice(gaps)) out.append(t) return np.sort(lo + (np.array(out) - lo) % span) res = {'list': tag} for name, mask in (('All', np.ones(len(rows), bool)), ('T-A', dir_all == 'T-A'), ('A-T', dir_all == 'A-T')): ep = idx_all[mask & elig] gaps = np.diff(idx_all[mask]) r = np.random.default_rng(5) sets = np.array([random_epochs(gaps, len(ep), r) for _ in range(1000)]) out = {} for fname, fac in (('synthetic_lightning_season', sfac), ('R1_precip_climatology', pclim)): real = np.array([fac[ep + l].mean() for l in LAGS]) rnd = np.array([[fac[s + l].mean() for l in LAGS] for s in sets]) z = (real - rnd.mean(axis=0)) / rnd.std(axis=0) out[fname] = {'z_at_lags': {int(l): round(float(v), 2) for l, v in zip(LAGS, z)}, 'n_lags_z_gt_1.96': int(np.sum(z > 1.96)), 'max_z': round(float(z.max()), 2), 'lag_of_max_z': int(LAGS[np.argmax(z)])} res[name] = out with open(os.path.join(outdir, f'seasonal_bias_{tag}.json'), 'w', encoding='utf-8', newline='\n') as f: json.dump(res, f, indent=1) for name in ('All', 'T-A', 'A-T'): for fname in ('synthetic_lightning_season', 'R1_precip_climatology'): o = res[name][fname] zz = o['z_at_lags'] print(name, fname, 'n z>1.96:', o['n_lags_z_gt_1.96'], 'max z', o['max_z'], 'at', o['lag_of_max_z'], '| z(-27,0,+27):', zz[-27], zz[0], zz[27])