"""Test 3 (RULES_multitaper_null.txt): how many "significant" multitaper peaks does a series with no periodicity produce, and how often do they land on HCS-like periods? usage: py -3.12 -I multitaper_null.py [n_series] Needs numpy, scipy and netCDF4. Uses the tuned synthetic model from sea_null_RC.json. """ 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 from scipy.signal.windows import dpss # noqa: E402 from scipy.stats import chi2, f as fdist # noqa: E402 import common as C # noqa: E402 dl, outdir = sys.argv[1], sys.argv[2] NS = int(sys.argv[3]) if len(sys.argv) > 3 else 200 D0, D1 = dt.date(2010, 1, 1), dt.date(2023, 12, 31) dates = C.daterange(D0, D1) N = len(dates) K, NW, NFFT = 6, 3.5, 8192 TAPERS = dpss(N, NW, Kmax=K) # (K, N) U0 = TAPERS.sum(axis=1) # taper spectra at zero frequency freqs = np.fft.rfftfreq(NFFT, d=1.0) band = (freqs >= 1 / 30.0) & (freqs <= 1 / 4.5) L99 = chi2.ppf(0.99, 2 * K) / (2 * K) L95 = chi2.ppf(0.95, 2 * K) / (2 * K) F95 = fdist.ppf(0.95, 2, 2 * K - 2) F99 = fdist.ppf(0.99, 2, 2 * K - 2) TARGETS = [(6.0, 0.5), (9.0, 0.5), (15.0, 1.0), (27.0, 1.0)] def mt(x): x = x - x.mean() Y = np.fft.rfft(TAPERS * x[None, :], n=NFFT, axis=1) # (K, F) S = (np.abs(Y) ** 2).mean(axis=0) Sstd = S / S[1:].mean() mu = (U0[:, None] * Y).sum(axis=0) / (U0 ** 2).sum() num = (K - 1) * np.abs(mu) ** 2 * (U0 ** 2).sum() den = (np.abs(Y - mu[None, :] * U0[:, None]) ** 2).sum(axis=0) F = num / den return Sstd, F def peaks(v, level): """indices of local maxima above level, inside the band""" i = np.where(band)[0] out = [] for j in i: if v[j] > level and v[j] >= v[j - 1] and v[j] >= v[j + 1]: out.append(j) return out def analyse(x): Sstd, F = mt(x) ps = peaks(Sstd, L99) pf = peaks(F, F95) per_s = 1 / freqs[ps] per_f = 1 / freqs[pf] matched = [] for (T, tol) in TARGETS: m = bool(np.any(np.abs(per_s - T) <= tol) or np.any(np.abs(per_f - T) <= tol)) matched.append(m) return {'n_std99': len(ps), 'n_F95': len(pf), 'n_F99': int(sum(F[j] > F99 for j in pf)), 'matched': matched, 'periods_std99': [round(float(p), 2) for p in per_s], 'periods_F95': [round(float(p), 2) for p in per_f]} def prewhiten(x): r1 = np.corrcoef(x[:-1], x[1:])[0, 1] return x[1:] - r1 * x[:-1], r1 res = {'K': K, 'NW': NW, 'nfft': NFFT, 'lines': {'std95': L95, 'std99': L99, 'F95': F95, 'F99': F99}, 'band_days': [4.5, 30], 'targets': TARGETS, 'n_independent_bands_in_band': round(float((1 / 4.5 - 1 / 30) / (2 * NW / N)), 1)} # positive control: OMNI By GSE d, gse, gsm = C.read_omni_daily(os.path.join(dl, 'omni', 'omni_01_av.dat'), 2010, 2023) by = np.where(np.isnan(gse), np.nanmean(gse), gse) a = analyse(by) a['top_std_periods'] = sorted(a['periods_std99'], key=lambda p: -mt(by)[0][np.argmin(np.abs(freqs - 1 / p))])[:6] res['OMNI_By_GSE_raw'] = a # real weather series: R1 USA-box precipitation rd, pr = C.read_r1_box(os.path.join(dl, 'ncep-r1'), 'prate', range(2010, 2024)) res['R1_precip_raw'] = analyse(pr) pw, r1 = prewhiten(pr) res['R1_precip_prewhitened'] = analyse(np.concatenate([[pw[0]], pw])) res['R1_precip_r1'] = round(float(r1), 3) # a series with no periodicity at all: white noise, same length res['white_noise_example'] = analyse(np.random.default_rng(5).standard_normal(N)) # null: synthetic series par = json.load(open(os.path.join(outdir, 'sea_null_RC.json'), encoding='utf-8'))['synthetic_model'] A, PHI, SIG = par['A'], par['phi'], par['sigma'] doy = np.array([x.timetuple().tm_yday for x in dates]) s = A * np.cos(2 * np.pi * (doy - 196) / 365.25) rng = np.random.default_rng(31) agg = {'raw': [], 'pw': [], 'either': []} nstd, nF95, nF99 = [], [], [] for i in range(NS): eps = rng.standard_normal(N + 500) * SIG * np.sqrt(1 - PHI ** 2) x = np.exp(s + lfilter([1.0], [1.0, -PHI], eps)[500:]) ra = analyse(x) xw, _ = prewhiten(x) xw = np.concatenate([[xw[0]], xw]) # keep length N for the same tapers pa = analyse(xw) nstd.append(ra['n_std99']); nF95.append(ra['n_F95']); nF99.append(ra['n_F99']) agg['raw'].append(sum(ra['matched'])) agg['pw'].append(sum(pa['matched'])) agg['either'].append(sum(m1 or m2 for m1, m2 in zip(ra['matched'], pa['matched']))) res['null_synthetic'] = { 'n_series': NS, 'mean_n_std99_peaks_raw': round(float(np.mean(nstd)), 2), 'mean_n_F95_peaks_raw': round(float(np.mean(nF95)), 2), 'mean_n_F99_peaks_raw': round(float(np.mean(nF99)), 2), } for key, v in agg.items(): v = np.array(v) res['null_synthetic'][f'matched_{key}'] = {'P_ge_2': round(float(np.mean(v >= 2)), 3), 'P_ge_3': round(float(np.mean(v >= 3)), 3), 'P_all_4': round(float(np.mean(v >= 4)), 3), 'mean': round(float(v.mean()), 2)} with open(os.path.join(outdir, 'multitaper_null.json'), 'w', encoding='utf-8', newline='\n') as fh: json.dump(res, fh, indent=1) print(json.dumps(res, indent=1))