#!/usr/bin/env python3 """Shared readers for the akasofu-epsilon-weak-field verification (Fact-Checked Science). Everything read here is data: OMNI2 hourly files (NASA SPDF), IGRF-14 coefficients (IAGA/NOAA), GFZ's Kp, ap and Hpo files, Kyoto's Dst monthly pages, and the paper's supplementary CSV tables. Nothing from the downloads is executed. Needs numpy (py -3.12). Run with -I. """ import csv import datetime import hashlib import math import os import re import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) BASE = os.path.dirname(HERE) DL = os.path.join(BASE, "downloads") OUT = os.path.join(BASE, "out") WORK = os.path.join(BASE, "work") SUPP = os.path.join(DL, "supplied-supplement") # the folder holding the paper's supplementary files; name made general for hosting MU0 = 4.0e-7 * math.pi # H/m RE_M = 6371.0e3 # m, the paper's R_E L0 = 7.0 * RE_M # m K_EPS = 4.0 * math.pi / MU0 * L0 * L0 # epsilon [W] = K_EPS * V[m/s] * BT[T]^2 * sin^4(theta/2) def sha256(path): h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(1 << 20), b""): h.update(chunk) return h.hexdigest() # ---------------------------------------------------------------- IGRF-14 def read_igrf(path=None): path = path or os.path.join(DL, "igrf14", "igrf14coeffs.txt") epochs, rows = None, {} with open(path, encoding="ascii") as f: for line in f: if line.startswith("g/h"): epochs = [float(x) for x in line.split()[3:-1]] elif line[:1] in "gh" and not line.startswith("g/h"): p = line.split() rows[(p[0], int(p[1]), int(p[2]))] = [float(x) for x in p[3:]] main = {k: v[:-1] for k, v in rows.items()} sv = {k: v[-1] for k, v in rows.items()} return epochs, main, sv def igrf_coeff(epochs, main, sv, key, t): v = main[key] if t >= epochs[-1]: return v[-1] + (t - epochs[-1]) * sv[key] i0 = max(i for i, e in enumerate(epochs) if e <= t) w = (t - epochs[i0]) / (epochs[i0 + 1] - epochs[i0]) return v[i0] + w * (v[i0 + 1] - v[i0]) def dipole_proxy(t, igrf=None): """sqrt(g10^2 + g11^2 + h11^2) at decimal year t, coefficients interpolated linearly.""" epochs, main, sv = igrf or read_igrf() g10 = igrf_coeff(epochs, main, sv, ("g", 1, 0), t) g11 = igrf_coeff(epochs, main, sv, ("g", 1, 1), t) h11 = igrf_coeff(epochs, main, sv, ("h", 1, 1), t) return math.sqrt(g10 * g10 + g11 * g11 + h11 * h11) # ---------------------------------------------------------------- OMNI2 # Word numbers (1-based) from omni2.text W_YEAR, W_DOY, W_HOUR = 1, 2, 3 W_BMAG, W_BX, W_BY_GSE, W_BZ_GSE, W_BY_GSM, W_BZ_GSM = 9, 13, 14, 15, 16, 17 W_DENS, W_V, W_PDYN = 24, 25, 29 W_KP, W_DST, W_AP = 39, 41, 50 FILL = {W_BMAG: 999.9, W_BX: 999.9, W_BY_GSE: 999.9, W_BZ_GSE: 999.9, W_BY_GSM: 999.9, W_BZ_GSM: 999.9, W_DENS: 999.9, W_V: 9999.0, W_PDYN: 99.99, W_KP: 99, W_DST: 99999, W_AP: 999} WANT = [W_BMAG, W_BX, W_BY_GSE, W_BZ_GSE, W_BY_GSM, W_BZ_GSM, W_DENS, W_V, W_PDYN, W_KP, W_DST, W_AP] def read_omni_year(year, folder=None): """One yearly file, parsed by whitespace. Returns dict of numpy arrays; fill values become NaN.""" folder = folder or os.path.join(DL, "omni2") path = os.path.join(folder, "omni2_%d.dat" % year) cols = {w: [] for w in WANT} yy, dd, hh = [], [], [] with open(path, encoding="ascii") as f: for line in f: p = line.split() if len(p) < 55: raise ValueError("%s: line with %d words" % (path, len(p))) yy.append(int(p[0])); dd.append(int(p[1])); hh.append(int(p[2])) for w in WANT: x = float(p[w - 1]) cols[w].append(float("nan") if x == FILL[w] else x) out = {w: np.array(v, dtype=float) for w, v in cols.items()} out["year"] = np.array(yy); out["doy"] = np.array(dd); out["hour"] = np.array(hh) d0 = datetime.date(year, 1, 1) out["month"] = np.array([(d0 + datetime.timedelta(days=int(d) - 1)).month for d in dd]) out["dom"] = np.array([(d0 + datetime.timedelta(days=int(d) - 1)).day for d in dd]) return out def read_omni(years, folder=None): parts = [read_omni_year(y, folder) for y in years] return {k: np.concatenate([p[k] for p in parts]) for k in parts[0]} def epsilon(v_kms, by_nt, bz_nt): """Akasofu epsilon in W by the paper's recipe (section 6.1). Inputs are numpy arrays; NaN in gives NaN out.""" bt = np.sqrt(by_nt ** 2 + bz_nt ** 2) theta = np.mod(np.arctan2(by_nt, bz_nt), 2.0 * math.pi) return K_EPS * (v_kms * 1.0e3) * (bt * 1.0e-9) ** 2 * np.sin(theta / 2.0) ** 4 def newell(v_kms, by_nt, bz_nt): """Newell et al. (2007) coupling function, V^(4/3) BT^(2/3) sin^(8/3)(theta/2); V in km/s, BT in nT.""" bt = np.sqrt(by_nt ** 2 + bz_nt ** 2) theta = np.mod(np.arctan2(by_nt, bz_nt), 2.0 * math.pi) return v_kms ** (4.0 / 3.0) * bt ** (2.0 / 3.0) * np.abs(np.sin(theta / 2.0)) ** (8.0 / 3.0) # ---------------------------------------------------------------- the paper's tables (data only) def read_table(name): path = os.path.join(SUPP, name) with open(path, encoding="utf-8", newline="") as f: return list(csv.DictReader(f)) def annual_table(): return read_table("1-s2.0-S0273117726015188-mmc3.csv") def monthly_table(): return read_table("1-s2.0-S0273117726015188-mmc4.csv") # ---------------------------------------------------------------- GFZ def read_gfz_kp(path=None): """Three-hourly Kp and ap. Returns dict keyed (y, m, d, h0) -> (Kp, ap, definitive flag).""" path = path or os.path.join(DL, "gfz-kp", "Kp_ap_since_1932.txt") out = {} with open(path, encoding="ascii") as f: for line in f: if line.startswith("#") or not line.strip(): continue p = line.split() y, m, d = int(p[0]), int(p[1]), int(p[2]) h0 = int(round(float(p[3]))) out[(y, m, d, h0)] = (float(p[7]), int(p[8]), int(p[9])) return out def read_gfz_hp60(path=None): """Hourly Hp60 and ap60. Returns dict keyed (y, m, d, h) -> (Hp60, ap60).""" path = path or os.path.join(DL, "gfz-hpo", "Hp60_ap60_complete_series.txt") out = {} with open(path, encoding="ascii") as f: for line in f: if line.startswith("#") or not line.strip(): continue p = line.split() out[(int(p[0]), int(p[1]), int(p[2]), int(round(float(p[3]))))] = (float(p[7]), int(p[8])) return out # ---------------------------------------------------------------- Kyoto Dst monthly pages def read_kyoto_month(path): """Hourly Dst of one monthly page. Returns (kind, dict day -> list of 24 values or None for 9999).""" with open(path, encoding="euc-jp", errors="replace") as f: text = f.read() m = re.search(r"Hourly Equatorial Dst Values \((\w[\w -]*)\)", text) kind = m.group(1) if m else "?" body = text.split("DAY", 1)[1].split("