#!/usr/bin/env python3 r"""Recompute every number marked "Our analysis" on factchecked.science/ionosphere-five-cycles/. python3 -I ionosphere_numbers.py Downloads the public inputs into (about 170 MB; files already there are reused), reads them as data only, and writes ionosphere-numbers.json next to this script. Needs numpy. Takes a few minutes, mostly the downloads. What it recomputes, each under rules written before the test ran (the RULES_*.txt files hosted beside this script): K geomagnetic activity by solar cycle, and the share of summer-morning hours with Kpm <= 5 (RULES_kp_cycles.txt) M the main field at the six ionosondes in 1965 and 2015, from IGRF-14 (RULES_igrf_stations.txt) S Juliusruh NmF2 against F30 by cycle, January 14 LT: the registered reading of "disturbed days" (RULES_juliusruh_solar.txt) and amendment 1, the reading that matches the paper's own counts (not blind) (..._amend1.txt) G Juliusruh's summer-morning storm response by cycle (RULES_juliusruh_storm.txt, ..._amend0.txt) E the Kan-Lee field against Kp by cycle, from OMNI2 (RULES_ekl_kpm.txt) P the F30-F10.7 relation by cycle, and straight-line fits (amendment 2, not blind) (RULES_amend2_independent.txt) C the CO2 numbers (RULES_co2.txt) Amendment 3, after a fresh review (post hoc, not blind; RULES_amend3_review.txt): the matched Kan-Lee comparison, which replaces the registered E2 comparison of the cycles' raw medians (withdrawn: it depends on each cycle's overall solar wind and so cannot separate the hypotheses); trend margins that count the scatter between cycles (Test G); a level-then-decline shape for Test S's residuals; and a global IGRF-14 grid at 300 km (Test M). Shared definitions are in RULES_common.txt. The Juliusruh and F30 inputs state no licence, so only derived numbers are published; GFZ's Kp is CC BY 4.0 (Matzka et al. 2021, doi:10.5880/Kp.0001); OMNI is NASA SPDF's; IGRF-14 is IAGA's; the CO2 means are NOAA GML's. The Kp and F30 files grow every day; only data before 2026 are used. """ import datetime as dt import gzip import hashlib import json import math import os import sys import time import urllib.request import numpy as np UA = {"User-Agent": "factchecked-research/1.0"} JULIUSRUH = "https://downloads.sws.bom.gov.au/wdc/iondata/wdc_display/juliusruh/0318.00/031800.%02d.gz" F30_URL = "https://www.iup.uni-bremen.de/gome/solar/rflux_jpn.txt" KP_URL = "https://kp.gfz.de/app/files/Kp_ap_Ap_SN_F107_since_1932.txt" OMNI = "https://spdf.gsfc.nasa.gov/pub/data/omni/low_res_omni/omni2_%d.dat" IGRF_URL = "https://www.ngdc.noaa.gov/IAGA/vmod/coeffs/igrf14coeffs.txt" CO2_URL = "https://gml.noaa.gov/webdata/ccgg/trends/co2/co2_annmean_mlo.txt" T0 = dt.datetime(1957, 1, 1) T1 = dt.datetime(2026, 1, 1) NH = int((T1 - T0).total_seconds() // 3600) ND = NH // 24 CYCLES = [("SC20", dt.datetime(1964, 6, 1), dt.datetime(1975, 12, 1)), ("SC21", dt.datetime(1975, 12, 1), dt.datetime(1986, 3, 1)), ("SC22", dt.datetime(1986, 3, 1), dt.datetime(1996, 2, 1)), ("SC23", dt.datetime(1996, 2, 1), dt.datetime(2008, 6, 1)), ("SC24", dt.datetime(2008, 6, 1), dt.datetime(2019, 4, 1))] SC25 = ("SC25", dt.datetime(2019, 4, 1), T1) SEED = 20261106 SEED3 = 20261107 # amendment 3 T975_3DF, T80_3DF = 3.182446, 0.978472 # Student t quantiles, 3 degrees of freedom FLUX = [60, 70, 80, 90, 100, 110, 120] # ---------------------------------------------------------------- downloads def fetch(url, path): if os.path.exists(path) and os.path.getsize(path) > 0: return os.makedirs(os.path.dirname(path), exist_ok=True) req = urllib.request.Request(url, headers=UA) with urllib.request.urlopen(req, timeout=120) as r: data = r.read() with open(path, "wb") as fh: fh.write(data) time.sleep(0.3) def fetch_all(folder): paths = {"juliusruh": [], "omni": []} for y in range(1957, 2026): p = os.path.join(folder, "juliusruh", "031800.%02d.gz" % (y % 100)) fetch(JULIUSRUH % (y % 100), p) paths["juliusruh"].append(p) for y in range(1964, 2020): p = os.path.join(folder, "omni2", "omni2_%d.dat" % y) fetch(OMNI % y, p) paths["omni"].append(p) for key, url, name in (("f30", F30_URL, "rflux_jpn.txt"), ("kp", KP_URL, "Kp_ap_Ap_SN_F107_since_1932.txt"), ("igrf", IGRF_URL, "igrf14coeffs.txt"), ("co2", CO2_URL, "co2_annmean_mlo.txt")): p = os.path.join(folder, name) fetch(url, p) paths[key] = p return paths def sha256(path): h = hashlib.sha256() with open(path, "rb") as fh: for chunk in iter(lambda: fh.read(1 << 20), b""): h.update(chunk) return h.hexdigest() # ---------------------------------------------------------------- loaders (as in verification/ionosphere-five-cycles/code/common.py) def hour_index(t): return int((t - T0).total_seconds() // 3600) def day_index(t): return (t - T0).days def day_dates(): return [T0 + dt.timedelta(days=i) for i in range(ND)] def load_foF2(files): val = np.full(NH, np.nan) qual = np.full(NH, " ", dtype="= 57 else 2000 + int(fn[-5:-3]) with gzip.open(fn, "rb") as fh: text = fh.read().decode("latin-1") for line in text.splitlines(): if len(line) < 12 or not line[:4].isdigit(): continue if line[0:4] != "0318" or line[4:6] != "00": raise ValueError("unexpected record %r" % line[:12]) yy, mm, dd = int(line[6:8]), int(line[8:10]), int(line[10:12]) year = 1900 + yy if yy >= 57 else 2000 + yy if year != y: raise ValueError("year mismatch in %s" % fn) h0 = hour_index(dt.datetime(year, mm, dd)) body = line[12:].ljust(120) for i in range(24): cell = body[5 * i: 5 * i + 5] v = cell[1:4].strip() if v and v.isdigit() and int(v) > 0: val[h0 + i] = int(v) / 10.0 qual[h0 + i] = cell[0] return val, qual def load_kp(fn): kp_h = np.full(NH, np.nan) kpmax_d = np.full(ND, np.nan) kpmed_d = np.full(ND, np.nan) ap_d = np.full(ND, np.nan) f107_d = np.full(ND, np.nan) defin_d = np.zeros(ND, dtype=int) kp3 = np.full((ND, 8), np.nan) with open(fn, encoding="ascii") as fh: for line in fh: if line.startswith("#") or not line.strip(): continue p = line.split() t = dt.datetime(int(p[0]), int(p[1]), int(p[2])) if t < T0 or t >= T1: continue di = day_index(t) kps = [float(x) for x in p[7:15]] if any(k < 0 for k in kps): continue kp3[di] = kps for j, k in enumerate(kps): kp_h[di * 24 + 3 * j: di * 24 + 3 * j + 3] = k kpmax_d[di] = max(kps) kpmed_d[di] = float(np.median(kps)) ap_d[di] = float(p[23]) f = float(p[25]) f107_d[di] = f if f > 0 else np.nan defin_d[di] = int(p[27]) return dict(kp_h=kp_h, kpmax_d=kpmax_d, kpmed_d=kpmed_d, ap_d=ap_d, f107_d=f107_d, defin_d=defin_d, kp3=kp3) def load_f30(fn): f30 = np.full(ND, np.nan) with open(fn, encoding="latin-1") as fh: for line in fh: if line.startswith("#") or not line.strip(): continue p = line.split() year = int(float(p[0])) t = dt.datetime(year, int(p[1]), int(p[2])) if abs((float(p[0]) - year) * 365.25 - (t - dt.datetime(year, 1, 1)).days) > 2.0: raise ValueError("date mismatch in F30 line %r" % line) if t < T0 or t >= T1: continue v = float(p[3]) if v > 0: f30[day_index(t)] = v return f30 def quiet_days(daily, thresh=3.0, after_days=2): dist = daily >= thresh dist = np.where(np.isnan(daily), True, dist) bad = dist.copy() for k in range(1, after_days + 1): bad[k:] |= dist[:-k] return ~bad def cubic_fit(x, y): ok = np.isfinite(x) & np.isfinite(y) if ok.sum() < 8: return None return np.polyfit(x[ok], y[ok], 3) # ---------------------------------------------------------------- K: activity by cycle def test_k(kp, val): dates = day_dates() last = max(i for i in range(ND) if kp["defin_d"][i] >= 1 and np.isfinite(kp["kpmax_d"][i])) out = {"K1": {}, "K2": {}} for name, a, b in CYCLES + [SC25]: i0, i1 = day_index(a), min(day_index(b), last + 1) k3 = kp["kp3"][i0:i1] ok = np.all(np.isfinite(k3), axis=1) & (kp["defin_d"][i0:i1] >= 1) k3 = k3[ok] years = ok.sum() / 365.25 row = {"days": int(ok.sum()), "years": round(years, 2), "mean_Ap": round(float(np.nanmean(kp["ap_d"][i0:i1][ok])), 2)} for thr, lab in [(4.667, "Kp>=5-"), (5.667, "Kp>=6-"), (6.667, "Kp>=7-"), (7.667, "Kp>=8-")]: n = int((k3 >= thr - 1e-6).sum()) row[lab] = n row[lab + "_per_year"] = round(n / years, 1) sd = int((k3.max(axis=1) >= 4.667 - 1e-6).sum()) row["storm_days(max Kp>=5-)"] = sd row["storm_days_per_year"] = round(sd / years, 1) row["partial"] = name == "SC25" out["K1"][name] = row kph = kp["kp_h"] pk = paired_kp(kph) for wname, (months, uth) in {"A_MayJul_5-7LT": ((5, 6, 7), (4, 5, 6)), "B_NovJan_15-17LT": ((11, 12, 1), (14, 15, 16))}.items(): pooled = {"all": [0, 0], "withdata": [0, 0], "paired_all": [0, 0], "paired_withdata": [0, 0]} out["K2"][wname] = {} for name, a, b in CYCLES: idx = np.array([di * 24 + h for di in range(day_index(a), day_index(b)) if dates[di].month in months for h in uth]) k, p = kph[idx], pk[idx] have = np.isfinite(val[idx]) r = {} for key, sel, arr in (("all", np.isfinite(k), k), ("withdata", np.isfinite(k) & have, k), ("paired_all", np.isfinite(p), p), ("paired_withdata", np.isfinite(p) & have, p)): n = int(sel.sum()) m = int((arr[sel] <= 5.0 + 1e-9).sum()) r[key] = {"n": n, "share_Kpm_le_5": round(100.0 * m / n, 2) if n else None} pooled[key][0] += m pooled[key][1] += n out["K2"][wname][name] = r out["K2"][wname]["SC20-SC24"] = {k: {"n": v[1], "share_Kpm_le_5": round(100.0 * v[0] / v[1], 2)} for k, v in pooled.items()} share = out["K2"]["A_MayJul_5-7LT"]["SC20-SC24"]["all"]["share_Kpm_le_5"] out["K2_decision"] = {"pooled_share_A_all": share, "reproduced(96-99.5%)": bool(96.0 <= share <= 99.5)} return out # ---------------------------------------------------------------- M: IGRF-14 at the stations A_REF = 6371.2 WGS_A, WGS_B = 6378.137, 6356.7523142 STATIONS = [("Boulder", (40.00, -105.30), (40.00, -105.30), 47.72), ("Port Stanley", (-51.60, -57.90), (-51.60, -57.90), 42.21), ("Juliusruh", (54.60, 13.40), (54.60, 13.40), 53.95), ("Slough/Chilton", (51.50, -0.60), (51.70, -1.33), 53.41), ("Moscow", (55.47, 37.30), (55.47, 37.30), 51.05), ("Hobart", (-42.90, 147.32), (-42.90, 147.32), 49.77)] def igrf_coeffs(path): with open(path, encoding="ascii") as fh: lines = [l for l in fh if not l.startswith("#")] years = lines[1].split()[3:] coef = {} for l in lines[2:]: p = l.split() if p: for y, v in zip(years, p[3:]): coef.setdefault(y, {})[(p[0], int(p[1]), int(p[2]))] = float(v) return coef def field(coef, nmax, lat_deg, lon_deg, h_km): lat = math.radians(lat_deg) a2, b2 = WGS_A ** 2, WGS_B ** 2 sl, cl = math.sin(lat), math.cos(lat) rho = math.sqrt(a2 * cl * cl + b2 * sl * sl) r = math.sqrt(h_km * h_km + 2 * h_km * rho + (a2 * a2 * cl * cl + b2 * b2 * sl * sl) / (rho * rho)) cd = (h_km + rho) / r sd = (a2 - b2) / rho * cl * sl / r ct = sl * cd - cl * sd st = cl * cd + sl * sd P = [[0.0] * (nmax + 2) for _ in range(nmax + 2)] dP = [[0.0] * (nmax + 2) for _ in range(nmax + 2)] P[0][0] = 1.0 for n in range(1, nmax + 1): for m in range(0, n + 1): if n == m: k = math.sqrt(1.0 - 1.0 / (2 * m)) if m > 1 else 1.0 P[n][m] = k * st * P[n - 1][m - 1] dP[n][m] = k * (st * dP[n - 1][m - 1] + ct * P[n - 1][m - 1]) elif n == 1 and m == 0: P[1][0], dP[1][0] = ct, -st else: k1 = (2 * n - 1) / math.sqrt(n * n - m * m) k2 = math.sqrt(((n - 1) ** 2 - m * m) / (n * n - m * m)) if n - 1 >= m else 0.0 P[n][m] = k1 * ct * P[n - 1][m] - (k2 * P[n - 2][m] if n - 2 >= m else 0.0) dP[n][m] = k1 * (ct * dP[n - 1][m] - st * P[n - 1][m]) - (k2 * dP[n - 2][m] if n - 2 >= m else 0.0) ph = math.radians(lon_deg) Br = Bt = Bp = 0.0 for n in range(1, nmax + 1): ar = (A_REF / r) ** (n + 2) for m in range(0, n + 1): g = coef.get(("g", n, m), 0.0) h = coef.get(("h", n, m), 0.0) if m > 0 else 0.0 cm, sm = math.cos(m * ph), math.sin(m * ph) Br += (n + 1) * ar * (g * cm + h * sm) * P[n][m] Bt += -ar * (g * cm + h * sm) * dP[n][m] Bp += ar * m * (g * sm - h * cm) * P[n][m] / st X, Y, Z = -Bt, Bp, -Br Xd, Zd = X * cd + Z * sd, -X * sd + Z * cd H = math.hypot(Xd, Y) return dict(F=math.sqrt(Xd * Xd + Y * Y + Zd * Zd), I=math.degrees(math.atan2(Zd, H)), D=math.degrees(math.atan2(Y, Xd)), gc_lat=90.0 - math.degrees(math.atan2(st, ct))) def dipole(c): g10, g11, h11 = c[("g", 1, 0)], c[("g", 1, 1)], c[("h", 1, 1)] B0 = math.sqrt(g10 ** 2 + g11 ** 2 + h11 ** 2) return B0, 90.0 - math.degrees(math.acos(-g10 / B0)), math.degrees(math.atan2(-h11, -g11)), B0 * 1e-9 * (A_REF * 1e3) ** 3 / 1e-7 def dlat(lat, lon, plat, plon): a, b = math.radians(lat), math.radians(plat) return math.degrees(math.asin(math.sin(a) * math.sin(b) + math.cos(a) * math.cos(b) * math.cos(math.radians(lon - plon)))) def grid_fall(co, h_km=300.0): """Percentage fall of F from 1965 to 2015 on a 1-degree grid of cell centres; Legendre functions per latitude.""" lats = np.arange(-89.5, 90.0, 1.0) lons = np.arange(-179.5, 180.0, 1.0) lon = np.radians(lons) fields = {} for yr, nmax in (("1965.0", 10), ("2015.0", 13)): coef = co[yr] cosm = [np.cos(m * lon) for m in range(nmax + 1)] sinm = [np.sin(m * lon) for m in range(nmax + 1)] F = np.zeros((len(lats), len(lons))) for i, lat_deg in enumerate(lats): lat = math.radians(lat_deg) a2, b2 = WGS_A ** 2, WGS_B ** 2 sl, cl = math.sin(lat), math.cos(lat) rho = math.sqrt(a2 * cl * cl + b2 * sl * sl) r = math.sqrt(h_km * h_km + 2 * h_km * rho + (a2 * a2 * cl * cl + b2 * b2 * sl * sl) / (rho * rho)) cd = (h_km + rho) / r sd = (a2 - b2) / rho * cl * sl / r ct, st = sl * cd - cl * sd, cl * cd + sl * sd P = [[0.0] * (nmax + 2) for _ in range(nmax + 2)] dP = [[0.0] * (nmax + 2) for _ in range(nmax + 2)] P[0][0] = 1.0 for n in range(1, nmax + 1): for m in range(0, n + 1): if n == m: k = math.sqrt(1.0 - 1.0 / (2 * m)) if m > 1 else 1.0 P[n][m] = k * st * P[n - 1][m - 1] dP[n][m] = k * (st * dP[n - 1][m - 1] + ct * P[n - 1][m - 1]) elif n == 1 and m == 0: P[1][0], dP[1][0] = ct, -st else: k1 = (2 * n - 1) / math.sqrt(n * n - m * m) k2 = math.sqrt(((n - 1) ** 2 - m * m) / (n * n - m * m)) if n - 1 >= m else 0.0 P[n][m] = k1 * ct * P[n - 1][m] - (k2 * P[n - 2][m] if n - 2 >= m else 0.0) dP[n][m] = k1 * (ct * dP[n - 1][m] - st * P[n - 1][m]) - (k2 * dP[n - 2][m] if n - 2 >= m else 0.0) Br = np.zeros(len(lons)) Bt = np.zeros(len(lons)) Bp = np.zeros(len(lons)) for n in range(1, nmax + 1): ar = (A_REF / r) ** (n + 2) for m in range(0, n + 1): g = coef.get(("g", n, m), 0.0) hh = coef.get(("h", n, m), 0.0) if m > 0 else 0.0 gc = g * cosm[m] + hh * sinm[m] Br += (n + 1) * ar * gc * P[n][m] Bt += -ar * gc * dP[n][m] Bp += ar * m * (g * sinm[m] - hh * cosm[m]) * P[n][m] / st X, Y, Z = -Bt, Bp, -Br F[i] = np.sqrt((X * cd + Z * sd) ** 2 + Y ** 2 + (-X * sd + Z * cd) ** 2) fields[yr] = F fall = 100.0 * (1.0 - fields["2015.0"] / fields["1965.0"]) w = np.repeat(np.cos(np.radians(lats))[:, None], len(lons), axis=1) res = {} for label, thr in (("PortStanley_10.91", 10.91), ("dipole_3.5", 3.5)): s = fall > thr res["cells_falling_more_than_" + label] = {"share_cells": round(float(s.mean()), 4), "share_area": round(float((w * s).sum() / w.sum()), 4)} i, j = np.unravel_index(np.argmax(fall), fall.shape) res["largest_fall_pct"] = round(float(fall[i, j]), 2) res["largest_fall_cell"] = {"lat": float(lats[i]), "lon": float(lons[j])} ii, jj = np.where(fall > 10.0) res["cells_falling_more_than_10pct_range"] = {"lat": [float(lats[ii].min()), float(lats[ii].max())], "lon": [float(lons[jj].min()), float(lons[jj].max())], "n_cells": int(len(ii))} return res def test_m(path): co = igrf_coeffs(path) c65, c15 = co["1965.0"], co["2015.0"] d65, d15 = dipole(c65), dipole(c15) out = {"dipole_moment_1e22_Am2": {"1965": round(d65[3] / 1e22, 4), "2015": round(d15[3] / 1e22, 4)}, "dipole_moment_change_pct": round(100 * (round(d15[3] / 1e22, 4) / round(d65[3] / 1e22, 4) - 1), 2), "stations": []} for name, p65, p15, tab in STATIONS: f65, f15 = field(c65, 10, p65[0], p65[1], 300.0), field(c15, 13, p15[0], p15[1], 300.0) m65, m15 = dlat(p65[0], p65[1], d65[1], d65[2]), dlat(p15[0], p15[1], d15[1], d15[2]) m15gc = dlat(f15["gc_lat"], p15[1], d15[1], d15[2]) out["stations"].append({"station": name, "F300_1965_nT": round(f65["F"], 1), "F300_2015_nT": round(f15["F"], 1), "F300_change_pct": round(100 * (f15["F"] / f65["F"] - 1), 2), "I300_1965": round(f65["I"], 2), "I300_2015": round(f15["I"], 2), "dipole_lat_1965": round(m65, 2), "dipole_lat_2015": round(m15, 2), "dipole_lat_change_deg": round(abs(m15) - abs(m65), 2), "dipole_lat_2015_from_geocentric_lat": round(m15gc, 2), "table1_geomag_lat": tab}) out["amend3_global_grid_300km"] = grid_fall(co) return out # ---------------------------------------------------------------- S: the solar response at Juliusruh def covered(x, v, k=5): return (x <= v).sum() >= k and (x >= v).sum() >= k def s_select(val, qual, proxy, daily_kp, ut=13, drop_q=False, also_kp2=False, years_out=None): dates = day_dates() quiet = quiet_days(daily_kp, 3.0, 2) if also_kp2: quiet &= quiet_days(daily_kp, 2.0, 0) rows = [] for di, d in enumerate(dates): if d.month != 1 or not quiet[di]: continue if years_out and years_out[0] <= d.year <= years_out[1]: continue h = di * 24 + ut v = val[h] if not np.isfinite(v) or (drop_q and qual[h] in ("D", "E", "I", "U")): continue nm = 1.24e10 * v * v if nm > 4e12 or not np.isfinite(proxy[di]): continue rows.append((di, d, proxy[di], nm)) return rows def by_cycle(rows): return {n: (np.array([r[2] for r in rows if a <= r[1] < b]), np.array([r[3] for r in rows if a <= r[1] < b])) for n, a, b in CYCLES} def s_variant(rows, boot): cyc = by_cycle(rows) fits = {n: cubic_fit(x, y) for n, (x, y) in cyc.items()} table = {n: {"n": int(len(x)), "F_range": [float(x.min()), float(x.max())] if len(x) else None, "fit_1e11": {str(v): (round(float(np.polyval(fits[n], v)) / 1e11, 4) if covered(x, v) else None) for v in FLUX}} for n, (x, y) in cyc.items()} (x20, y20), (x24, y24) = cyc["SC20"], cyc["SC24"] boots = [] if boot: rng = np.random.default_rng(SEED) for _ in range(2000): s20 = rng.choice(len(x20), len(x20), replace=True) s24 = rng.choice(len(x24), len(x24), replace=True) boots.append((cubic_fit(x20[s20], y20[s20]), cubic_fit(x24[s24], y24[s24]))) diff = {} for v in FLUX: if not (covered(x20, v) and covered(x24, v)): diff[str(v)] = None continue f20, f24 = np.polyval(fits["SC20"], v), np.polyval(fits["SC24"], v) pct = 100.0 * (f24 - f20) / f20 row = {"pct_SC24_vs_SC20": round(pct, 2), "pct_per_year_43.6y": round(pct / 43.6, 3), "abs_per_year_1e9_43.6y": round((f24 - f20) / 1e9 / 43.6, 2)} if boot: b = np.array([100.0 * (np.polyval(c24, v) - np.polyval(c20, v)) / np.polyval(c20, v) for c20, c24 in boots]) row["pct_95ci"] = [round(float(np.percentile(b, 2.5)), 2), round(float(np.percentile(b, 97.5)), 2)] diff[str(v)] = row return table, diff, fits def s_decision(diff): neg = all(v is None or v["pct_SC24_vs_SC20"] < 0 for v in diff.values()) p60 = diff["60"]["pct_per_year_43.6y"] if diff.get("60") else None p90 = diff["90"]["pct_per_year_43.6y"] if diff.get("90") else None return {"direction_reproduced": neg, "pct_per_year_60": p60, "pct_per_year_90": p90, "size_reproduced": bool(p60 is not None and p90 is not None and 0.29 / 1.5 <= -p60 <= 0.29 * 1.5 and 0.44 / 1.5 <= -p90 <= 0.44 * 1.5)} def residual_series(rows): X = np.array([r[2] for r in rows]) Y = np.array([r[3] for r in rows]) yrs = np.array([r[1].year for r in rows]) c = cubic_fit(X, Y) pres = 100.0 * (Y - np.polyval(c, X)) / np.polyval(c, X) ann = {y: float(np.median(pres[yrs == y])) for y in range(1957, 2026) if (yrs == y).sum() >= 5} yy = np.array([k for k in ann if 1964 <= k <= 2019], dtype=float) rr = np.array([ann[int(k)] for k in yy]) def line(sel): A = np.vstack([yy[sel] - 1990, np.ones(sel.sum())]).T co, *_ = np.linalg.lstsq(A, rr[sel], rcond=None) res = rr[sel] - A @ co se = float(np.sqrt(((res ** 2).sum() / (sel.sum() - 2)) * np.linalg.inv(A.T @ A)[0, 0])) return co[0], se, float((res ** 2).sum()) s, se, rss = line(np.ones(len(yy), bool)) best = None for ys in range(1970, 2015): lo, hi = rr[yy < ys], rr[yy >= ys] if len(lo) < 3 or len(hi) < 3: continue r = ((lo - lo.mean()) ** 2).sum() + ((hi - hi.mean()) ** 2).sum() if best is None or r < best[0]: best = (r, ys, hi.mean() - lo.mean()) steps = {} for ys in (1990, 1993, 1994, 1995): lo, hi = rr[yy < ys], rr[yy >= ys] steps[str(ys)] = {"step_pct": round(float(hi.mean() - lo.mean()), 2), "rss": round(float(((lo - lo.mean()) ** 2).sum() + ((hi - hi.mean()) ** 2).sum()), 1)} eras = {} for name, (y0, y1) in {"1964-1989": (1964, 1989), "1995-2019": (1995, 2019)}.items(): sel = (yy >= y0) & (yy <= y1) if sel.sum() >= 5: s2, se2, _ = line(sel) eras[name] = {"n_years": int(sel.sum()), "pct_per_decade": round(10 * s2, 2), "95ci": [round(10 * (s2 - 1.96 * se2), 2), round(10 * (s2 + 1.96 * se2), 2)]} hinge = None for t0 in range(1970, 2011): X = np.vstack([np.ones_like(yy), np.maximum(yy - t0, 0.0)]).T coh, *_ = np.linalg.lstsq(X, rr, rcond=None) rh = float(((rr - X @ coh) ** 2).sum()) if hinge is None or rh < hinge[0]: hinge = (rh, t0, coh[1]) return {"annual_median_residual_pct": {str(k): round(v, 2) for k, v in ann.items()}, "amend3_level_then_decline": {"hinge_year": hinge[1], "slope_after_pct_per_decade": round(10 * float(hinge[2]), 2), "rss": round(hinge[0], 1)}, "linear_1964-2019_pct_per_decade": round(10 * s, 2), "linear_95ci_pct_per_decade": [round(10 * (s - 1.96 * se), 2), round(10 * (s + 1.96 * se), 2)], "linear_rss": round(rss, 1), "best_step_year": best[1], "best_step_size_pct": round(float(best[2]), 2), "best_step_rss": round(float(best[0]), 1), "steps_at_instrument_changes": steps, "trend_within_eras": eras, "n_years": int(len(rr))} def test_s(val, qual, f30, kp): out = {} readings = {"registered_daily_max": kp["kpmax_d"], "amend1_daily_mean": np.nanmean(kp["kp3"], axis=1)} a, b = hour_index(dt.datetime(1957, 7, 1)), hour_index(dt.datetime(2024, 1, 1)) have = np.isfinite(val[a:b]) nm = 1.24e10 * val[a:b] ** 2 for rname, daily in readings.items(): qh = np.repeat(quiet_days(daily, 3.0, 2), 24)[a:b] ok = have & ~(nm > 4e12) r = {"table2_counts_1957-07_to_2023": {"total_hours": int(b - a), "missing": int((~have).sum()), "outliers_gt_4e12": int((nm > 4e12).sum()), "removed_disturbed": int((ok & ~qh).sum()), "remaining": int((ok & qh).sum()), "paper": {"total": 582960, "nan": 48658, "outliers": 3, "disturbed": 214238, "remaining": 320061}}} for vname, kw in {"main_13UT": dict(ut=13), "14UT": dict(ut=14), "drop_DEIU": dict(ut=13, drop_q=True), "also_Kp_ge_2": dict(ut=13, also_kp2=True)}.items(): rows = s_select(val, qual, f30, daily, **kw) table, diff, fits = s_variant(rows, boot=(vname == "main_13UT")) r[vname] = {"per_cycle": table, "SC24_minus_SC20": diff} if vname == "main_13UT": main_rows, main_fits = rows, fits r["decision"] = s_decision(diff) rows = s_select(val, qual, kp["f107_d"], daily, ut=13) table, diff, _ = s_variant(rows, boot=False) r["F107obs"] = {"per_cycle": table, "SC24_minus_SC20": diff} xe, ye = by_cycle(s_select(val, qual, f30, daily, ut=13, years_out=(1990, 1994)))["SC22"] xm = by_cycle(main_rows)["SC22"][0] ce = cubic_fit(xe, ye) r["SC22_without_1990-94"] = {"n": int(len(xe)), "n_main": int(len(xm)), "fit_1e11": {str(v): (round(float(np.polyval(ce, v)) / 1e11, 4) if covered(xe, v) else None) for v in FLUX}, "main_fit_1e11": {str(v): (round(float(np.polyval(main_fits["SC22"], v)) / 1e11, 4) if covered(xm, v) else None) for v in FLUX}} r["residual_series"] = residual_series(main_rows) out[rname] = r return out # ---------------------------------------------------------------- G: the storm response at Juliusruh def paired_kp(kph, lag=9, width=17, centred=False): cs = np.concatenate([[0.0], np.cumsum(np.nan_to_num(kph))]) cn = np.concatenate([[0], np.cumsum(np.isfinite(kph))]) t = np.arange(len(kph)) hi = t - lag + width // 2 + 1 if centred else t - lag + 1 lo = hi - width out = np.full(len(kph), np.nan) ok = (lo >= 0) & (hi <= len(kph)) s = cs[hi[ok]] - cs[lo[ok]] n = cn[hi[ok]] - cn[lo[ok]] out[ok] = np.where(n == width, s / np.maximum(n, 1), np.nan) return out def g_build(val, f30, kph, quiet, centred): dates = day_dates() pk = paired_kp(kph, centred=centred) recs, minfit = [], 10 ** 9 for name, a, b in CYCLES: for m in (5, 6, 7): days = [di for di in range(day_index(a), day_index(b)) if dates[di].month == m] for h in (4, 5, 6): xs, ys = [], [] for di in days: v = val[di * 24 + h] if np.isfinite(v) and np.isfinite(f30[di]) and 1.24e10 * v * v <= 4e12 and quiet[di]: xs.append(f30[di]) ys.append(1.24e10 * v * v) minfit = min(minfit, len(xs)) c = cubic_fit(np.array(xs), np.array(ys)) if c is None: continue for di in days: v = val[di * 24 + h] if not np.isfinite(v) or not np.isfinite(f30[di]) or 1.24e10 * v * v > 4e12: continue model = np.polyval(c, f30[di]) k = pk[di * 24 + h] if model > 0 and np.isfinite(k): recs.append((name, di, h, 100.0 * (1.24e10 * v * v - model) / model, k)) return recs, minfit def g_clean(recs): out, removed = [], {} for name, _, _ in CYCLES: r = [x for x in recs if x[0] == name] y = np.array([x[3] for x in r]) k = np.array([x[4] for x in r]) res = y - np.polyval(np.polyfit(k, y, 1), k) keep = np.abs(res) <= 2 * res.std(ddof=1) removed[name] = {"n": int(len(r)), "removed": int((~keep).sum()), "removed_pct": round(100 * (~keep).mean(), 2)} out += [x for x, kk in zip(r, keep) if kk] return out, removed def medians_by_bin(y, k, centres=(2, 3, 4)): return np.array([np.median(y[(k >= c - 1) & (k < c + 1)]) if ((k >= c - 1) & (k < c + 1)).sum() else np.nan for c in centres]) def g_analyse(recs): res, per = {}, {} names = [n for n, _, _ in CYCLES] for name in names: r = [x for x in recs if x[0] == name] y, k = np.array([x[3] for x in r]), np.array([x[4] for x in r]) d, h = np.array([x[1] for x in r]), np.array([x[2] for x in r]) per[name] = (y, k, d, h) bins = {} for c in (1, 2, 3, 4, 5, 6): s = (k >= c - 1.0) & (k < c + 1.0) if s.sum(): q1, med, q3 = np.percentile(y[s], [25, 50, 75]) bins[str(c)] = {"n": int(s.sum()), "median": round(float(med), 2), "q1": round(float(q1), 2), "q3": round(float(q3), 2), "flag_lt10": bool(s.sum() < 10)} else: bins[str(c)] = {"n": 0} res[name] = {"n": int(len(y)), "pearson_r_5-7LT": round(float(np.corrcoef(y, k)[0, 1]), 3), "pearson_r_6LT": round(float(np.corrcoef(y[h == 5], k[h == 5])[0, 1]), 3), "bins": bins} ally = np.concatenate([per[n][0] for n in names]) allk = np.concatenate([per[n][1] for n in names]) allh = np.concatenate([per[n][3] for n in names]) res["pooled"] = {"n": int(len(ally)), "pearson_r_5-7LT": round(float(np.corrcoef(ally, allk)[0, 1]), 3), "pearson_r_6LT": round(float(np.corrcoef(ally[allh == 5], allk[allh == 5])[0, 1]), 3)} cyc_no = np.arange(len(names), dtype=float) A = np.vstack([cyc_no, np.ones_like(cyc_no)]).T slope = lambda m: np.linalg.lstsq(A, m, rcond=None)[0][0] med = np.array([medians_by_bin(per[n][0], per[n][1]) for n in names]) rng = np.random.default_rng(SEED) groups = {} for n in names: d = per[n][2] ud = np.unique(d) groups[n] = (ud, {u: np.where(d == u)[0] for u in ud}) bs_s, bs_d = [], [] for _ in range(2000): mm = [] for n in names: y, k = per[n][0], per[n][1] ud, ibd = groups[n] ii = np.concatenate([ibd[u] for u in rng.choice(ud, len(ud), replace=True)]) mm.append(medians_by_bin(y[ii], k[ii])) mm = np.array(mm) bs_s.append([slope(mm[:, j]) for j in range(3)]) bs_d.append(mm[-1] - mm[0]) bs_s, bs_d = np.array(bs_s), np.array(bs_d) det = {} for j, c in enumerate((2, 3, 4)): lo, hi = np.nanpercentile(bs_s[:, j], [2.5, 97.5]) dlo, dhi = np.nanpercentile(bs_d[:, j], [2.5, 97.5]) det[str(c)] = {"cycle_medians": [round(float(x), 2) for x in med[:, j]], "slope_pp_per_cycle": round(float(slope(med[:, j])), 2), "slope_95ci": [round(float(lo), 2), round(float(hi), 2)], "slope_ci_halfwidth": round(float((hi - lo) / 2), 2), "SC24_minus_SC20": round(float(med[-1, j] - med[0, j]), 2), "diff_95ci": [round(float(dlo), 2), round(float(dhi), 2)]} for j, c in enumerate((2, 3, 4)): y5 = np.round(med[:, j], 2) # the medians as published (2 decimals), as in the verification run co5 = np.linalg.lstsq(A, y5, rcond=None)[0] se5 = math.sqrt(((y5 - A @ co5) ** 2).sum() / 3 / ((cyc_no - cyc_no.mean()) ** 2).sum()) det[str(c)]["amend3_ols_95_halfwidth"] = round(T975_3DF * se5, 2) det[str(c)]["amend3_trend_detected_4_in_5"] = round((T975_3DF + T80_3DF) * se5, 2) det[str(c)]["amend3_share_of_response_4_steps"] = round(4 * T975_3DF * se5 / abs(float(y5.mean())), 2) res["detectability"] = det overlap = all(not (None in [res[n]["bins"][c].get("q1") for n in names] + [res[n]["bins"][c].get("q3") for n in names]) and max(res[n]["bins"][c]["q1"] for n in names) <= min(res[n]["bins"][c]["q3"] for n in names) for c in ("1", "2", "3", "4")) zero = all(v["slope_95ci"][0] <= 0 <= v["slope_95ci"][1] for v in det.values()) res["decision"] = {"IQRs_overlap_bins_1-4": overlap, "slope_CIs_include_zero": zero, "similar_response_reproduced": bool(overlap and zero)} return res def test_g(val, f30, kp): out = {} for name, daily, centred in (("main_daily_mean_trailing", np.nanmean(kp["kp3"], axis=1), False), ("daily_max_trailing", kp["kpmax_d"], False), ("daily_mean_centred", np.nanmean(kp["kp3"], axis=1), True)): recs, minfit = g_build(val, f30, kp["kp_h"], quiet_days(daily, 3.0, 2), centred) kept, removed = g_clean(recs) r = g_analyse(kept) r["outliers"] = removed r["min_quiet_points_in_a_fit"] = int(minfit) out[name] = r return out # ---------------------------------------------------------------- E: Kan-Lee field against Kp def load_omni(files): ekl = np.full(NH, np.nan) imf = np.full(NH, -1, dtype=int) for fn in files: with open(fn, encoding="ascii") as fh: for line in fh: p = line.split() if len(p) < 25: continue t = dt.datetime(int(p[0]), 1, 1) + dt.timedelta(days=int(p[1]) - 1, hours=int(p[2])) by, bz, v = float(p[15]), float(p[16]), float(p[24]) if by >= 999.0 or bz >= 999.0 or v >= 9999.0: continue bt = (by * by + bz * bz) ** 0.5 s2 = 0.5 if bt == 0 else (1.0 - bz / bt) / 2.0 h = hour_index(t) ekl[h] = v * bt * s2 * 1e-3 imf[h] = int(p[4]) return ekl, imf def daily_ekl(ekl, min_hours): e = ekl[: ND * 24].reshape(ND, 24) n = np.isfinite(e).sum(axis=1) med = np.full(ND, np.nan) ok = n >= min_hours med[ok] = np.nanmedian(e[ok], axis=1) return med, n def crossing(e, k, level=4.0): """E_KL at which the median Kpm in bins 1 mV/m wide (step 0.5, at least 10 days) first reaches the level.""" centres, meds = [], [] for kk in range(1, 40): s = (e >= 0.5 * kk - 0.5) & (e < 0.5 * kk + 0.5) if s.sum() >= 10: centres.append(0.5 * kk) meds.append(float(np.median(k[s]))) for j in range(1, len(meds)): if meds[j - 1] < level <= meds[j]: return centres[j - 1] + (level - meds[j - 1]) / (meds[j] - meds[j - 1]) * (centres[j] - centres[j - 1]) return None def test_e(files, kp): ekl, _ = load_omni(files) ed, n = daily_ekl(ekl, 12) kpd = kp["kpmed_d"] out = {"coverage": {}, "paper_representation": {}, "forcing": {}} names = [nm for nm, _, _ in CYCLES] e_all, k_all, c_all = [], [], [] for name, a, b in CYCLES: h0, h1, i0, i1 = hour_index(a), hour_index(b), day_index(a), day_index(b) out["coverage"][name] = {"hours_valid_pct": round(100 * np.isfinite(ekl[h0:h1]).mean(), 1), "days_ge12h_pct": round(100 * (n[i0:i1] >= 12).mean(), 1)} e, k = ed[i0:i1], kpd[i0:i1] ok = np.isfinite(e) & np.isfinite(k) e, k = e[ok], k[ok] out["paper_representation"][name] = {"EKL_at_Kpm_3": round(crossing(e, k, 3.0), 2), "EKL_at_Kpm_4": round(crossing(e, k, 4.0), 2)} out["forcing"][name] = {"mean_daily_EKL": round(float(e.mean()), 3), "mean_daily_Kpm": round(float(k.mean()), 3), "days": int(len(e))} e_all += list(e) k_all += list(k) c_all += [name] * len(e) e_all, k_all, c_all = np.array(e_all), np.array(k_all), np.array(c_all) order = np.argsort(e_all, kind="stable") def stat(k, name, lo, hi): return float(np.median(e_all[(c_all == name) & (k >= lo) & (k < hi)])) # amendment 3: each cycle against its own solar wind under one shared relation (days pooled into groups by E_KL) matched = {"note": "observed = median daily E_KL on the cycle's days with Kpm in the window; null = the same with each day's " "Kpm drawn from its pooled group of days of similar E_KL (500 draws)", "n_days": int(len(e_all))} for size in (100, 50, 200): groups = [order[g:g + size] for g in range(0, len(order), size)] for lo, hi in ((3.5, 4.5), (2.5, 3.5)): if size != 100 and (lo, hi) != (3.5, 4.5): continue rng = np.random.default_rng(SEED3) draws = {nm: [] for nm in names} cross = {nm: [] for nm in names} main = size == 100 and (lo, hi) == (3.5, 4.5) for _ in range(500): knew = np.empty_like(k_all) for idx in groups: knew[idx] = rng.choice(k_all[idx], len(idx), replace=True) for nm in names: draws[nm].append(stat(knew, nm, lo, hi)) if main: sel = c_all == nm cross[nm].append(crossing(e_all[sel], knew[sel])) key = "groups%d_Kpm%g-%g" % (size, lo, hi) matched[key] = {} for nm in names: obs = stat(k_all, nm, lo, hi) d = np.array(draws[nm]) row = {"observed": round(obs, 3), "null_mean": round(float(d.mean()), 3), "observed_minus_null": round(obs - float(d.mean()), 3), "share_draws_ge_observed": round(float((d >= obs).mean()), 4)} if main: cv = np.array([x for x in cross[nm] if x is not None]) sel = c_all == nm ob = round(crossing(e_all[sel], k_all[sel]), 2) row.update({"EKL_at_Kpm_4_observed": ob, "EKL_at_Kpm_4_null_mean": round(float(cv.mean()), 2), "EKL_at_Kpm_4_null_2.5-97.5": [round(float(np.percentile(cv, 2.5)), 2), round(float(np.percentile(cv, 97.5)), 2)], "EKL_at_Kpm_4_share_draws_ge_observed": round(float((cv >= ob).mean()), 4)}) matched[key][nm] = row out["amend3_matched"] = matched return out # ---------------------------------------------------------------- P: the proxies, and straight-line fits def test_p(val, qual, f30, kp): daily = np.nanmean(kp["kp3"], axis=1) out = {"linear_fits_SC24_minus_SC20_pct": {}, "ratio": {}} for pname, proxy, grid in (("F30", f30, (60, 80, 100)), ("F107obs", kp["f107_d"], (80, 100, 120))): cyc = by_cycle(s_select(val, qual, proxy, daily, ut=13)) lines = {n: np.polyfit(x, y, 1) for n, (x, y) in cyc.items()} out["linear_fits_SC24_minus_SC20_pct"][pname] = {str(g): round(100 * (np.polyval(lines["SC24"], g) / np.polyval(lines["SC20"], g) - 1), 2) for g in grid} fits = {} for name, a, b in CYCLES: i0, i1 = day_index(a), day_index(b) ok = np.isfinite(f30[i0:i1]) & np.isfinite(kp["f107_d"][i0:i1]) x, y = kp["f107_d"][i0:i1][ok], f30[i0:i1][ok] fits[name] = np.polyfit(x, y, 1) out["ratio"][name] = {"days": int(ok.sum()), "median_F30_over_F107": round(float(np.median(y / x)), 4), "F30_at_F107": {str(g): round(float(np.polyval(fits[name], g)), 2) for g in (80, 100, 120, 150)}} out["ratio"]["SC24_vs_SC20_pct_F30_at_F107"] = {str(g): round(100 * (np.polyval(fits["SC24"], g) / np.polyval(fits["SC20"], g) - 1), 2) for g in (80, 100, 120, 150)} x20, y20 = by_cycle(s_select(val, qual, kp["f107_d"], daily, ut=13))["SC20"] c20 = np.polyfit(x20, y20, 3) inv = {n: (90.0 - fits[n][1]) / fits[n][0] for n in ("SC20", "SC24")} out["ratio"]["F107_for_F30_90"] = {n: round(float(v), 1) for n, v in inv.items()} out["ratio"]["NmF2_change_from_proxy_shift_alone_pct"] = round(float(100 * (np.polyval(c20, inv["SC24"]) / np.polyval(c20, inv["SC20"]) - 1)), 2) return out # ---------------------------------------------------------------- C: CO2 def test_c(path): ann = {} with open(path, encoding="ascii") as fh: for line in fh: if line.startswith("#") or not line.strip(): continue p = line.split() ann[int(p[0])] = float(p[1]) fr = lambda a, b: round(math.log(b / a) / math.log(2), 3) return {"Mauna_Loa_ppm": {str(y): ann[y] for y in (1964, 2018, 2019)}, "fraction_of_doubling": {"paper_319_to_409": fr(319, 409), "mlo_1964_to_2019": fr(ann[1964], ann[2019]), "Liu2021_345_to_690": fr(345, 690), "Pedatella2025_400_to_918": fr(400, 918)}, "observed_as_share_of_models": {"Liu2021": round(fr(319, 409) / fr(345, 690), 3), "Pedatella2025": round(fr(319, 409) / fr(400, 918), 3)}} def main(): if len(sys.argv) != 2: sys.exit(__doc__) folder = os.path.abspath(sys.argv[1]) os.makedirs(folder, exist_ok=True) paths = fetch_all(folder) val, qual = load_foF2(paths["juliusruh"]) kp = load_kp(paths["kp"]) f30 = load_f30(paths["f30"]) out = {"about": "Our numbers for factchecked.science/ionosphere-five-cycles/; see the docstring of ionosphere_numbers.py", "K_activity": test_k(kp, val), "M_field": test_m(paths["igrf"]), "S_solar_response": test_s(val, qual, f30, kp), "G_storm_response": test_g(val, f30, kp), "E_kan_lee": test_e(paths["omni"], kp), "P_proxies": test_p(val, qual, f30, kp), "C_co2": test_c(paths["co2"])} inputs = {} for key in ("f30", "kp", "igrf", "co2"): inputs[os.path.basename(paths[key])] = sha256(paths[key]) for key in ("juliusruh", "omni"): for p in paths[key]: inputs[key + "/" + os.path.basename(p)] = sha256(p) out["inputs_sha256"] = inputs dest = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ionosphere-numbers.json") with open(dest, "w", encoding="utf-8", newline="\n") as fh: json.dump(out, fh, indent=1, ensure_ascii=False) fh.write("\n") print("wrote", dest) if __name__ == "__main__": main()