"""Shared helpers for the checks of S0 News research note 008 (Fact-Checked Science, 2026-11-15). Reads the public files as data; runs nothing from them. Needs numpy and scipy. Months are integers: m = year*12 + (month-1). """ import csv import math import numpy as np from scipy import stats def ym(s): """'1979-01' or '1979-01-01' -> month integer.""" y, m = s.strip().split("-")[:2] return int(y) * 12 + int(m) - 1 def ym_str(m): return f"{m // 12:04d}-{m % 12 + 1:02d}" def ym_dec(m): """Month integer -> decimal year at mid-month.""" return m // 12 + (m % 12 + 0.5) / 12.0 class Monthly: """A contiguous monthly series: start month and a float array (NaN = missing).""" def __init__(self, start, values): self.start = int(start) self.v = np.asarray(values, dtype=float) @property def end(self): return self.start + len(self.v) - 1 def restrict(self, a, b): a = max(a, self.start) b = min(b, self.end) return Monthly(a, self.v[a - self.start: b - self.start + 1].copy()) def get(self, m): if m < self.start or m > self.end: return float("nan") return self.v[m - self.start] def __len__(self): return len(self.v) def _from_dict(d): ms = sorted(d) start, end = ms[0], ms[-1] arr = np.full(end - start + 1, np.nan) for m in ms: arr[m - start] = d[m] return Monthly(start, arr) def load_v3(path, column="sector_pressure (hPa) [a]"): rows = {} header = None meta = {} with open(path, encoding="utf-8") as f: for line in f: if line.startswith("#"): if ":" in line: k, _, val = line[1:].partition(":") meta[k.strip()] = val.strip() continue parts = next(csv.reader([line])) if header is None: header = parts ci = header.index(column) continue if not parts or not parts[0].strip(): continue rows[ym(parts[0])] = float(parts[ci]) return _from_dict(rows), meta def load_v3_column(path, column): s, _ = load_v3(path, column) return s def load_v2(path, column="SectorPres"): rows = {} header = None with open(path, encoding="utf-8") as f: for line in f: if line.startswith("#") or not line.strip(): continue parts = line.split() if header is None: header = parts ci = header.index(column) continue rows[int(parts[0]) * 12 + int(parts[1]) - 1] = float(parts[ci]) return _from_dict(rows) def load_silso(path): """SN_m_tot_V2.0.csv: year;month;decimal;SN;sd;nobs;definitive.""" rows, defin = {}, {} with open(path, encoding="utf-8") as f: for line in f: p = [x.strip() for x in line.strip().split(";")] if len(p) < 7: continue m = int(p[0]) * 12 + int(p[1]) - 1 rows[m] = float(p[3]) defin[m] = int(p[6]) return _from_dict(rows), defin def load_workbook(path): asl, ssn = {}, {} with open(path, encoding="utf-8") as f: for parts in csv.reader(f): if len(parts) < 3: continue d = parts[0].strip() if len(d) == 7 and d[4] == "-" and d[:4].isdigit(): m = ym(d) asl[m] = float(parts[1]) ssn[m] = float(parts[2]) return _from_dict(asl), _from_dict(ssn) def cma(series, w, odd=False): """Centred moving average. Even form: d-w/2 .. d+w/2-1 (w months). Odd form (odd=True): d-w/2 .. d+w/2 (w+1 months). Full windows only (no NaN). Returns a Monthly whose values are NaN where undefined.""" v = series.v n = len(v) lo = w // 2 hi = w // 2 - 1 if not odd else w // 2 span = lo + hi + 1 out = np.full(n, np.nan) if n < span: return Monthly(series.start, out) good = np.isfinite(v) vz = np.where(good, v, 0.0) cs = np.concatenate([[0.0], np.cumsum(vz)]) cg = np.concatenate([[0], np.cumsum(good.astype(int))]) for i in range(lo, n - hi): a, b = i - lo, i + hi + 1 if cg[b] - cg[a] == span: out[i] = (cs[b] - cs[a]) / span return Monthly(series.start, out) def pair(ssn_c, asl_c, lag): """x = SSN_CMA[t], y = ASL_CMA[t+lag]; both defined. Returns x, y, t (month ints).""" xs, ys, ts = [], [], [] for i, xv in enumerate(ssn_c.v): if not np.isfinite(xv): continue t = ssn_c.start + i yv = asl_c.get(t + lag) if np.isfinite(yv): xs.append(xv) ys.append(yv) ts.append(t) return np.array(xs), np.array(ys), np.array(ts, dtype=int) def pearson(x, y): if len(x) < 3: return float("nan") xm, ym_ = x - x.mean(), y - y.mean() d = math.sqrt(float((xm * xm).sum()) * float((ym_ * ym_).sum())) return float((xm * ym_).sum() / d) if d > 0 else float("nan") def acf_biased(x): """Globally centred, biased (divide by N) autocorrelation, lags 0..N-1.""" x = np.asarray(x, float) n = len(x) xm = x - x.mean() f = np.fft.rfft(xm, 2 * n) c = np.fft.irfft(f * np.conj(f), 2 * n)[:n] / n return c / c[0] def neff_bretherton(x, y, maxlag=None): """Bretherton et al. (1999) Eq. 30 with biased sample ACFs, lags 1..N-1 (or 1..maxlag).""" n = len(x) rx, ry = acf_biased(x), acf_biased(y) L = n - 1 if maxlag is None else min(maxlag, n - 1) tau = np.arange(1, L + 1) s = 1.0 + 2.0 * np.sum((1.0 - tau / n) * rx[1:L + 1] * ry[1:L + 1]) return n / s def neff_single(x): """Same estimator for one series with itself (order-2 ESS of a series).""" return neff_bretherton(x, x) def p_two_sided(r, neff): df = neff - 2.0 if df <= 0 or not np.isfinite(r) or abs(r) >= 1: return float("nan") t = r * math.sqrt(df / (1.0 - r * r)) return float(2.0 * stats.t.sf(abs(t), df)) WIDTHS = [12, 24, 36, 48, 60, 72, 84, 96] LAGS = list(range(0, 49)) def grid(ssn_raw, asl_raw, widths=WIDTHS, lags=LAGS, odd=False): """r and n for every width x lag.""" R = np.full((len(widths), len(lags)), np.nan) N = np.zeros((len(widths), len(lags)), dtype=int) for i, w in enumerate(widths): sc, ac = cma(ssn_raw, w, odd), cma(asl_raw, w, odd) for j, L in enumerate(lags): x, y, _ = pair(sc, ac, L) R[i, j] = pearson(x, y) N[i, j] = len(x) return R, N def phase_surrogates(x, nsur, rng): """Fourier phase-randomised surrogates of a real series (no NaN): amplitudes kept, phases of components 1..ceil(n/2)-1 uniform random; the mean (k=0) and, for even n, the Nyquist component are kept as they are. Returns an (nsur, n) array.""" x = np.asarray(x, float) n = len(x) X = np.fft.rfft(x) amp = np.abs(X) nf = len(X) k_last = nf - 1 if n % 2 == 0 else nf # exclude Nyquist for even n out = np.empty((nsur, n)) for s in range(nsur): ph = np.angle(X).copy() ph[1:k_last] = rng.uniform(0.0, 2.0 * np.pi, k_last - 1) out[s] = np.fft.irfft(amp * np.exp(1j * ph), n) return out def cma_matrix(V, w, odd=False): """Row-wise centred moving average of a (B, n) array with no NaN. Returns (B, n) with NaN where the window is incomplete (same alignment as cma()).""" B, n = V.shape lo = w // 2 hi = w // 2 - 1 if not odd else w // 2 span = lo + hi + 1 cs = np.concatenate([np.zeros((B, 1)), np.cumsum(V, axis=1)], axis=1) out = np.full((B, n), np.nan) i = np.arange(lo, n - hi) out[:, i] = (cs[:, i + hi + 1] - cs[:, i - lo]) / span return out def rows_corr(x, Y): """Pearson r between a vector x (n) and each row of Y (B, n).""" xm = x - x.mean() Ym = Y - Y.mean(axis=1, keepdims=True) num = Ym @ xm den = np.sqrt((Ym * Ym).sum(axis=1) * (xm * xm).sum()) return num / den def cols_corr(X, y): """Pearson r between each row of X (B, n) and a vector y (n).""" return rows_corr(y, X)