"""Test 4 (RULES_r1_sea.txt): does NCEP/NCAR R1 show the thesis's ERA5 precipitation and surface-pressure behaviour around HCS crossings, and does it survive a shifted-list null? usage: py -3.12 -I r1_sea.py Needs numpy and netCDF4. The shifted-list null was corrected after review (RULES_post_review.txt). """ 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 WINDOWS = [(-29, -25), (-15, -12), (-2, 2), (12, 15), (25, 29)] 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')): panels[name] = {'epochs': idx_all[mask & elig], 'gaps': np.diff(idx_all[mask])} 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) MC = {} for i, name in enumerate(panels): r = np.random.default_rng(100 + i) MC[name] = np.array([random_epochs(panels[name]['gaps'], len(panels[name]['epochs']), r) for _ in range(1000)]) def sea(x, ep): return x[ep[:, None] + LAGS[None, :]].mean(axis=0) def sea_sets(x, sets): 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 read_counts(obs, mc): hi = np.percentile(mc, 97.5, axis=0) lo = np.percentile(mc, 2.5, axis=0) ex = obs > hi H = sum(bool(ex[(LAGS >= a) & (LAGS <= b)].any()) for (a, b) in WINDOWS) # added after review: the thesis's own reading, above the 95th percentile (RULES_post_review.txt) ex95 = obs > np.percentile(mc, 95, axis=0) H95 = sum(bool(ex95[(LAGS >= a) & (LAGS <= b)].any()) for (a, b) in WINDOWS) return {'E_upper': int(ex.sum()), 'E_lower': int((obs < lo).sum()), 'H': int(H), 'upper_lags': LAGS[ex].tolist(), 'lower_lags': LAGS[obs < lo].tolist(), 'E_upper_p95': int(ex95.sum()), 'H_p95': int(H95), 'upper_lags_p95': LAGS[ex95].tolist()} def shifted_lists(ep_idx): """The real list shifted by whole years give or take 15 days. Corrected after review (RULES_post_review.txt): a crossing pushed past the end of the eligible range now wraps back by 14 years (5,114 days), keeping its season, instead of by the range's 5,033 days, which put wrapped crossings about 80 days off season; a crossing that then lands before the start is dropped.""" lo, hi = MARGIN, N - 1 - MARGIN back = int(round(365.25 * 14)) out = [] for k in range(1, 14): for dlt in range(-15, 16): d = int(round(365.25 * k + dlt)) q = ep_idx + d q = np.where(q > hi, q - back, q) out.append(np.sort(q[q >= lo])) return out res = {'list': tag, 'n_epochs': {k: int(len(v['epochs'])) for k, v in panels.items()}, 'note': 'NCEP/NCAR R1 is not ERA5; box 30-50N, 125-60W, cell centres inside'} series = {} for kind in ('prate', 'pres'): for wt in (True, False): dd, x = C.read_r1_box(os.path.join(dl, 'ncep-r1'), kind, range(2010, 2024), weighted=wt) assert dd[0] == D0 and dd[-1] == D1 and len(dd) == N, (dd[0], dd[-1], len(dd)) series[(kind, wt)] = x res['box_means'] = { 'prate_mm_per_day_weighted_mean': round(float(series[('prate', True)].mean()), 3), 'prate_mm_per_hour_weighted_mean': round(float(series[('prate', True)].mean() / 24), 4), 'prate_by_month_mm_per_day': {m: round(float(series[('prate', True)][[d.month == m for d in dates]].mean()), 3) for m in range(1, 13)}, 'pres_hPa_weighted_mean': round(float(series[('pres', True)].mean()), 2), 'pres_hPa_unweighted_mean': round(float(series[('pres', False)].mean()), 2), 'pres_by_month_hPa': {m: round(float(series[('pres', True)][[d.month == m for d in dates]].mean()), 2) for m in range(1, 13)}, 'pres_anomaly_sd_hPa': round(float(C.harmonic_anomaly(dates, series[('pres', True)]).std()), 3), 'prate_anomaly_sd_mm_day': round(float(C.harmonic_anomaly(dates, series[('prate', True)]).std()), 3), } # 1. thesis-style descriptive counts on raw series desc = {} curves = {} for kind in ('prate', 'pres'): x = series[(kind, True)] desc[kind] = {} curves[kind] = {} for name in panels: obs = sea(x, panels[name]['epochs']) mc = sea_sets(x, MC[name]) desc[kind][name] = read_counts(obs, mc) curves[kind][name] = {'sea': np.round(obs, 4).tolist(), 'mc_p2_5': np.round(np.percentile(mc, 2.5, axis=0), 4).tolist(), 'mc_p97_5': np.round(np.percentile(mc, 97.5, axis=0), 4).tolist(), 'mc_p5': np.round(np.percentile(mc, 5, axis=0), 4).tolist(), 'mc_p95': np.round(np.percentile(mc, 95, axis=0), 4).tolist(), 'mc_mean': np.round(mc.mean(axis=0), 4).tolist()} desc[kind]['E_upper_tot'] = sum(desc[kind][n]['E_upper'] for n in panels) desc[kind]['H_tot'] = sum(desc[kind][n]['H'] for n in panels) desc[kind]['E_upper_tot_p95'] = sum(desc[kind][n]['E_upper_p95'] for n in panels) desc[kind]['H_tot_p95'] = sum(desc[kind][n]['H_p95'] for n in panels) res['thesis_style_raw'] = desc # 2. primary statistics on anomalies, with shifted-list and random-epoch nulls anom = {kind: C.harmonic_anomaly(dates, series[(kind, True)]) for kind in ('prate', 'pres')} anom_uw = {kind: C.harmonic_anomaly(dates, series[(kind, False)]) for kind in ('prate', 'pres')} w0 = (LAGS >= -2) & (LAGS <= 2) wE = ((LAGS >= -29) & (LAGS <= -25)) | w0 | ((LAGS >= 25) & (LAGS <= 29)) w03 = (LAGS >= 0) & (LAGS <= 3) def stats_for(epochs_all, epochs_ta, epochs_at, A): p = sea(A['prate'], epochs_all) P1 = p[w0].mean() P2 = p[wE].mean() S1 = sea(A['pres'], epochs_ta)[w03].mean() - sea(A['pres'], epochs_at)[w03].mean() return P1, P2, S1 def run_tests(A): ep = {n: panels[n]['epochs'] for n in panels} obs = stats_for(ep['All'], ep['T-A'], ep['A-T'], A) shA, shT, shB = shifted_lists(ep['All']), shifted_lists(ep['T-A']), shifted_lists(ep['A-T']) # shift T-A and A-T lists by the same offsets as All so the pair keeps its relation null = np.array([stats_for(a, t, b, A) for a, t, b in zip(shA, shT, shB)]) rnd = np.array([stats_for(MC['All'][i], MC['T-A'][i], MC['A-T'][i], A) for i in range(1000)]) out = {} for j, nm in enumerate(('P1_precip_lags_-2_2', 'P2_precip_echo_windows', 'S1_pressure_TA_minus_AT_lags_0_3')): o = obs[j] out[nm] = {'observed': round(float(o), 4), 'p_shifted_two_sided': round(float((1 + np.sum(np.abs(null[:, j]) >= abs(o))) / (1 + len(null))), 4), 'null_shifted_sd': round(float(null[:, j].std()), 4), 'p_random_epochs_two_sided': round(float((1 + np.sum(np.abs(rnd[:, j] - rnd[:, j].mean()) >= abs(o - rnd[:, j].mean()))) / 1001), 4), 'null_random_sd': round(float(rnd[:, j].std()), 4)} return out res['primary_anomaly_tests_weighted'] = run_tests(anom) res['primary_anomaly_tests_unweighted'] = run_tests(anom_uw) # anomaly SEA curves for the record res['anomaly_curves'] = {kind: {n: np.round(sea(anom[kind], panels[n]['epochs']), 4).tolist() for n in panels} for kind in ('prate', 'pres')} res['lags'] = LAGS.tolist() with open(os.path.join(outdir, f'r1_sea_{tag}.json'), 'w', encoding='utf-8', newline='\n') as f: json.dump(res, f, indent=1) with open(os.path.join(outdir, f'r1_sea_curves_{tag}.json'), 'w', encoding='utf-8', newline='\n') as f: json.dump({'lags': LAGS.tolist(), 'raw_curves_and_bands': curves}, f) short = {k: v for k, v in res.items() if k not in ('anomaly_curves', 'lags')} print(json.dumps(short, indent=1))