"""Pre-registered analysis (code/RULES_model_rates.txt): weakening rates of the axial dipole |g10| and the dipole moment over 1590-1840 and 1840-1990 in open historical and archaeomagnetic field models, the checks K1-K5, the comparisons C1-C4 and the directional context D1-D3. Reads the model files as data (never executes anything from them). Needs numpy and scipy. Run: py -3.12 -I code/model_rates.py Fact-Checked Science, 2026-11-09. """ import json import math import os import sys import numpy as np from scipy.optimize import least_squares A_KM = 6371.2 # reference radius of the models (km) R_KM = 6371.0 # radius for great-circle distances (km) NT_TO_M22 = 1e7 * (A_KM * 1e3) ** 3 * 1e-9 / 1e22 # |g| in nT -> dipole moment in 1e22 A m^2 # ---------------------------------------------------------------- readers def numbers(text): out = [] for tok in text.replace('D', 'E').replace('d', 'e').split(): try: out.append(float(tok)) except ValueError: pass return out class SplineModel: """Cubic B-spline (order 4) Gauss-coefficient model, coefficients per spline g10, g11, h11, ...""" def __init__(self, name, lmax, nspl, knots, coefs, span, order=4): n = lmax * (lmax + 2) assert len(knots) == nspl + order, (name, len(knots), nspl) assert len(coefs) == nspl * n, (name, len(coefs), nspl * n) self.name, self.lmax, self.nspl, self.k = name, lmax, nspl, order self.U = np.array(knots, dtype=float) self.C = np.array(coefs, dtype=float).reshape(nspl, n) self.t0, self.t1 = span def basis(self, t): U, k, nspl = self.U, self.k, self.nspl if not (U[k - 1] - 1e-9 <= t <= U[nspl] + 1e-9): raise ValueError('%s: t=%s outside %s-%s' % (self.name, t, U[k - 1], U[nspl])) # order-1 basis on the full knot vector; the right end belongs to the last interval B = np.zeros(len(U) - 1) if t >= U[nspl]: B[nspl - 1] = 1.0 else: i = np.searchsorted(U, t, side='right') - 1 B[i] = 1.0 for kk in range(2, k + 1): Bn = np.zeros(len(U) - kk) for i in range(len(U) - kk): v = 0.0 d1 = U[i + kk - 1] - U[i] d2 = U[i + kk] - U[i + 1] if d1 > 0 and B[i]: v += (t - U[i]) / d1 * B[i] if d2 > 0 and B[i + 1]: v += (U[i + kk] - t) / d2 * B[i + 1] Bn[i] = v B = Bn return B[:nspl] def coeffs(self, t): return self.basis(t) @ self.C # flat array g10, g11, h11, g20, ... def read_gufm1_colorado(path): lines = open(path, encoding='ascii').read().split('\n') v = numbers('\n'.join(lines[1:])) lmax, nspl = int(v[0]), int(v[1]) knots = v[2:2 + nspl + 4] coefs = v[2 + nspl + 4:] return SplineModel('gufm1 (colorado.edu copy)', lmax, nspl, knots, coefs, (1590.0, 1990.0)) def read_korte_format(path, name): """gufm1/CALSxk format as described in pymagglobal's README: line 1 tstart tend (+ text); then lmax, unused, nspl, the nspl+4 knots and the coefficients.""" lines = open(path, encoding='ascii').read().split('\n') head = numbers(lines[0]) t0, t1 = head[0], head[1] v = numbers('\n'.join(lines[1:])) lmax, nspl = int(v[0]), int(v[2]) knots = v[3:3 + nspl + 4] coefs = v[3 + nspl + 4:] n = lmax * (lmax + 2) if len(coefs) == 2 * nspl * n: # arhimag1k: a second block of positive values (standard deviations of the 501-model # average); the mean coefficients are the first block, as a Fortran reader takes them coefs = coefs[:nspl * n] return SplineModel(name, lmax, nspl, knots, coefs, (t0, t1)) def read_covobs(path): lines = open(path, encoding='ascii').read().split('\n') head = lines[1].split() lmax, nspl, order = int(head[0]), int(head[1]), int(head[2]) knots = [float(x) for x in head[3:]] coefs = numbers('\n'.join(lines[2:])) return SplineModel('COV-OBS.x2', lmax, nspl, knots, coefs, (1840.0, 2020.0), order=order) def read_covobs_shc(path): """Tabulated COV-OBS.x2: comment lines, a header 'nmin nmax ntimes order step', a line of times, then rows 'n m c(t1) c(t2) ...' (negative m = h).""" rows = [ln for ln in open(path, encoding='ascii').read().split('\n') if ln.strip() and not ln.startswith('#')] hdr = [int(x) for x in rows[0].split()[:3]] ntimes = hdr[2] times = [float(x) for x in rows[1].split()] assert len(times) == ntimes tab = {} for ln in rows[2:]: p = ln.split() n, m = int(p[0]), int(p[1]) if n == 1: tab[(n, m)] = np.array([float(x) for x in p[2:]]) return np.array(times), tab def read_shadif(path): data = {} for ln in open(path, encoding='ascii'): p = ln.split() if len(p) < 5: continue t, n, m, g, h = (float(x) for x in p[:5]) if int(n) == 1: data.setdefault(t, {})[(int(m))] = (g * 1000.0, h * 1000.0) out = {} for t, d in data.items(): out[t] = (d[0][0], d[1][0], d[1][1]) # g10, g11, h11 in nT return out def read_dm(path): out = {} for ln in open(path, encoding='ascii'): p = ln.split() if len(p) >= 2: out[int(float(p[0]))] = float(p[1]) return out # ---------------------------------------------------------------- helpers def dipole(g10, g11, h11): m = math.sqrt(g10 * g10 + g11 * g11 + h11 * h11) return abs(g10), m * NT_TO_M22 def ols_slope(t, y): t = np.asarray(t, float) y = np.asarray(y, float) tm = t.mean() return float(((t - tm) * (y - y.mean())).sum() / ((t - tm) ** 2).sum()) def series(model_eval, years): rows = [] for t in years: g10, g11, h11 = model_eval(t) A, M = dipole(g10, g11, h11) rows.append((t, g10, g11, h11, A, M)) return rows def rates(rows, w0, w1): sel = [r for r in rows if w0 - 1e-9 <= r[0] <= w1 + 1e-9] if len(sel) < 3: return None t = [r[0] for r in sel] A = [r[4] for r in sel] M = [r[5] for r in sel] first, last = sel[0], sel[-1] m_ref = first[5] return { 'window': [first[0], last[0]], 'n_epochs': len(sel), 'A_weakening_OLS_nT_per_yr': round(-ols_slope(t, A), 3), 'A_weakening_endpoint_nT_per_yr': round((first[4] - last[4]) / (last[0] - first[0]), 3), 'M_weakening_OLS_1e22_per_century': round(-100 * ols_slope(t, M), 4), 'M_weakening_OLS_pct_per_century_of_start': round(-100 * ols_slope(t, M) / m_ref * 100, 3), } # ---------------------------------------------------------------- field evaluation (gufm1 directions) def legendre_schmidt(theta, nmax): """Schmidt semi-normalised P_n^m(cos theta) and dP/dtheta, n <= nmax.""" c, s = math.cos(theta), math.sin(theta) P = np.zeros((nmax + 1, nmax + 1)) dP = np.zeros((nmax + 1, nmax + 1)) P[0, 0] = 1.0 for n in range(1, nmax + 1): for m in range(0, n + 1): if n == m: f = math.sqrt((2 * n - 1) / (2 * n)) if n > 1 else 1.0 P[n, m] = f * s * P[n - 1, m - 1] dP[n, m] = f * (c * P[n - 1, m - 1] + s * dP[n - 1, m - 1]) 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 else 0.0 P[n, m] = k1 * c * P[n - 1, m] - (k2 * P[n - 2, m] if n > 1 else 0.0) dP[n, m] = k1 * (c * dP[n - 1, m] - s * P[n - 1, m]) - (k2 * dP[n - 2, m] if n > 1 else 0.0) return P, dP def unflatten(flat, lmax): g = np.zeros((lmax + 1, lmax + 1)) h = np.zeros((lmax + 1, lmax + 1)) k = 0 for n in range(1, lmax + 1): g[n, 0] = flat[k]; k += 1 for m in range(1, n + 1): g[n, m] = flat[k]; h[n, m] = flat[k + 1]; k += 2 return g, h def xyz(g, h, lat, lon, lmax): """North, east, down components (nT) at radius a (spherical Earth).""" theta = math.radians(90.0 - lat) phi = math.radians(lon) P, dP = legendre_schmidt(theta, lmax) s = math.sin(theta) X = Y = Z = 0.0 for n in range(1, lmax + 1): for m in range(0, n + 1): cm, sm = math.cos(m * phi), math.sin(m * phi) gh = g[n, m] * cm + h[n, m] * sm X += gh * dP[n, m] if s > 1e-12: Y += m * (g[n, m] * sm - h[n, m] * cm) * P[n, m] / s Z -= (n + 1) * gh * P[n, m] return X, Y, Z def declination(g, h, lat, lon, lmax): X, Y, Z = xyz(g, h, lat, lon, lmax) return math.degrees(math.atan2(Y, X)) def dip_pole(g, h, lmax, guess): def res(p): X, Y, _ = xyz(g, h, p[0], p[1], lmax) return [X, Y] best = None for lat in np.arange(60.0, 89.6, 1.0): for lon in np.arange(-180.0, 180.0, 4.0): X, Y, _ = xyz(g, h, lat, lon, lmax) H = math.hypot(X, Y) if best is None or H < best[0]: best = (H, lat, lon) sol = least_squares(res, [best[1], best[2]], xtol=1e-12, ftol=1e-12, gtol=1e-12) X, Y, Z = xyz(g, h, sol.x[0], sol.x[1], lmax) lon = ((sol.x[1] + 180.0) % 360.0) - 180.0 return float(sol.x[0]), float(lon), float(math.hypot(X, Y)) def gc_km(lat1, lon1, lat2, lon2): p1, p2 = math.radians(lat1), math.radians(lat2) dl = math.radians(lon2 - lon1) c = math.sin(p1) * math.sin(p2) + math.cos(p1) * math.cos(p2) * math.cos(dl) return R_KM * math.acos(max(-1.0, min(1.0, c))) def geomag_pole(g10, g11, h11): m = math.sqrt(g10 * g10 + g11 * g11 + h11 * h11) lat = 90.0 - math.degrees(math.acos(-g10 / m)) lon = math.degrees(math.atan2(-h11, -g11)) return lat, lon # ---------------------------------------------------------------- main def main(): D, OUT = sys.argv[1], sys.argv[2] os.makedirs(OUT, exist_ok=True) p = lambda *a: os.path.join(D, *a) res = {'checks': {}, 'models': {}, 'comparisons': {}, 'directions': {}} guf = read_gufm1_colorado(p('gufm1', 'gufm1.txt')) guf2 = read_korte_format(p('pymagglobal-dat', 'gufm1'), 'gufm1 (pymagglobal copy)') cov = read_covobs(p('cov-obs-x2', 'COV-OBS.x2-int')) cals = [read_korte_format(p('erda-2207', 'extracted', 'CALS10k.2'), 'CALS10k.2 (ERDA)'), read_korte_format(p('gfz-models', 'extracted', 'CALS10k.2'), 'CALS10k.2 (GFZ)'), read_korte_format(p('pymagglobal-dat', 'CALS10k.2'), 'CALS10k.2 (pymagglobal)')] hfm = read_korte_format(p('erda-2207', 'extracted', 'HFM.OL1.A1'), 'HFM.OL1.A1') arch = read_korte_format(p('pymagglobal-dat', 'ARCH10k.1'), 'ARCH10k.1') pfm = read_korte_format(p('pymagglobal-dat', 'pfm9k.1a'), 'pfm9k.1a') arhi = read_korte_format(p('pymagglobal-dat', 'arhimag1k'), 'arhimag1k') sha = read_shadif(p('erda-1897', 'extracted', 'coeff_SHA.DIF.14k.dat')) dm = read_dm(p('gfz-models', 'extracted', 'DM_CALS10k_2.txt')) deg1 = lambda mdl: (lambda t: tuple(mdl.coeffs(float(t))[:3])) yrs_hist = list(range(1590, 1991)) # K1 gufm1 copies d = max(max(abs(a - b) for a, b in zip(deg1(guf)(t), deg1(guf2)(t))) for t in yrs_hist) res['checks']['K1_gufm1_copies_max_diff_nT'] = d res['checks']['K1_pass'] = d < 1e-6 # K2 CALS10k.2 copies d2 = 0.0 for t in yrs_hist: v = [deg1(m)(t) for m in cals] d2 = max(d2, max(abs(v[0][i] - v[j][i]) for j in (1, 2) for i in range(3))) res['checks']['K2_cals10k2_copies_max_diff_nT'] = d2 res['checks']['K2_pass'] = d2 < 1e-6 # K3 CALS10k.2 dipole moment vs GFZ DM file d3 = max(abs(dipole(*deg1(cals[0])(t))[1] - dm[t]) for t in yrs_hist) res['checks']['K3_cals10k2_DM_max_abs_diff_1e22'] = round(d3, 5) res['checks']['K3_pass'] = d3 < 0.006 # K4 COV-OBS.x2 splines vs tabulated times, tab = read_covobs_shc(p('cov-obs-x2', 'COV-OBS.x2-int.shc')) d4 = 0.0 for i, t in enumerate(times): if 1840.0 <= t <= 2020.0: g10, g11, h11 = deg1(cov)(t) d4 = max(d4, abs(g10 - tab[(1, 0)][i]), abs(g11 - tab[(1, 1)][i]), abs(h11 - tab[(1, -1)][i])) res['checks']['K4_covobs_spline_vs_shc_max_diff_nT'] = round(d4, 4) res['checks']['K4_pass'] = d4 < 0.5 # K5 1990 g10 against DGRF 1990 g90_guf, g90_cov = deg1(guf)(1990)[0], deg1(cov)(1990)[0] res['checks']['K5_g10_1990'] = {'gufm1': round(g90_guf, 1), 'COV-OBS.x2': round(g90_cov, 1), 'DGRF1990': -29775.0} res['checks']['K5_pass'] = abs(g90_guf + 29775) < 30 and abs(g90_cov + 29775) < 30 and abs(g90_guf - g90_cov) < 30 # model series specs = [ ('gufm1', deg1(guf), 1590, 1990, 'pre-1840 g10 imposed (15 nT/yr, Barraclough 1974); historical and modern data'), ('COV-OBS.x2', deg1(cov), 1840, 1990, 'instrumental data from 1840 (observatories, surveys, satellites)'), ('CALS10k.2', deg1(cals[0]), 1590, 1990, 'archaeo/volcanic + sediment; constrained to gufm1 1600-1990 "taking due account of the lack of intensity control prior to 1840"'), ('ARCH10k.1', deg1(arch), 1590, 1990, 'archaeo/volcanic only; recent centuries constrained to agree in general with gufm1; a construction tool'), ('HFM.OL1.A1', deg1(hfm), 1590, 1990, 'archaeo/volcanic + sediment; no gufm1 constraint'), ('pfm9k.1a', deg1(pfm), 1590, 1900, 'archaeo/volcanic + sediment; no gufm1 constraint; valid to 1900'), ('arhimag1k', deg1(arhi), 1590, 1990, 'historical + archaeo/volcanic data together; no constraint on g10 before 1840'), ] for name, ev, a, b, label in specs: rows = series(ev, list(range(a, b + 1))) res['models'][name] = { 'label': label, 'R1_1590_1840': rates(rows, 1590, 1840), 'R2_1840_1990' if b >= 1990 else 'R2_1840_1900': rates(rows, 1840, 1990 if b >= 1990 else 1900), 'R_1840_1900': rates(rows, 1840, 1900), 'values': {str(t): {'g10': round(r[1], 1), 'absg10': round(r[4], 1), 'M': round(r[5], 4)} for r in rows for t in [r[0]] if t in (1590, 1600, 1650, 1700, 1750, 1800, 1840, 1900, 1950, 1990)}, } if name == 'COV-OBS.x2': res['models'][name]['R_1840_1860'] = rates(rows, 1840, 1860) res['models'][name]['R_1840_2020'] = rates(series(ev, list(range(1840, 2021))), 1840, 2020) with open(os.path.join(OUT, 'series_%s.tsv' % name.replace('.', '_')), 'w', encoding='utf-8', newline='\n') as fh: fh.write('year\tg10_nT\tg11_nT\th11_nT\tabs_g10_nT\tM_1e22Am2\n') for r in rows: fh.write('%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.5f\n' % r) # SHA.DIF.14k at its own epochs ts = sorted(t for t in sha if 1590 <= t <= 1900) rows = [(t,) + sha[t] + dipole(*sha[t]) for t in ts] res['models']['SHA.DIF.14k'] = { 'label': 'archaeo/volcanic; constrained by gufm1 over the historical period (Troyano et al. 2021); tabulated epochs, to 1900', 'epochs_used': ts, 'R1_1590_1840': rates(rows, 1590, 1840), 'R2_1840_1900': rates(rows, 1840, 1900), 'values': {str(int(r[0])): {'g10': round(r[1], 1), 'absg10': round(r[4], 1), 'M': round(r[5], 4)} for r in rows}, } # C1 gufm1 imposed slope and end of the straight line g = np.array([deg1(guf)(t)[0] for t in range(1590, 1861)]) d2g = np.diff(g, 2) # second difference centred on 1591..1859 first_bend = None for i, v in enumerate(d2g): if abs(v) >= 0.01: first_bend = 1591 + i # centre year of the first second difference >= 0.01 nT/yr^2 break r1 = res['models']['gufm1']['R1_1590_1840']['A_weakening_OLS_nT_per_yr'] res['comparisons']['C1'] = {'gufm1_R1': r1, 'pass_|R1-15|<0.05': abs(r1 - 15) < 0.05, 'first_centre_year_second_difference_ge_0.01': first_bend, 'g10_slope_1590_1800_nT_per_yr': round(float(np.polyfit(range(1590, 1801), g[:211], 1)[0]), 4)} # C2 classes cls = {} for name, d in res['models'].items(): r = d.get('R1_1590_1840') if not r: continue v = r['A_weakening_OLS_nT_per_yr'] c = ('within Gubbins et al. 1-sigma range' if -0.44 <= v <= 5.0 else 'between' if 5.0 < v < 10.0 else 'near gufm1 15' if v >= 10.0 else 'growing') cls[name] = {'R1': v, 'class': c} res['comparisons']['C2'] = cls # C3 onset at start of data c3 = res['models']['COV-OBS.x2']['R_1840_1860']['A_weakening_OLS_nT_per_yr'] res['comparisons']['C3'] = {'COV-OBS.x2_R_1840_1860': c3, 'decline_under_way_at_start': c3 >= 10.0} # D1-D3 directional context from gufm1 sites = {'London': (51.5, -0.12), 'Cape Town': (-33.9, 18.4)} dec = {k: {} for k in sites} for t in range(1590, 1991, 10): gg, hh = unflatten(guf.coeffs(float(t)), guf.lmax) for k, (la, lo) in sites.items(): dec[k][t] = round(declination(gg, hh, la, lo, guf.lmax), 2) res['directions']['D1_declination_deg'] = dec res['directions']['D1_range_1590_1840'] = { k: [min(v for t, v in dec[k].items() if t <= 1840), max(v for t, v in dec[k].items() if t <= 1840)] for k in sites} poles, gm = {}, {} for t in (1590, 1650, 1700, 1750, 1800, 1840, 1900, 1950, 1990): f = guf.coeffs(float(t)) gg, hh = unflatten(f, guf.lmax) poles[t] = dip_pole(gg, hh, guf.lmax, None) gm[t] = geomag_pole(f[0], f[1], f[2]) res['directions']['D3_dip_pole_lat_lon_residualH'] = {str(t): [round(v[0], 3), round(v[1], 3), round(v[2], 4)] for t, v in poles.items()} res['directions']['D2_geomagnetic_pole_lat_lon'] = {str(t): [round(v[0], 3), round(v[1], 3)] for t, v in gm.items()} # mean speeds: sum of great-circle legs between the listed epochs within each window def path_speed(t_list): dist = sum(gc_km(poles[a][0], poles[a][1], poles[b][0], poles[b][1]) for a, b in zip(t_list, t_list[1:])) return round(dist, 1), round(dist / (t_list[-1] - t_list[0]), 2) # finer path for speeds: every 10 years fine = {} for t in range(1590, 1991, 10): gg, hh = unflatten(guf.coeffs(float(t)), guf.lmax) fine[t] = dip_pole(gg, hh, guf.lmax, None) def fine_speed(a, b): ts = list(range(a, b + 1, 10)) dist = sum(gc_km(fine[x][0], fine[x][1], fine[y][0], fine[y][1]) for x, y in zip(ts, ts[1:])) return {'path_km': round(dist, 1), 'mean_km_per_yr': round(dist / (b - a), 2), 'net_km': round(gc_km(fine[a][0], fine[a][1], fine[b][0], fine[b][1]), 1)} res['directions']['D3_dip_pole_speed_10yr_steps'] = {'1590-1840': fine_speed(1590, 1840), '1840-1990': fine_speed(1840, 1990)} res['directions']['D3_dip_pole_every_10yr'] = {str(t): [round(v[0], 3), round(v[1], 3)] for t, v in fine.items()} with open(os.path.join(OUT, 'model_rates.json'), 'w', encoding='utf-8', newline='\n') as fh: json.dump(res, fh, indent=1, ensure_ascii=False, default=lambda o: o.item() if hasattr(o, 'item') else str(o)) print(json.dumps({'checks': res['checks'], 'comparisons': res['comparisons']}, indent=1, default=lambda o: o.item() if hasattr(o, 'item') else str(o))) for name, d in res['models'].items(): r1 = d.get('R1_1590_1840') r2 = d.get('R2_1840_1990') or d.get('R2_1840_1900') print('%-12s R1 %s | R2 %s' % (name, r1 and (r1['A_weakening_OLS_nT_per_yr'], r1['A_weakening_endpoint_nT_per_yr'], r1['M_weakening_OLS_pct_per_century_of_start']), r2 and (r2['window'], r2['A_weakening_OLS_nT_per_yr'], r2['M_weakening_OLS_pct_per_century_of_start']))) if __name__ == '__main__': main()