#!/usr/bin/env python3 """Earth's main field along the brown planthopper's migration route, from IGRF-14. Fact-Checked Science ("Our analysis"), https://factchecked.science/planthopper-magnetic-genes/ Data: Xie, W., et al. (2026), Dryad, doi:10.5061/dryad.r4xgxd2vx (CC0); make the input folder with prepare_inputs.py, then pass /dataset (or /field for igrf_route.py) as the script's usage says. Fact-Checked Science, planthopper-magnetic-genes ("Our analysis"). Rules: RULES_igrf_route.txt (fixed first). Standard library only. The spherical-harmonic synthesis is adapted from the site's published pages/magnetic-field-guide/field_decline.py and is checked here against NOAA's WMM2025 test values. Usage: python3 igrf_route.py Inputs are read as data (the zip is read in memory; nothing in it is executed or extracted). """ import hashlib import json import math import os import sys import zipfile IGRF_SHA256 = "8f8d88403028fc4ee92c4f38d97b46e0a87e2cfc496045b43c9e26c1d6b0903c" WMM_SHA256 = "999080a12c95122c2031aeac8be77229d97584530e87e0f1a6df7d946ecf90c5" A_REF = 6371.2 WGS84_A = 6378.137 WGS84_F = 1.0 / 298.257223563 WGS84_E2 = WGS84_F * (2.0 - WGS84_F) NMAX = 13 SITES = [ # name, lat, lon, role (from RULES_igrf_route.txt) ("Hanoi", 21.03, 105.85, "primary"), ("Haikou", 20.04, 110.32, "primary"), ("Zhanjiang", 21 + 12 / 60 + 29 / 3600, 110 + 21 / 60 + 11 / 3600, "primary"), ("Nanning", 22.82, 108.32, "primary"), ("Guangzhou", 23.13, 113.26, "primary"), ("Changsha", 28.23, 112.94, "primary"), ("Wuhan", 30.59, 114.31, "primary"), ("Nanjing", 32 + 3 / 60 + 42 / 3600, 118 + 46 / 60 + 40 / 3600, "primary"), ("Gwangju", 35.16, 126.85, "primary"), ("Fukuoka", 33.59, 130.40, "primary"), ("Hue", 16.46, 107.59, "sensitivity"), ] DATES = [1900.0, 1950.0, 2000.0, 2020.0, 2025.0, 2026.0] EPOCHS_5Y = [1900.0 + 5 * k for k in range(26)] # 1900 ... 2025 def sha256(path): with open(path, "rb") as f: return hashlib.sha256(f.read()).hexdigest() def read_igrf(path): 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:]] return epochs, {k: v[:-1] for k, v in rows.items()}, {k: v[-1] for k, v in rows.items()} def zeros(): return [[0.0] * (NMAX + 1) for _ in range(NMAX + 1)] def igrf_at(epochs, main, sv, t): g, h = zeros(), zeros() if t >= epochs[-1]: i0 = len(epochs) - 1 for (gh, n, m), v in main.items(): (g if gh == "g" else h)[n][m] = v[i0] + (t - epochs[-1]) * sv[(gh, n, m)] else: i0 = max(i for i, e in enumerate(epochs) if e <= t) w = (t - epochs[i0]) / (epochs[i0 + 1] - epochs[i0]) for (gh, n, m), v in main.items(): (g if gh == "g" else h)[n][m] = v[i0] + w * (v[i0 + 1] - v[i0]) return g, h def read_wmm(zpath): z = zipfile.ZipFile(zpath) names = {os.path.basename(n): n for n in z.namelist()} cof = z.read(names["WMM.COF"]).decode("ascii") tests = z.read(names["WMM2025_TEST_VALUES.txt"]).decode("ascii") g, h, gd, hd = zeros(), zeros(), zeros(), zeros() lines = cof.splitlines() epoch = float(lines[0].split()[0]) for line in lines[1:]: p = line.split() if len(p) < 6 or p[0].startswith("9999"): continue n, m = int(p[0]), int(p[1]) g[n][m], h[n][m], gd[n][m], hd[n][m] = map(float, p[2:6]) return epoch, g, h, gd, hd, tests def geodetic_to_geocentric(lat_deg, h_km): phi = math.radians(lat_deg) s, c = math.sin(phi), math.cos(phi) N = WGS84_A / math.sqrt(1.0 - WGS84_E2 * s * s) x = (N + h_km) * c z = (N * (1.0 - WGS84_E2) + h_km) * s phic = math.atan2(z, x) return math.hypot(x, z), phic, phi - phic def legendre(theta): ct, st = math.cos(theta), math.sin(theta) P, D = zeros(), zeros() P[0][0], P[1][0], D[1][0], P[1][1], D[1][1] = 1.0, ct, -st, st, ct for n in range(2, NMAX + 1): k = math.sqrt((2.0 * n - 1.0) / (2.0 * n)) P[n][n] = k * st * P[n - 1][n - 1] D[n][n] = k * (ct * P[n - 1][n - 1] + st * D[n - 1][n - 1]) for m in range(n): a2 = math.sqrt((n - 1.0) ** 2 - m * m) if n - 1 >= m else 0.0 den = math.sqrt(n * n - m * m) P2 = P[n - 2][m] if n - 2 >= m else 0.0 D2 = D[n - 2][m] if n - 2 >= m else 0.0 P[n][m] = ((2.0 * n - 1.0) * ct * P[n - 1][m] - a2 * P2) / den D[n][m] = ((2.0 * n - 1.0) * (ct * D[n - 1][m] - st * P[n - 1][m]) - a2 * D2) / den return P, D def field(g, h, lat, lon, hkm=0.0): """X (north), Y (east), Z (down) in nT at a geodetic point.""" r, phic, delta = geodetic_to_geocentric(lat, hkm) theta = math.pi / 2.0 - phic st = math.sin(theta) P, D = legendre(theta) lam = math.radians(lon) br = bt = bp = 0.0 for n in range(1, NMAX + 1): f = (A_REF / r) ** (n + 2) for m in range(0, n + 1): c, s = math.cos(m * lam), math.sin(m * lam) gnm, hnm = g[n][m], h[n][m] br += (n + 1) * f * (gnm * c + hnm * s) * P[n][m] bt -= f * (gnm * c + hnm * s) * D[n][m] bp -= m * f * (-gnm * s + hnm * c) * P[n][m] bp /= st xc, zc = -bt, -br cd, sd = math.cos(delta), math.sin(delta) return xc * cd + zc * sd, bp, zc * cd - xc * sd def elements(X, Y, Z): H = math.hypot(X, Y) F = math.sqrt(X * X + Y * Y + Z * Z) return {"F_nT": F, "H_nT": H, "I_deg": math.degrees(math.atan2(Z, H)), "D_deg": math.degrees(math.atan2(Y, X)), "X_nT": X, "Y_nT": Y, "Z_nT": Z} def validate(zpath): epoch, g, h, gd, hd, tests = read_wmm(zpath) worst = {k: 0.0 for k in ("X", "Y", "Z", "F")} n = 0 for line in tests.splitlines(): if line.startswith("#") or not line.strip(): continue p = [float(x) for x in line.split()] t, hkm, lat, lon = p[0], p[1], p[2], p[3] gg = [[g[i][j] + (t - epoch) * gd[i][j] for j in range(NMAX + 1)] for i in range(NMAX + 1)] hh = [[h[i][j] + (t - epoch) * hd[i][j] for j in range(NMAX + 1)] for i in range(NMAX + 1)] X, Y, Z = field(gg, hh, lat, lon, hkm) F = math.sqrt(X * X + Y * Y + Z * Z) for key, mine, ref in (("X", X, p[4]), ("Y", Y, p[5]), ("Z", Z, p[6]), ("F", F, p[8])): worst[key] = max(worst[key], abs(mine - ref)) n += 1 return {"test_points": n, "largest_abs_difference_nT": {k: round(v, 4) for k, v in worst.items()}, "pass_within_1nT": all(v <= 1.0 for v in worst.values())} def contour_lat(gh, lon, target, lat0=10.0, lat1=40.0, step=0.01): """First latitude (south to north) where F crosses target, refined linearly between 0.01-degree steps.""" g, h = gh prev_lat, prev_F = None, None k = 0 while True: lat = round(lat0 + k * step, 6) if lat > lat1: return None F = elements(*field(g, h, lat, lon))["F_nT"] if prev_F is not None and (prev_F - target) * (F - target) <= 0: return prev_lat + (target - prev_F) / (F - prev_F) * (lat - prev_lat) prev_lat, prev_F = lat, F k += 1 def main(): igrf_path, wmm_path, out_path = sys.argv[1], sys.argv[2], sys.argv[3] out = {"inputs": {"igrf14coeffs.txt": sha256(igrf_path), "WMM2025COF.zip": sha256(wmm_path)}} if out["inputs"]["igrf14coeffs.txt"] != IGRF_SHA256: sys.exit("IGRF file hash differs from the rules; stopping.") if out["inputs"]["WMM2025COF.zip"] != WMM_SHA256: sys.exit("WMM file hash differs from the rules; stopping.") out["wmm2025_check"] = v = validate(wmm_path) print("WMM2025 check:", json.dumps(v)) if not v["pass_within_1nT"]: sys.exit("Synthesis check failed; stopping before any route value.") epochs, main_c, sv = read_igrf(igrf_path) models = {t: igrf_at(epochs, main_c, sv, t) for t in sorted(set(DATES + EPOCHS_5Y))} sites = [] for name, lat, lon, role in SITES: rec = {"site": name, "lat": round(lat, 4), "lon": round(lon, 4), "role": role, "height_km": 0.0, "by_date": {}} for t in DATES: e = elements(*field(*models[t], lat, lon)) rec["by_date"][str(t)] = {k: round(val, 4) for k, val in e.items()} series = [(t, elements(*field(*models[t], lat, lon))["F_nT"]) for t in EPOCHS_5Y] F1900 = series[0][1] rec["dF_2025_minus_1900_nT"] = round(series[-1][1] - F1900, 1) rec["max_abs_dev_from_1900_nT"] = round(max(abs(F - F1900) for _, F in series), 1) rec["F_5yr_series_nT"] = [[t, round(F, 1)] for t, F in series] sites.append(rec) if name in ("Zhanjiang", "Nanjing"): rec15 = {"site": name, "lat": round(lat, 4), "lon": round(lon, 4), "role": "context", "height_km": 1.5, "by_date": {}} for t in DATES: e = elements(*field(*models[t], lat, lon, 1.5)) rec15["by_date"][str(t)] = {k: round(val, 4) for k, val in e.items()} sites.append(rec15) out["sites"] = sites # decision quantities prim = [s for s in sites if s["role"] == "primary" and s["height_km"] == 0.0] F25 = {s["site"]: s["by_date"]["2025.0"]["F_nT"] for s in prim} I25 = {s["site"]: s["by_date"]["2025.0"]["I_deg"] for s in prim} fmin, fmax = min(F25.values()), max(F25.values()) out["decisions"] = { "a_Nanjing_F2025_minus_50000": round(F25["Nanjing"] - 50000, 1), "a_pass": abs(F25["Nanjing"] - 50000) <= 1000, "b_Zhanjiang_F2025_minus_45000": round(F25["Zhanjiang"] - 45000, 1), "b_pass": abs(F25["Zhanjiang"] - 45000) <= 1000, "c_route_min_F2025": round(fmin, 1), "c_route_min_site": min(F25, key=F25.get), "c_route_max_F2025": round(fmax, 1), "c_route_max_site": max(F25, key=F25.get), "c_pass": (fmin - 1000 <= 45000 <= fmax + 1000) and (fmin - 1000 <= 50000 <= fmax + 1000), "c_fraction_of_span_covered_by_45_50": round( max(0.0, min(50000, fmax) - max(45000, fmin)) / (fmax - fmin), 3) if fmax > fmin else None, "c_sites_outside_45_50": sorted([k for k, f in F25.items() if f < 45000 or f > 50000]), "d_I_Nanjing_minus_I_Zhanjiang_deg": round(I25["Nanjing"] - I25["Zhanjiang"], 2), "e_max_abs_dF_since_1900_nT": max(abs(s["dF_2025_minus_1900_nT"]) for s in prim), "e_max_abs_dev_any_epoch_nT": max(s["max_abs_dev_from_1900_nT"] for s in prim), "e_century_change_smaller_than_5000nT": max(s["max_abs_dev_from_1900_nT"] for s in prim) < 5000, } cont = {} for lon_name, lon in (("Zhanjiang_meridian_110.3531E", SITES[2][2]), ("Nanjing_meridian_118.7778E", SITES[7][2])): for target in (45000.0, 50000.0): for t in (1900.0, 2025.0): cont[lon_name + "_" + str(int(target)) + "nT_" + str(t)] = contour_lat(models[t], lon, target) for target in (45000.0, 50000.0): a = cont[lon_name + "_" + str(int(target)) + "nT_1900.0"] b = cont[lon_name + "_" + str(int(target)) + "nT_2025.0"] if a is not None and b is not None: cont[lon_name + "_" + str(int(target)) + "nT_shift_deg"] = round(b - a, 3) cont[lon_name + "_" + str(int(target)) + "nT_shift_km"] = round((b - a) * 111.2, 0) out["contours"] = {k: (round(v, 3) if isinstance(v, float) else v) for k, v in cont.items()} with open(out_path, "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=1) # printed summary print("site, height, F/I/D at 1900 and 2025, dF, max dev") for s in sites: a, b = s["by_date"]["1900.0"], s["by_date"]["2025.0"] print("%-10s %4.1f km 1900: F %8.0f I %6.2f D %6.2f | 2025: F %8.0f I %6.2f D %6.2f | 2026: F %8.0f | dF %s maxdev %s" % ( s["site"], s["height_km"], a["F_nT"], a["I_deg"], a["D_deg"], b["F_nT"], b["I_deg"], b["D_deg"], s["by_date"]["2026.0"]["F_nT"], s.get("dF_2025_minus_1900_nT", "-"), s.get("max_abs_dev_from_1900_nT", "-"))) print(json.dumps(out["decisions"], indent=1)) print(json.dumps(out["contours"], indent=1)) if __name__ == "__main__": main()