"""Shared readers and the crossing rule for the lightning-sector-crossings checks. Needs Python 3 with numpy (and netCDF4 for the reanalysis readers). Reads downloaded files as data only. Written for factchecked.science, 2026-11-15. """ import datetime as dt import os import numpy as np FILL = 999.9 def read_omni_daily(path, y0=2000, y1=2023): """OMNI daily averages (omni_01_av.dat): returns dates, By GSE, By GSM (NaN = missing).""" dates, gse, gsm = [], [], [] with open(path, encoding='ascii') as f: for line in f: w = line.split() if len(w) < 16: continue y = int(w[0]) if y < y0 or y > y1: continue d = dt.date(y, 1, 1) + dt.timedelta(days=int(w[1]) - 1) a, b = float(w[13]), float(w[15]) dates.append(d) gse.append(np.nan if a >= FILL else a) gsm.append(np.nan if b >= FILL else b) return dates, np.array(gse), np.array(gsm) def read_omni_hourly_daily_means(folder, years): """Daily means of hourly By GSE from omni2_YYYY.dat (any day with >= 1 valid hour).""" out = {} for y in years: sums, cnt = {}, {} with open(os.path.join(folder, f'omni2_{y}.dat'), encoding='ascii') as f: for line in f: w = line.split() d = dt.date(int(w[0]), 1, 1) + dt.timedelta(days=int(w[1]) - 1) v = float(w[13]) if v >= FILL: continue sums[d] = sums.get(d, 0.0) + v cnt[d] = cnt.get(d, 0) + 1 for d in sums: out[d] = sums[d] / cnt[d] return out def daterange(d0, d1): n = (d1 - d0).days + 1 return [d0 + dt.timedelta(days=i) for i in range(n)] def subset(dates, arr, d0, d1): idx = [i for i, d in enumerate(dates) if d0 <= d <= d1] return [dates[i] for i in idx], arr[idx] def running_mean5(b): n = len(b) m = np.full(n, np.nan) for t in range(n): lo, hi = max(0, t - 2), min(n, t + 3) seg = b[lo:hi] seg = seg[~np.isnan(seg)] if len(seg) >= 3 and hi - lo == 5: m[t] = seg.mean() return m def window_mean_abs(b, lo, hi): """mean |b| over indices lo..hi inclusive, needs >= 3 valid values inside the series.""" n = len(b) if lo < 0 or hi >= n: return np.nan seg = np.abs(b[lo:hi + 1]) seg = seg[~np.isnan(seg)] return seg.mean() if len(seg) >= 3 else np.nan WINDOWS = { # name: (before offsets), (after offsets) relative to the crossing day t 'W1': ((-5, -1), (0, 4)), 'W2': ((-5, -1), (1, 5)), 'W3': ((-4, 0), (1, 5)), 'W4': ((-6, -2), (0, 4)), } def detect_crossings(dates, b, thr, rule='A', win='W1'): """The thesis's three-step rule (Peterson 2026, p. 63-64), our operationalisation. Returns a list of dicts: date, index, direction ('T-A' or 'A-T'), before, after. """ m = running_mean5(b) (b0, b1), (a0, a1) = WINDOWS[win] out = [] n = len(b) for t in range(1, n): p, q = b[t - 1], b[t] if np.isnan(p) or np.isnan(q) or p == 0 or q == 0 or np.sign(p) == np.sign(q): continue direction = 'T-A' if p < 0 < q else 'A-T' want = np.sign(q) # rule 2: running mean changes sign in the same direction ok2 = False if rule == 'A': for s in range(max(1, t - 2), min(n, t + 3)): u, v = m[s - 1], m[s] if not (np.isnan(u) or np.isnan(v)) and np.sign(u) == -want and np.sign(v) == want: ok2 = True break else: u, v = m[t - 1], m[t] ok2 = (not (np.isnan(u) or np.isnan(v))) and np.sign(u) == -want and np.sign(v) == want if not ok2: continue before = window_mean_abs(b, t + b0, t + b1) after = window_mean_abs(b, t + a0, t + a1) if np.isnan(before) or np.isnan(after) or before <= thr or after <= thr: continue out.append({'date': dates[t], 'index': t, 'direction': direction, 'before': before, 'after': after}) return out def detect_crossings_rc(dates, b, thr, after_start=0): """Post hoc reading "R-C" (closest to the thesis's counts; see hcs_variants.py): centred 5-day running mean must change sign (same direction) within +/-1 day of the daily sign change; |mean By| over t-5..t-1 and over t..t+4 must exceed thr.""" m = running_mean5(b) out = [] n = len(b) for t in range(1, n): p, q = b[t - 1], b[t] if np.isnan(p) or np.isnan(q) or p == 0 or q == 0 or np.sign(p) == np.sign(q): continue want = np.sign(q) ok2 = False for s in range(max(1, t - 1), min(n, t + 2)): u, v = m[s - 1], m[s] if not (np.isnan(u) or np.isnan(v)) and np.sign(u) == -want and np.sign(v) == want: ok2 = True break if not ok2: continue if t - 5 < 0 or t + 4 + after_start >= n: continue seg_b = b[t - 5:t] seg_a = b[t + after_start:t + 5 + after_start] seg_b = seg_b[~np.isnan(seg_b)] seg_a = seg_a[~np.isnan(seg_a)] if len(seg_b) < 3 or len(seg_a) < 3: continue before, after = abs(seg_b.mean()), abs(seg_a.mean()) if before <= thr or after <= thr: continue out.append({'date': dates[t], 'index': t, 'direction': 'T-A' if p < 0 else 'A-T', 'before': before, 'after': after}) return out def read_r1_box(folder, kind, years, lat0=30.0, lat1=50.0, lon0=235.0, lon1=300.0, weighted=True): """Box mean of R1 daily means. kind 'prate' (mm/day) or 'pres' (hPa). Grid cells whose centres lie inside the box (inclusive).""" import netCDF4 as nc vals, dates = [], [] for y in years: if kind == 'prate': f = os.path.join(folder, f'prate.sfc.gauss.{y}.USAbox.nc') var, scale = 'prate', 86400.0 else: f = os.path.join(folder, f'pres.sfc.{y}.nc') var, scale = 'pres', 0.01 d = nc.Dataset(f) lat = np.array(d.variables['lat'][:], dtype=float) lon = np.array(d.variables['lon'][:], dtype=float) la = (lat >= lat0) & (lat <= lat1) lo = (lon >= lon0) & (lon <= lon1) x = np.array(d.variables[var][:, la, :][:, :, lo], dtype=float) * scale if kind == 'prate': # PSL's 2014 file stores some dry cells as -2.3e-10 kg m-2 s-1, below the # variable's valid_range (0..0.005); the subset service returned them as NaN. # Checked against the full file: they are (near) zero precipitation. x = np.where(np.isnan(x), 0.0, x) w = np.cos(np.deg2rad(lat[la]))[:, None] * np.ones(lo.sum())[None, :] if weighted else np.ones((la.sum(), lo.sum())) vals.append((x * w[None]).sum(axis=(1, 2)) / w.sum()) t = d.variables['time'] base = dt.datetime(1800, 1, 1) dates += [(base + dt.timedelta(hours=float(h))).date() for h in t[:]] d.close() return dates, np.concatenate(vals) def harmonic_anomaly(dates, x, nharm=4): """x minus its mean annual cycle (mean + nharm annual harmonics, least squares).""" doy = np.array([d.timetuple().tm_yday for d in dates], dtype=float) cols = [np.ones_like(doy)] for k in range(1, nharm + 1): cols += [np.cos(2 * np.pi * k * doy / 365.25), np.sin(2 * np.pi * k * doy / 365.25)] G = np.array(cols).T coef, *_ = np.linalg.lstsq(G, x, rcond=None) return x - G @ coef def read_crossings_csv(path): rows = [] with open(path, encoding='utf-8') as f: next(f) for line in f: d, direction = line.strip().split(',')[:2] rows.append((dt.date.fromisoformat(d), direction)) return rows def eligible(crossings, dates, margin=40): n = len(dates) return [c for c in crossings if c['index'] >= margin and c['index'] <= n - 1 - margin] def in_season(d, start_md, end_md): s = dt.date(d.year, *start_md) e = dt.date(d.year, *end_md) return s <= d <= e