"""igrf_tilt.py -- RULES_igrf_tilt.txt. Standard library only. python3 -I igrf_tilt.py Dipole moment, D in the paper's units, dipole angle from the rotation axis and the boreal geomagnetic pole for 1840 (gufm1), 1900 and 2025 (IGRF-14) and 2026.88 (IGRF-14 + SV); the GSM dipole tilt every 10 minutes through 1900 and 2025, by two implementations; and a rough reading of the paper's Figs. 4 and 5 for those changes. """ import csv import datetime as dt import hashlib import json import math import os import sys igrf_path, gufm_path, dig_path, rules_path, out_dir = sys.argv[1:6] A_M = 6371.2e3 B_REF_NT = 31100.0 # the paper's equatorial surface field, 3.11e-5 T D2R = math.pi / 180 def sha(p): with open(p, "rb") as f: return hashlib.sha256(f.read()).hexdigest() # ---------------------------------------------------------------- IGRF-14 def read_igrf(path): cols, tab = None, {} with open(path, encoding="utf-8") as f: for ln in f: p = ln.split() if p[:3] == ["g/h", "n", "m"]: cols = p elif cols and len(p) == len(cols) and p[0] in ("g", "h"): key = (p[0], int(p[1]), int(p[2])) tab[key] = {c: float(v) for c, v in zip(cols[3:], p[3:])} return cols[3:], tab epochs, IG = read_igrf(igrf_path) def igrf_deg1(t): """g10, g11, h11 (nT) at decimal year t: linear between 5-year epochs; after 2025 with the SV column.""" keys = [("g", 1, 0), ("g", 1, 1), ("h", 1, 1)] ep = [float(e) for e in epochs if not e.startswith("2025-")] sv = [e for e in epochs if e.startswith("2025-")][0] out = [] for k in keys: if t >= 2025.0: out.append(IG[k]["2025.0"] + IG[k][sv] * (t - 2025.0)) else: i = max(j for j in range(len(ep)) if ep[j] <= t) t0, t1 = ep[i], ep[i + 1] v0, v1 = IG[k]["%.1f" % t0], IG[k]["%.1f" % t1] out.append(v0 + (v1 - v0) * (t - t0) / (t1 - t0)) return tuple(out) # ---------------------------------------------------------------- gufm1 (pymagglobal layout) def read_gufm1(path): with open(path, encoding="utf-8") as f: lines = f.read().split("\n") vals = [] for tok in " ".join(lines[1:]).replace("D", "E").split(): try: vals.append(float(tok)) except ValueError: pass lmax, nspl = int(vals[0]), int(vals[2]) knots = vals[3:3 + nspl + 4] n = lmax * (lmax + 2) coefs = vals[3 + nspl + 4:3 + nspl + 4 + nspl * n] return lmax, nspl, knots, [coefs[j * n:(j + 1) * n] for j in range(nspl)] def bspline_basis(knots, nspl, t, k=4): """Cox-de Boor recursion for order-k B-splines on the knot vector.""" m = len(knots) - 1 B = [1.0 if knots[i] <= t < knots[i + 1] else 0.0 for i in range(m)] for kk in range(2, k + 1): nb = [] for i in range(m - kk + 1): v = 0.0 if knots[i + kk - 1] > knots[i]: v += (t - knots[i]) / (knots[i + kk - 1] - knots[i]) * B[i] if knots[i + kk] > knots[i + 1]: v += (knots[i + kk] - t) / (knots[i + kk] - knots[i + 1]) * B[i + 1] nb.append(v) B = nb return B[:nspl] GL, GN, GK, GC = read_gufm1(gufm_path) def gufm1_deg1(t): b = bspline_basis(GK, GN, t) return tuple(sum(w * GC[j][q] for j, w in enumerate(b)) for q in range(3)) # ---------------------------------------------------------------- dipole quantities def dipole(g10, g11, h11): B0 = math.sqrt(g10 ** 2 + g11 ** 2 + h11 ** 2) M = 1e7 * A_M ** 3 * B0 * 1e-9 theta = math.degrees(math.acos(abs(g10) / B0)) lat = math.degrees(math.asin(-g10 / B0)) # boreal pole: direction (-g11, -h11, -g10)/B0 lon = math.degrees(math.atan2(-h11, -g11)) return {"g10": g10, "g11": g11, "h11": h11, "B0_nT": B0, "M_1e22_Am2": M / 1e22, "D_paper": B0 / B_REF_NT, "angle_from_rotation_axis_deg": theta, "boreal_pole_lat": lat, "boreal_pole_lon": lon} # ---------------------------------------------------------------- Sun and sidereal time (USNO) def jd(t): """Julian date of a UTC datetime (UT1 ~ UTC is ample here).""" a = (14 - t.month) // 12 y = t.year + 4800 - a m = t.month + 12 * a - 3 jdn = t.day + (153 * m + 2) // 5 + 365 * y + y // 4 - y // 100 + y // 400 - 32045 return jdn - 0.5 + (t.hour + t.minute / 60 + t.second / 3600) / 24 def sun(D): g = (357.529 + 0.98560028 * D) % 360 q = (280.459 + 0.98564736 * D) % 360 L = (q + 1.915 * math.sin(g * D2R) + 0.020 * math.sin(2 * g * D2R)) % 360 e = 23.439 - 0.00000036 * D ra = math.degrees(math.atan2(math.cos(e * D2R) * math.sin(L * D2R), math.cos(L * D2R))) % 360 dec = math.degrees(math.asin(math.sin(e * D2R) * math.sin(L * D2R))) return L, e, ra, dec def gmst_deg(t): j = jd(t) j0 = math.floor(j - 0.5) + 0.5 H = (j - j0) * 24 Dut = j0 - 2451545.0 T = (j - 2451545.0) / 36525 return ((6.697375 + 0.065709824279 * Dut + 1.0027379 * H + 0.0000258 * T * T) % 24) * 15 def tilt_two_ways(t, g10, g11, h11): B0 = math.sqrt(g10 ** 2 + g11 ** 2 + h11 ** 2) mx, my, mz = -g11 / B0, -h11 / B0, -g10 / B0 # boreal dipole axis, GEO D = jd(t) - 2451545.0 L, e, ra, dec = sun(D) th = gmst_deg(t) * D2R # 1: dot product in GEI with the Sun's RA/Dec lat = math.asin(mz) lon = math.atan2(my, mx) + th m1 = (math.cos(lat) * math.cos(lon), math.cos(lat) * math.sin(lon), math.sin(lat)) s1 = (math.cos(dec * D2R) * math.cos(ra * D2R), math.cos(dec * D2R) * math.sin(ra * D2R), math.sin(dec * D2R)) psi1 = math.degrees(math.asin(sum(a * b for a, b in zip(m1, s1)))) # 2: GEO -> GEI (rotation by GMST) -> ecliptic (obliquity) -> GSE (Sun's ecliptic longitude); Hapgood's tilt xg = mx * math.cos(th) - my * math.sin(th) yg = mx * math.sin(th) + my * math.cos(th) zg = mz ce, se = math.cos(e * D2R), math.sin(e * D2R) xe, ye, ze = xg, yg * ce + zg * se, -yg * se + zg * ce cl, sl = math.cos(L * D2R), math.sin(L * D2R) xs, ys, zs = xe * cl + ye * sl, -xe * sl + ye * cl, ze psi2 = math.degrees(math.atan2(xs, math.sqrt(ys * ys + zs * zs))) return psi1, psi2 def year_samples(year, coeff_fn): t = dt.datetime(year, 1, 1) end = dt.datetime(year + 1, 1, 1) step = dt.timedelta(minutes=10) out = [] while t < end: frac = year + (t - dt.datetime(year, 1, 1)).total_seconds() / (end - dt.datetime(year, 1, 1)).total_seconds() g10, g11, h11 = coeff_fn(frac) p1, p2 = tilt_two_ways(t, g10, g11, h11) out.append((t, p1, p2)) t += step return out def stats(samples): p = [s[1] for s in samples] maxdiff = max(abs(s[1] - s[2]) for s in samples) days = {} for t, p1, _ in samples: days.setdefault(t.date(), []).append(p1) daily = [(d, min(v), max(v), sum(v) / len(v), max(v) - min(v)) for d, v in sorted(days.items())] imax = max(range(len(p)), key=lambda i: p[i]) imin = min(range(len(p)), key=lambda i: p[i]) n = len(p) return { "n_samples": n, "max_impl_difference_deg": maxdiff, "psi_max_deg": p[imax], "psi_max_time": samples[imax][0].isoformat(), "psi_min_deg": p[imin], "psi_min_time": samples[imin][0].isoformat(), "mean_abs_psi_deg": sum(abs(x) for x in p) / n, "share_abs_le_10": sum(abs(x) <= 10 for x in p) / n, "share_abs_le_20": sum(abs(x) <= 20 for x in p) / n, "share_abs_le_30": sum(abs(x) <= 30 for x in p) / n, "daily_range_max_deg": max(d[4] for d in daily), "daily_range_min_deg": min(d[4] for d in daily), "daily_range_mean_deg": sum(d[4] for d in daily) / len(daily), }, daily # ---------------------------------------------------------------- rough reading of Figs 4 and 5 dig = json.load(open(dig_path, encoding="utf-8")) f4 = {r["nominal"]: r["y_mean"] for r in dig["points"]["fig4"]} f5 = sorted([(round(r["x_A"] / 30) * 30, r["y_mean"]) for r in dig["points"]["fig5"]]) s_lo = math.log10(f4["D=1"] / f4["D=0.1"]) # dlog rate / dlog D on 0.1-1 (negative) s_hi = math.log10(f4["D=10"] / f4["D=1"]) # on 1-10 s_f6 = dig["derived"]["log_slope_fig6_tilt30_0.7D_to_1D"] def rate_D(D, s_below=None, s_above=None): s_below = s_lo if s_below is None else s_below s_above = s_hi if s_above is None else s_above s = s_below if D < 1 else s_above return f4["D=1"] * 10 ** (s * math.log10(D)) def rate_tilt(a): a = abs(a) for (x0, y0), (x1, y1) in zip(f5[:-1], f5[1:]): if x0 <= a <= x1: return 10 ** (math.log10(y0) + (math.log10(y1) - math.log10(y0)) * (a - x0) / (x1 - x0)) raise ValueError(a) def main(): res = {"inputs_sha256": {os.path.basename(igrf_path): sha(igrf_path), os.path.basename(gufm_path): sha(gufm_path), os.path.basename(dig_path): sha(dig_path), os.path.basename(rules_path): sha(rules_path)}} ref_M = 1e7 * A_M ** 3 * B_REF_NT * 1e-9 res["paper_reference"] = {"B_eq_T": 3.11e-5, "M_1e22_Am2_from_B": ref_M / 1e22, "paper_says": "~8e22 A m^2"} ep = {"1840.0 (gufm1)": dipole(*gufm1_deg1(1840.0)), "1900.0 (gufm1)": dipole(*gufm1_deg1(1900.0)), "1990.0 (gufm1)": dipole(*gufm1_deg1(1990.0)), "1900.0 (IGRF-14)": dipole(*igrf_deg1(1900.0)), "1990.0 (IGRF-14)": dipole(*igrf_deg1(1990.0)), "2025.0 (IGRF-14)": dipole(*igrf_deg1(2025.0)), "2026.88 (IGRF-14 + SV)": dipole(*igrf_deg1(2026.88))} # the year the dipole matched the paper's reference (IGRF-14, linear between epochs) t, found = 1900.0, None while t <= 2030.0: if dipole(*igrf_deg1(t))["B0_nT"] <= B_REF_NT: found = t break t += 0.01 res["epochs"] = ep res["year_dipole_fell_to_paper_reference"] = found M = {k: v["M_1e22_Am2"] for k, v in ep.items()} res["changes"] = { "M 2025 vs 1840 (%)": 100 * (M["2025.0 (IGRF-14)"] / M["1840.0 (gufm1)"] - 1), "M 2025 vs 1900 IGRF (%)": 100 * (M["2025.0 (IGRF-14)"] / M["1900.0 (IGRF-14)"] - 1), "M 2026.88 vs 1840 (%)": 100 * (M["2026.88 (IGRF-14 + SV)"] / M["1840.0 (gufm1)"] - 1), "gufm1 vs IGRF-14 at 1900, M (%)": 100 * (M["1900.0 (gufm1)"] / M["1900.0 (IGRF-14)"] - 1), "site check: gufm1 M 1840 vs /dipole-before-1840/ 8.4964": M["1840.0 (gufm1)"] - 8.4964, "site check: gufm1 M 1900 vs /dipole-before-1840/ 8.3091": M["1900.0 (gufm1)"] - 8.3091, } # rough reading A (moment) Dv = {k: v["D_paper"] for k, v in ep.items()} rr = {} for label, (a, b) in {"1840->2025": ("1840.0 (gufm1)", "2025.0 (IGRF-14)"), "1900->2025": ("1900.0 (IGRF-14)", "2025.0 (IGRF-14)"), "1840->2026.88": ("1840.0 (gufm1)", "2026.88 (IGRF-14 + SV)")}.items(): rr[label] = {"D_from": Dv[a], "D_to": Dv[b], "ratio_piecewise_fig4": rate_D(Dv[b]) / rate_D(Dv[a]), "ratio_slope_0.1-1_throughout": rate_D(Dv[b], s_lo, s_lo) / rate_D(Dv[a], s_lo, s_lo), "ratio_slope_1-10_throughout": rate_D(Dv[b], s_hi, s_hi) / rate_D(Dv[a], s_hi, s_hi), "ratio_slope_fig6_30deg": rate_D(Dv[b], s_f6, s_f6) / rate_D(Dv[a], s_f6, s_f6)} res["rough_reading_moment"] = {"slopes": {"fig4 0.1-1": s_lo, "fig4 1-10": s_hi, "fig6 30deg 0.7-1D": s_f6}, "ratios": rr, "note": "Fig. 4 has no run between D = 0.1 and 1 or between 1 and 10 at 0 deg tilt; " "Fig. 6 has 0.7D at 30 deg and 0.4D at 60 deg, confounded with tilt. " "Power-law interpolation is ours, not the paper's."} # tilt tilts = {} for year, fn in ((2025, igrf_deg1), (1900, igrf_deg1)): samples = year_samples(year, fn) st, daily = stats(samples) g10, g11, h11 = fn(year + 0.5) st["expected_extreme_23.44_plus_theta_d"] = 23.44 + dipole(g10, g11, h11)["angle_from_rotation_axis_deg"] st["expected_daily_swing_2theta_d"] = 2 * dipole(g10, g11, h11)["angle_from_rotation_axis_deg"] rates = [rate_tilt(s[1]) for s in samples] st["rough_mean_rate_fig5"] = sum(rates) / len(rates) day_rates = {} for (t, p1, _), r in zip(samples, rates): day_rates.setdefault(t.date(), []).append(r) dm = [sum(v) / len(v) for v in day_rates.values()] st["rough_daily_mean_rate_max_over_min"] = max(dm) / min(dm) st["rough_rate_at_abs_psi_max_over_at_0"] = rate_tilt(max(abs(st["psi_max_deg"]), abs(st["psi_min_deg"]))) / rate_tilt(0) tilts[str(year)] = st with open(os.path.join(out_dir, "tilt_daily_%d.csv" % year), "w", encoding="utf-8", newline="\n") as f: f.write("# GSM dipole tilt (deg), every 10 min, by UT day; IGRF-14 dipole; USNO solar formulas. " "Fact-Checked Science.\n") w = csv.writer(f, lineterminator="\n") w.writerow(["date", "psi_min_deg", "psi_max_deg", "psi_mean_deg", "daily_range_deg"]) for d, lo, hi, mean, rng in daily: w.writerow([d.isoformat(), "%.2f" % lo, "%.2f" % hi, "%.2f" % mean, "%.2f" % rng]) res["gsm_tilt"] = tilts res["rough_reading_tilt"] = { "mean_rate_ratio_1900_over_2025": tilts["1900"]["rough_mean_rate_fig5"] / tilts["2025"]["rough_mean_rate_fig5"], "note": "Fig. 5 interpolated log-linearly in tilt between its 30-degree points; |psi| used (the paper does not " "say whether its tilts lean toward or away from the Sun); fixed solar wind and IMF."} res["rough_reading_combined_1900_to_2025"] = (rr["1900->2025"]["ratio_piecewise_fig4"] / res["rough_reading_tilt"]["mean_rate_ratio_1900_over_2025"]) with open(os.path.join(out_dir, "igrf_tilt.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(res, f, indent=1, default=str) with open(os.path.join(out_dir, "igrf_tilt_log.txt"), "w", encoding="utf-8", newline="\n") as f: f.write(json.dumps(res, indent=1, default=str) + "\n") print(json.dumps(res, indent=1, default=str)) main()