"""Shared loaders and statistics for the note-003 checks (pure Python, standard library only). All downloads are read as data. By default the inputs are in ../downloads and the outputs go to ../results, relative to this file. With `--base DIR` on any script's command line, the inputs are read from DIR (as laid out by fetch_inputs.py: DIR/drive003/, DIR/gfz/) and the outputs go to DIR/results/. """ import csv import datetime as dt import glob import math import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) DL = os.path.join(ROOT, "downloads") RES = os.path.join(ROOT, "results") if "--base" in sys.argv: _i = sys.argv.index("--base") _base = os.path.abspath(sys.argv[_i + 1]) del sys.argv[_i:_i + 2] DL = _base RES = os.path.join(_base, "results") DRIVE = os.path.join(DL, "drive003") START = dt.date(1999, 1, 1) END = dt.date(2026, 11, 3) N = (END - START).days + 1 # 10,169 def di(d): """Day index from 1999-01-01.""" return (d - START).days def dd(i): return START + dt.timedelta(days=i) def pdate(s): return dt.date(int(s[0:4]), int(s[5:7]), int(s[8:10])) def drive_file(prefix): fs = sorted(glob.glob(os.path.join(DRIVE, prefix + "__*"))) if not fs: raise FileNotFoundError(prefix) return fs[0] def read_csv(path): with open(path, encoding="utf-8-sig", newline="") as f: return list(csv.DictReader(f)) def load_events(): return read_csv(drive_file("EE_events")) def load_daily(): return read_csv(drive_file("daily_ee_kp")) def load_gfz(path=None): """Return dict date -> (kp list of 8, Ap, D flag).""" path = path or os.path.join(DL, "gfz", "Kp_ap_Ap_SN_F107_since_1932.txt") out = {} with open(path, encoding="utf-8") as f: for ln in f: if ln.startswith("#") or not ln.strip(): continue a = ln.split() d = dt.date(int(a[0]), int(a[1]), int(a[2])) kp = [float(x) for x in a[7:15]] ap_day = int(a[23]) flag = int(a[-1]) out[d] = (kp, ap_day, flag) return out def daily_max_kp(gfz): res = {} for d, (kp, _, _) in gfz.items(): v = [k for k in kp if k >= 0] res[d] = max(v) if v else None return res def kp_code(v): t = int(round(v * 3)) base, rem = divmod(t, 3) if rem == 0: return "%do" % base if rem == 1: return "%d+" % base return "%d-" % (base + 1) def episodes(kpmax_by_index, thr, tol=1e-3): """Runs of consecutive day indices with kp >= thr; t0 = first day with the run's max. kpmax_by_index: list of floats (len N). Returns list of dicts.""" eps = [] i = 0 n = len(kpmax_by_index) while i < n: if kpmax_by_index[i] is not None and kpmax_by_index[i] >= thr - tol: j = i while j + 1 < n and kpmax_by_index[j + 1] is not None and kpmax_by_index[j + 1] >= thr - tol: j += 1 seg = kpmax_by_index[i:j + 1] pk = max(seg) t0 = i + seg.index(pk) eps.append({"start": i, "end": j, "t0": t0, "peak": pk, "n_days": j - i + 1}) i = j + 1 else: i += 1 return eps # ---------------------------------------------------------------- Poisson and gamma functions def gammp(a, x): """Regularized lower incomplete gamma P(a, x).""" if x <= 0: return 0.0 if x < a + 1: ap = a s = 1.0 / a delta = s for _ in range(100000): ap += 1 delta *= x / ap s += delta if abs(delta) < abs(s) * 1e-15: break return s * math.exp(-x + a * math.log(x) - math.lgamma(a)) # continued fraction for Q b = x + 1 - a c = 1e300 d = 1 / b h = d for i in range(1, 100000): an = -i * (i - a) b += 2 d = an * d + b if abs(d) < 1e-300: d = 1e-300 c = b + an / c if abs(c) < 1e-300: c = 1e-300 d = 1 / d de = d * c h *= de if abs(de - 1) < 1e-15: break q = math.exp(-x + a * math.log(x) - math.lgamma(a)) * h return 1 - q def pois_sf_ge(k, mu): """P(X >= k), X ~ Poisson(mu).""" if k <= 0: return 1.0 return gammp(k, mu) def pois_cdf_le(k, mu): """P(X <= k).""" if k < 0: return 0.0 return 1 - gammp(k + 1, mu) def gamma_quantile(p, a): """x with P(a, x) = p, by bisection.""" lo, hi = 0.0, max(10.0, a * 10 + 50) for _ in range(200): mid = (lo + hi) / 2 if gammp(a, mid) < p: lo = mid else: hi = mid return (lo + hi) / 2 def pois_ci(k, level=0.95): """Exact (Garwood) CI for a Poisson mean given count k.""" al = 1 - level lo = 0.0 if k == 0 else gamma_quantile(al / 2, k) hi = gamma_quantile(1 - al / 2, k + 1) return lo, hi def norm_sf(z): return 0.5 * math.erfc(z / math.sqrt(2)) # ---------------------------------------------------------------- GLM on 0/1 indicator designs def mat_inv(a): n = len(a) m = [row[:] + [1.0 if i == j else 0.0 for j in range(n)] for i, row in enumerate(a)] for c in range(n): p = max(range(c, n), key=lambda r: abs(m[r][c])) if abs(m[p][c]) < 1e-300: raise ZeroDivisionError("singular") m[c], m[p] = m[p], m[c] piv = m[c][c] inv = 1.0 / piv row_c = [v * inv for v in m[c]] m[c] = row_c for r in range(n): if r != c: f = m[r][c] if f != 0.0: row_r = m[r] m[r] = [x - f * y for x, y in zip(row_r, row_c)] return [row[n:] for row in m] def solve(a, b): inv = mat_inv(a) return [sum(x * y for x, y in zip(row, b)) for row in inv], inv def glm_fit(rows, y, ncol, family="poisson", alpha=0.0, offset=None, beta0=None, tol=1e-10, maxit=100): """IRLS for log-link Poisson or NB2 (fixed alpha). rows: list of lists of active column indices (0/1 design). Returns beta, cov (inverse information), mu, loglik.""" n = len(y) off = offset or [0.0] * n if beta0 is None: beta = [0.0] * ncol beta[0] = math.log(max(sum(y) / n, 1e-9)) else: beta = beta0[:] for it in range(maxit): xtwx = [[0.0] * ncol for _ in range(ncol)] xtwz = [0.0] * ncol for r, yi, oi in zip(rows, y, off): eta = oi + sum(beta[c] for c in r) mu = math.exp(eta) w = mu if family == "poisson" else mu / (1 + alpha * mu) z = (eta - oi) + (yi - mu) / mu for a in r: xtwz[a] += w * z ra = xtwx[a] for b in r: ra[b] += w new, cov = solve(xtwx, xtwz) diff = max(abs(p - q) for p, q in zip(new, beta)) beta = new if diff < tol: break mus = [math.exp(oi + sum(beta[c] for c in r)) for r, oi in zip(rows, off)] # recompute cov at the final beta xtwx = [[0.0] * ncol for _ in range(ncol)] for r, mu in zip(rows, mus): w = mu if family == "poisson" else mu / (1 + alpha * mu) for a in r: ra = xtwx[a] for b in r: ra[b] += w cov = mat_inv(xtwx) ll = loglik(y, mus, family, alpha) return beta, cov, mus, ll def loglik(y, mus, family="poisson", alpha=0.0): s = 0.0 if family == "poisson": for yi, mu in zip(y, mus): s += yi * math.log(mu) - mu - math.lgamma(yi + 1) return s r = 1.0 / alpha for yi, mu in zip(y, mus): s += (math.lgamma(yi + r) - math.lgamma(r) - math.lgamma(yi + 1) + yi * math.log(alpha * mu / (1 + alpha * mu)) - r * math.log(1 + alpha * mu)) return s def nb_fit(rows, y, ncol, offset=None): """NB2 with alpha by maximum likelihood (golden-section on log alpha, beta refitted at each alpha).""" b0, _, _, _ = glm_fit(rows, y, ncol, "poisson", offset=offset) cache = {} warm = [b0] def f(la): if la in cache: return cache[la][0] beta, cov, mus, ll = glm_fit(rows, y, ncol, "nb", math.exp(la), offset=offset, beta0=warm[0], tol=1e-8) warm[0] = beta cache[la] = (ll, beta, cov, mus) return ll lo, hi = math.log(1e-3), math.log(10.0) g = (math.sqrt(5) - 1) / 2 c = hi - g * (hi - lo) d = lo + g * (hi - lo) for _ in range(24): if f(c) > f(d): hi = d else: lo = c c = hi - g * (hi - lo) d = lo + g * (hi - lo) la = (lo + hi) / 2 f(la) ll, beta, cov, mus = cache[la] return beta, cov, mus, ll, math.exp(la) def rr_from(beta, cov, col): b = beta[col] se = math.sqrt(cov[col][col]) z = b / se return math.exp(b), math.exp(b - 1.959964 * se), math.exp(b + 1.959964 * se), 2 * norm_sf(abs(z)), se def design_rows(day_indices, exposure, extra=None): """Treatment-coded rows: intercept 0, year (ref first year), month (ref Jan), weekday (ref Monday), then the exposure column(s). exposure: list of 0/1 per day (or None); extra: dict name->list.""" years = sorted({dd(i).year for i in day_indices}) ycol = {y: k for k, y in enumerate(years[1:], start=1)} base = 1 + len(years) - 1 mcol = {m: base + m - 2 for m in range(2, 13)} base2 = base + 11 wcol = {w: base2 + w - 1 for w in range(1, 7)} ecol = base2 + 6 rows = [] for k, i in enumerate(day_indices): d = dd(i) r = [0] if d.year in ycol: r.append(ycol[d.year]) if d.month in mcol: r.append(mcol[d.month]) if d.weekday() in wcol: r.append(wcol[d.weekday()]) if exposure is not None and exposure[k]: r.append(ecol) rows.append(r) if exposure is None: return rows, ecol, ecol # no exposure column: ncol = ecol (the next free column index) return rows, ecol + 1, ecol def pearson_dispersion(y, mus, nparam): x2 = sum((a - m) ** 2 / m for a, m in zip(y, mus)) return x2 / (len(y) - nparam)