#!/usr/bin/env python3 """Every number marked "Our analysis" on factchecked.science/ice-giant-dynamos/. Usage: python3 -I ice_giant_numbers.py [DATA_FOLDER] It needs Python 3.10 or later with numpy. It downloads what it lacks into DATA_FOLDER (default: a folder ice_giant_data beside this script), about 140 MB, reads everything as data, unpacks nothing and runs nothing from the deposit, and writes three files beside this script. It takes a few minutes once the files are there. ice-giant-numbers.json all the numbers ice-giant-end40-ecdf.csv the share of 40-year windows with a tilt change up to x degrees, for all 15 models ice-giant-chart-series.json Model 6's tilt and misfit around its Uranus-like interval, and the three surface-field maps WHAT IT READS. Yan et al. (2026), Communications Physics 9, 336, doi:10.1038/s42005-026-02841-y. CC BY 4.0. The authors' deposit, doi:10.6084/m9.figshare.32447910 (version 2, file 66837416, 140,098,077 bytes). CC BY 4.0. The deposit's analysis scripts are not run; what they do is re-implemented here. Its observed-field files are, in its words, transcriptions of published tables: Holme & Bloxham (1996), doi:10.1029/95JE03437; Herbert (2009), doi:10.1029/2009JA014394; Connerney et al. (1991), doi:10.1029/91JA01165. The paper's Supplementary Data 2 and 3 (Figures 3 and 4), CC BY 4.0. IGRF-14 (IAGA Working Group V-MOD), https://www.ngdc.noaa.gov/IAGA/vmod/coeffs/igrf14coeffs.txt THE RULES were written before any tilt-change statistic was computed: RERUN_RULES.txt, hosted beside this script, with its additions in the order they were made. Additions C1-C10 came from the fresh review of the page; the blocks are marked. DEFINITIONS. Tilt: atan2(sqrt(g11^2 + h11^2), g10), 0 to 180 degrees, with Schmidt quasi-normalised coefficients. Clock: the paper's. tau_lambda = mu_0 sigma D^2, D = (1 - chi) A R, tau_nu = tau_lambda / Pm, Pm = 5, sigma = 1e4 S/m. Uranus clock A = 0.7, R = 25,559 km. Neptune clock A = 0.8, R = 24,622 km. Window: 40 years, one starting at every snapshot. END is |tilt(t + W) - tilt(t)|, RANGE is max - min inside the window, AXIS is the angle between the dipole axis at t and at t + W. No window spans a gap in the record. "Like" stretches: misfit below 0.54 (Uranus, A = 0.7) or 0.68 (Neptune, A = 0.8), the paper's Fig. 4 and Supp. Fig. 9. THE SQUARE ROOT OF 2. The deposit's morphology, SV and Figures 3-4 scripts divide every m > 0 Gauss coefficient by sqrt(2) ("Remove MagIC's sqrt(2) normalization for m>0"; one script gives the aim as "standard (non-MagIC) Schmidt convention"). Its f_M1 and spectrum scripts do not. MagIC's getGauss, at the commit the paper names (8bdb98b), applies that factor to reach Schmidt form, and its dipole output agrees with the undivided values. "divided" below is the deposit's recipe, needed to reproduce its misfit series and the paper's Supplementary Tables 2 and 3; "true" is undivided. """ import csv import hashlib import json import math import os import re import struct import sys import urllib.request import xml.etree.ElementTree as ET import zipfile import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) UA = "factchecked-research/1.0" MU0 = 4.0e-7 * math.pi YEAR = 365.25 * 86400.0 R_U = 25_559e3 R_N = 24_622e3 PM = 5.0 SQ2 = math.sqrt(2.0) SEED = 20261104 ROOT = "Deposit_IceGiantDynamos/" ESM = "https://static-content.springer.com/esm/art%3A10.1038%2Fs42005-026-02841-y/MediaObjects/42005_2026_2841_" FILES = { "Deposit_IceGiantDynamos.zip": ("https://ndownloader.figshare.com/files/66837416", "41a7cc835ee56069ad8cf76dad84b428d659fb6af0149661ddb57fb20b91864f"), "MOESM5.xlsx": (ESM + "MOESM5_ESM.xlsx", "8aec079722055c8e795ea6d767963aa78189eb87c287ee0f16449dec6abab805"), "MOESM6.xlsx": (ESM + "MOESM6_ESM.xlsx", "aac9d83f3c7cf68b9e2e9555821c6861e8c2fb5e6288ad0dc69fe505a0449454"), "igrf14coeffs.txt": ("https://www.ngdc.noaa.gov/IAGA/vmod/coeffs/igrf14coeffs.txt", "8f8d88403028fc4ee92c4f38d97b46e0a87e2cfc496045b43c9e26c1d6b0903c"), } CHI = {0: 0.35, 1: 0.35, 2: 0.35, 3: 0.35, 4: 0.5, 5: 0.5, 6: 0.5, 7: 0.5, 8: 0.6, 9: 0.6, 10: 0.6, 11: 0.6, 12: 0.5, 13: 0.35, 14: 0.35} PUBLISHED_TAG = {0: ["5.0"], 1: ["1.1"], 2: ["3.2"], 3: ["1.3"], 4: ["2.4"], 5: ["1.5"], 6: ["4.6"], 7: ["1.7"], 8: ["2.8"], 9: ["1.9"], 10: ["3.10"], 11: ["1.11", "2.11"], 12: ["2.12"], 13: ["2.13"], 14: ["2.14"]} RANKED = [1, 2, 3, 5, 6, 7, 9, 10, 11] FAMILY = {5, 6, 7, 9, 10, 11} # medium and thin shells with varying conductivity CONTROLS = [0, 4, 8] TABLE2 = {0: (1389, 0.06, 4, 2, 0, 0, 0.08, 0, 0), 1: (741, 0.10, 101, 63, 4.1, 7.2, 0.5, 21.7, 37.1), 2: (647, 0.08, 114, 44, 13.5, 13.0, 1.9, 58.2, 72.7), 3: (470, 0.07, 93, 51, 14.4, 17.7, 0.5, 25.6, 46.2), 4: (694, 0.10, 8, 5, 0, 0, 0.12, 0, 0), 5: (393, 0.17, 107, 52, 9.3, 13.1, 1.4, 74.9, 71.8), 6: (278, 0.11, 87, 50, 13.0, 12.5, 3.2, 89.6, 89.7), 7: (275, 0.13, 79, 40, 16.9, 17.7, 1.5, 66.9, 56.7), 8: (1082, 0.22, 5, 2, 0, 0, 0.13, 0, 0), 9: (235, 0.24, 105, 47, 11.6, 8.8, 1.9, 82.6, 94.9), 10: (201, 0.20, 106, 36, 8.7, 8.0, 3.0, 91.4, 85.5), 11: (169, 0.18, 83, 40, 12.6, 12.6, 2.1, 78.1, 62.8), # Supplementary Table 5 12: (324, 0.08, 80, 47, 13.4, 14.5, 1.7, 72.2, 76.7), 13: (524, 0.086, 103, 55, 8.9, 10.3, 1.08, 59.5, 72.0), 14: (920, 0.144, 89, 56, 7.1, 7.9, 0.97, 53.2, 72.5)} TABLE2_ELSASSER = {0: 2.2, 1: 1.0e-2, 2: 1.9e-4, 3: 2.1e-4, 4: 5.0, 5: 1.5e-2, 6: 1.5e-4, 7: 4.3e-4, 8: 1.8, 9: 1.8e-2, 10: 1.8e-4, 11: 4.2e-4, 12: 2.1e-4, 13: 3.7e-3, 14: 2.0e-2} def r(x, n=3): return None if x is None else round(float(x), n) def tau_nu_years(model, A, R, sigma=1e4): D = (1.0 - CHI[model]) * A * R return MU0 * sigma * D * D / YEAR / PM # ------------------------------------------------------------------ fetching and reading def fetch(folder): os.makedirs(folder, exist_ok=True) for name, (url, sha) in FILES.items(): path = os.path.join(folder, name) if not os.path.exists(path): print("downloading", url) req = urllib.request.Request(url, headers={"User-Agent": UA}) try: with urllib.request.urlopen(req, timeout=600) as resp, open(path + ".part", "wb") as out: while True: b = resp.read(1 << 20) if not b: break out.write(b) except OSError as e: raise SystemExit(f"{name}: the download from {url} failed ({e}). Fetch that file by hand into {folder} and run this again; its SHA-256 is checked either way.") os.replace(path + ".part", path) if sha: h = hashlib.sha256() with open(path, "rb") as f: for b in iter(lambda: f.read(1 << 20), b""): h.update(b) if h.hexdigest() != sha: raise SystemExit(f"{name}: SHA-256 {h.hexdigest()} differs from the file this page used, {sha}") class Deposit: def __init__(self, path): self.z = zipfile.ZipFile(path) self.names = self.z.namelist() def tags(self, model): pre = f"{ROOT}models/Model{model:02d}/B_coeff_cmb." tags = [n[len(pre):] for n in self.names if n.startswith(pre)] return sorted(tags, key=lambda t: (int(t.split(".")[1]), int(t.split(".")[0]))) def bcoeff(self, model, tag): """Big-endian Fortran records: l_max, minc, n_data; then time and n_data doubles per snapshot.""" blob = self.z.read(f"{ROOT}models/Model{model:02d}/B_coeff_cmb.{tag}") l_max, minc, n_data = struct.unpack(">3i", blob[4:16]) pos = 20 step = (n_data + 1) * 8 + 8 n = (len(blob) - pos) // step data = np.empty((n, n_data + 1)) for k in range(n): data[k] = np.frombuffer(blob, dtype=">f8", count=n_data + 1, offset=pos + k * step + 4) return data[:, 0], data[:, 1:], l_max def text_rows(self, member): for line in self.z.read(ROOT + member).decode("utf-8", "replace").splitlines(): yield line def table(self, model, kind, tag, min_cols): rows = [] for line in self.text_rows(f"models/Model{model:02d}/{kind}.{tag}"): s = line.split() if len(s) >= min_cols: try: rows.append([float(x) for x in s[:min_cols]]) except ValueError: pass return np.array(rows) def morpho(self, model, A): rows = [] for line in self.text_rows(f"derived/Model{model:02d}_morpho_rms_A{A:g}.txt"): if line.startswith("#") or not line.strip(): continue rows.append([float(x) for x in line.split()]) return np.array(rows) def obs(self, name): member, col = {"U_HB96": ("observed_fields/Uranus_GC.txt", 1), "U_AH5": ("observed_fields/Uranus_GC.txt", 2), "N_HB96": ("observed_fields/Neptune_GC_O8_blockorder.txt", 1), "N_O8": ("observed_fields/Neptune_GC_O8_blockorder.txt", 2)}[name] vals = [float(line.split()[col]) for line in self.text_rows(member) if line.strip() and not line.startswith("#")] g, h = {}, {} lmax = int(math.isqrt(len(vals) + 1)) - 1 for l in range(1, lmax + 1): g[(l, 0)] = vals[l * l - 1] h[(l, 0)] = 0.0 for m in range(1, l + 1): g[(l, m)] = vals[l * l + m - 1] h[(l, m)] = vals[l * l + l + m - 1] return g, h def gauss(raw, l_file, lmax_out=6): """Schmidt coefficients at r_o, up to a constant factor. As MagIC's getGauss, without its constant factors: g_l0 = l c_l Re b_l0; g_lm = sqrt(2) l c_l Re b_lm; h_lm = -sqrt(2) l c_l Im b_lm; c_l = sqrt((2l+1)/(4 pi)).""" idx = {} pos = 0 for l in range(1, l_file + 1): idx[(l, 0)] = pos pos += 1 for m in range(1, l_file + 1): for l in range(m, l_file + 1): idx[(l, m)] = pos pos += 2 g, h = {}, {} for l in range(1, lmax_out + 1): c = l * math.sqrt((2 * l + 1) / (4.0 * math.pi)) g[(l, 0)] = c * raw[:, idx[(l, 0)]] h[(l, 0)] = np.zeros(raw.shape[0]) for m in range(1, l + 1): p = idx[(l, m)] g[(l, m)] = SQ2 * c * raw[:, p] h[(l, m)] = -SQ2 * c * raw[:, p + 1] return g, h class Series: def __init__(self, dep, model, tags=None): tags = tags or dep.tags(model) segs = [] for tag in tags: t, raw, l_file = dep.bcoeff(model, tag) g, h = gauss(raw, l_file) segs.append((t, g, h)) segs.sort(key=lambda s: s[0][0]) T, G, H = segs[0][0].copy(), {k: v.copy() for k, v in segs[0][1].items()}, {k: v.copy() for k, v in segs[0][2].items()} for t, g, h in segs[1:]: mask = t > T[-1] T = np.concatenate([T, t[mask]]) for k in G: G[k] = np.concatenate([G[k], g[k][mask]]) H[k] = np.concatenate([H[k], h[k][mask]]) keep = np.concatenate([[True], np.diff(T) > 0]) self.model = model self.t = T[keep] self.g = {k: v[keep] for k, v in G.items()} self.h = {k: v[keep] for k, v in H.items()} self.theta = tilt(self.g[(1, 0)], self.g[(1, 1)], self.h[(1, 1)]) self.dt = float(np.median(np.diff(self.t))) self.gaps = np.where(np.diff(self.t) > 5 * self.dt)[0] def span(self): edges = np.concatenate([[0], self.gaps + 1, [len(self.t)]]) return float(sum(self.t[b - 1] - self.t[a] for a, b in zip(edges[:-1], edges[1:]))) def at(self, x): return float(np.interp(x, self.t, self.theta)) def tilt(g10, g11, h11): return np.degrees(np.arctan2(np.sqrt(g11 * g11 + h11 * h11), g10)) def axis(g10, g11, h11): n = np.sqrt(g10 * g10 + g11 * g11 + h11 * h11) return np.stack((g11 / n, h11 / n, g10 / n), axis=-1) def divided(d): return {k: (v / SQ2 if k[1] > 0 else v) for k, v in d.items()} def wl(l): return (l + 1) ** 2 / (2 * l + 1) def misfit(g, h, A, go, ho, lmax=3, nphi=360): """Min over polarity and 360 azimuthal rotations of the rms difference of the two surface B_r fields, each normalised by its own rms to lmax. Both unit rms, so this is sqrt(2 - 2 max|C|), with C their correlation.""" n = len(g[(1, 0)]) robs = 0.0 for l in range(1, lmax + 1): robs += wl(l) * go[(l, 0)] ** 2 for m in range(1, l + 1): robs += wl(l) * (go[(l, m)] ** 2 + ho[(l, m)] ** 2) robs = math.sqrt(robs) phi = np.linspace(0.0, 2.0 * np.pi, nphi, endpoint=False) p2 = np.zeros(n) c0 = np.zeros(n) cc = {m: np.zeros(n) for m in range(1, lmax + 1)} ss = {m: np.zeros(n) for m in range(1, lmax + 1)} for l in range(1, lmax + 1): uc = A ** (l + 2) w = wl(l) p2 += w * (g[(l, 0)] * uc) ** 2 c0 += w * g[(l, 0)] * uc * go[(l, 0)] for m in range(1, l + 1): gm, hm = g[(l, m)] * uc, h[(l, m)] * uc p2 += w * (gm * gm + hm * hm) cc[m] += w * (gm * go[(l, m)] + hm * ho[(l, m)]) ss[m] += w * (hm * go[(l, m)] - gm * ho[(l, m)]) C = np.repeat(c0[:, None], nphi, axis=1) for m in range(1, lmax + 1): C += np.outer(cc[m], np.cos(m * phi)) + np.outer(ss[m], np.sin(m * phi)) C /= np.sqrt(p2)[:, None] * robs return np.sqrt(np.maximum(2.0 - 2.0 * np.max(np.abs(C), axis=1), 0.0)) def windows(s, W): t = s.t g10, g11, h11 = s.g[(1, 0)], s.g[(1, 1)], s.h[(1, 1)] th = s.theta n = len(t) j = np.searchsorted(t, t + W, side="right") - 1 gc = np.zeros(n, dtype=int) if len(s.gaps): gc[s.gaps + 1] = 1 gc = np.cumsum(gc) idx = np.where(t + W <= t[-1])[0] jj = j[idx] jn = np.minimum(jj + 1, n - 1) same = gc[idx] == gc[jn] idx, jj, jn = idx[same], jj[same], jn[same] fr = np.where(jn > jj, (t[idx] + W - t[jj]) / np.where(jn > jj, t[jn] - t[jj], 1.0), 0.0) a = g10[jj] + fr * (g10[jn] - g10[jj]) b = g11[jj] + fr * (g11[jn] - g11[jj]) c = h11[jj] + fr * (h11[jn] - h11[jj]) the = tilt(a, b, c) end = np.abs(the - th[idx]) ax = np.degrees(np.arccos(np.clip(np.sum(axis(g10[idx], g11[idx], h11[idx]) * axis(a, b, c), axis=1), -1, 1))) rng_ = np.empty(len(idx)) for k, (i0, j0) in enumerate(zip(idx, jj)): seg = th[i0:j0 + 1] rng_[k] = max(seg.max(), the[k]) - min(seg.min(), the[k]) return {"i": idx, "END": end, "RANGE": rng_, "AXIS": ax} def shares(v): return {"n": int(len(v)), "gt10": r(np.mean(v > 10), 4), "gt30": r(np.mean(v > 30), 4), "gt60": r(np.mean(v > 60), 4), "p5": r(np.percentile(v, 5), 2), "p25": r(np.percentile(v, 25), 2), "p50": r(np.percentile(v, 50), 2), "p75": r(np.percentile(v, 75), 2), "p95": r(np.percentile(v, 95), 2), "max": r(v.max(), 2)} if len(v) else {"n": 0} def block_ci(values, block, rng, ndraw=2000): n = len(values) block = max(1, min(block, n)) nb = int(math.ceil(n / block)) starts = rng.integers(0, n - block + 1, size=(ndraw, nb)) out = {} for th_ in (10, 30, 60): cs = np.concatenate([[0.0], np.cumsum((values > th_).astype(float))]) s = (cs[starts + block] - cs[starts]).sum(axis=1) / (nb * block) out[f"gt{th_}"] = [r(np.percentile(s, 2.5), 3), r(np.percentile(s, 97.5), 3)] return out def match(s, times): j = np.clip(np.searchsorted(s.t, times), 1, len(s.t) - 1) near = np.where(np.abs(s.t[j - 1] - times) <= np.abs(s.t[j] - times), j - 1, j) return near, np.abs(s.t[near] - times) < 2e-6 def episodes(times_yr, below): """Runs of below-threshold samples; runs closer than 40 years are merged.""" idx = np.where(below)[0] out = [] for k in idx: if out and times_yr[k] - times_yr[out[-1][-1]] < 40.0: out[-1].append(k) else: out.append([k]) return [np.array(e) for e in out] def read_xlsx(path): ns = {"m": "http://schemas.openxmlformats.org/spreadsheetml/2006/main", "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships"} out = {} with zipfile.ZipFile(path) as z: strings = [] if "xl/sharedStrings.xml" in z.namelist(): for si in ET.fromstring(z.read("xl/sharedStrings.xml")).findall("m:si", ns): strings.append("".join(t.text or "" for t in si.iter("{%s}t" % ns["m"]))) rels = {x.get("Id"): x.get("Target") for x in ET.fromstring(z.read("xl/_rels/workbook.xml.rels"))} for sh in ET.fromstring(z.read("xl/workbook.xml")).find("m:sheets", ns): target = rels[sh.get("{%s}id" % ns["r"])].lstrip("/") target = target if target.startswith("xl/") else "xl/" + target rows = [] for row in ET.fromstring(z.read(target)).iter("{%s}row" % ns["m"]): cells = {} for c in row.findall("m:c", ns): col = 0 for ch in re.match(r"[A-Z]+", c.get("r")).group(0): col = col * 26 + ord(ch) - 64 v = c.find("m:v", ns) if c.get("t") == "s" and v is not None: cells[col - 1] = strings[int(v.text)] elif c.get("t") == "inlineStr": cells[col - 1] = "".join(x.text or "" for x in c.iter("{%s}t" % ns["m"])) elif v is not None: try: cells[col - 1] = float(v.text) except ValueError: cells[col - 1] = v.text if cells: rows.append([cells.get(i) for i in range(max(cells) + 1)]) out[sh.get("name")] = rows return out def schmidt(lmax, c, s): P = np.zeros((lmax + 1, lmax + 1, len(c))) P[0, 0] = 1.0 P[1, 0] = c P[1, 1] = s for l in range(2, lmax + 1): P[l, l] = math.sqrt((2 * l - 1) / (2.0 * l)) * s * P[l - 1, l - 1] P[l, l - 1] = math.sqrt(2 * l - 1) * c * P[l - 1, l - 1] for m in range(0, l - 1): d = math.sqrt(float(l * l - m * m)) P[l, m] = (2 * l - 1) / d * c * P[l - 1, m] - math.sqrt(float((l - 1) * (l - 1) - m * m)) / d * P[l - 2, m] return P def br_spots(go, ho, lmax): th = np.radians(np.arange(0.5, 180.0, 1.0)) ph = np.radians(np.arange(0.5, 360.0, 1.0)) P = schmidt(lmax, np.cos(th), np.sin(th)) Br = np.zeros((len(th), len(ph))) for l in range(1, lmax + 1): Br += (l + 1) * go[(l, 0)] * P[l, 0][:, None] for m in range(1, l + 1): Br += (l + 1) * np.outer(P[l, m], go[(l, m)] * np.cos(m * ph) + ho[(l, m)] * np.sin(m * ph)) a = np.unravel_index(np.argmax(Br), Br.shape) b = np.unravel_index(np.argmin(Br), Br.shape) unit = lambda t_, p_: np.array([math.sin(t_) * math.cos(p_), math.sin(t_) * math.sin(p_), math.cos(t_)]) ua, ub = unit(th[a[0]], ph[a[1]]), unit(th[b[0]], ph[b[1]]) d = np.array([go[(1, 1)], ho[(1, 1)], go[(1, 0)]]) d /= np.linalg.norm(d) ang = lambda x, y: float(np.degrees(np.arccos(np.clip(x @ y, -1, 1)))) return {"out_lat": r(90 - np.degrees(th[a[0]]), 1), "out_lon": r(np.degrees(ph[a[1]]), 1), "in_lat": r(90 - np.degrees(th[b[0]]), 1), "in_lon": r(np.degrees(ph[b[1]]), 1), "out_to_in": r(ang(ua, ub), 1), "out_to_dipole_out_pole": r(ang(ua, d), 1), "in_to_dipole_in_pole": r(ang(ub, -d), 1)} def br_map(go, ho, lmax, step=3.0): """Surface B_r on a step-degree grid, as rows of digits from north to south: 0 inward and stronger than the rms, 1 inward, 2 outward, 3 outward and stronger than the rms. With the strongest spots and the dipole's two poles, in degrees.""" th = np.radians(np.arange(step / 2, 180.0, step)) ph = np.radians(np.arange(step / 2, 360.0, step)) P = schmidt(lmax, np.cos(th), np.sin(th)) Br = np.zeros((len(th), len(ph))) for l in range(1, lmax + 1): Br += (l + 1) * go[(l, 0)] * P[l, 0][:, None] for m in range(1, l + 1): Br += (l + 1) * np.outer(P[l, m], go[(l, m)] * np.cos(m * ph) + ho[(l, m)] * np.sin(m * ph)) rms = math.sqrt(float(np.sum(Br ** 2 * np.sin(th)[:, None]) / (np.sum(np.sin(th)) * len(ph)))) cls = np.where(Br < -rms, 0, np.where(Br < 0, 1, np.where(Br < rms, 2, 3))) colat = math.degrees(math.atan2(math.hypot(go[(1, 1)], ho[(1, 1)]), go[(1, 0)])) lon = math.degrees(math.atan2(ho[(1, 1)], go[(1, 1)])) % 360.0 sp = br_spots(go, ho, lmax) return {"rows": ["".join(str(int(x)) for x in row) for row in cls], "step_deg": step, "dipole_out": [r(90 - colat, 1), r(lon, 1)], "dipole_in": [r(colat - 90, 1), r((lon + 180.0) % 360.0, 1)], "strongest_out": [sp["out_lat"], sp["out_lon"]], "strongest_in": [sp["in_lat"], sp["in_lon"]]} def power(g, h, A, l, m): return (l + 1) * A ** (2 * l + 4) * (g[(l, m)] ** 2 + h[(l, m)] ** 2) def main(): folder = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "ice_giant_data") fetch(folder) dep = Deposit(os.path.join(folder, "Deposit_IceGiantDynamos.zip")) OUT = {"what": "Our analysis for factchecked.science/ice-giant-dynamos/. Tilt changes in degrees; shares as fractions; sigma = 1e4 S/m unless a key says otherwise."} series = {m: Series(dep, m) for m in range(15)} pub = {m: Series(dep, m, PUBLISHED_TAG[m]) for m in range(15)} obs = {n: dep.obs(n) for n in ("U_HB96", "U_AH5", "N_HB96", "N_O8")} rng = np.random.default_rng(SEED) clock = {"U": (0.7, R_U), "N": (0.8, R_N)} # -------------------------------------------------------------- the clock t3 = {} for planet, R_ in (("U", 2.56e7), ("N", 2.46e7)): for A in (0.7, 0.75, 0.8): for chi in (0.35, 0.5, 0.6): D = (1 - chi) * A * R_ t3[f"{planet}|A{A}|chi{chi}"] = r(MU0 * 1e4 * D * D / YEAR / 1e3, 1) rm = {m: TABLE2[m][0] for m in (6, 11)} OUT["clock"] = {"table3_kyr": t3, "models": {str(m): {c: {"D_km": r((1 - CHI[m]) * A * R_ / 1e3, 0), "tau_lambda_kyr": r(tau_nu_years(m, A, R_) * PM / 1e3, 1), "tau_nu_yr": r(tau_nu_years(m, A, R_), 0), "snapshot_yr": r(series[m].dt * tau_nu_years(m, A, R_), 2), "tau_U_yr": r(tau_nu_years(m, A, R_) * PM / rm[m], 0), "U_mm_per_s": r(rm[m] / (MU0 * 1e4) / ((1 - CHI[m]) * A * R_) * 1e3, 2)} for c, (A, R_) in clock.items()} for m in (6, 11)}} # -------------------------------------------------------------- reader checks chk = {} for m, tag in ((11, "2.11"), (3, "1.3"), (7, "1.7")): # Model 7 and the 99th percentile: rule C8 s = Series(dep, m, [tag]) d = dep.table(m, "dipole", tag, 18) near, ok = match(s, d[:, 0]) x = d[ok] i = near[ok] res = {"rows": int(ok.sum())} for name, f in (("true", 1.0), ("divided", 1 / SQ2)): g = {k: (v[i] * f if k[1] > 0 else v[i]) for k, v in s.g.items()} h = {k: (v[i] * f if k[1] > 0 else v[i]) for k, v in s.h.items()} E = {} for l in range(1, 7): e = (l + 1) * g[(l, 0)] ** 2 for mm in range(1, l + 1): e = e + (l + 1) * (g[(l, mm)] ** 2 + h[(l, mm)] ** 2) E[l] = e th = tilt(g[(1, 0)], g[(1, 1)], h[(1, 1)]) ax_share = 2 * g[(1, 0)] ** 2 / E[1] res[name] = {"tilt_diff_median": float(f"{np.median(np.abs(th - x[:, 1])):.3g}"), "tilt_diff_max": float(f"{np.max(np.abs(th - x[:, 1])):.3g}"), "axial_share_of_dipole_diff_median": float(f"{np.median(np.abs(ax_share - x[:, 10] / x[:, 9])):.3g}")} # the dipole's share of surface energy to l <= 11 needs l up to 11, from the raw coefficients t_, raw, l_file = dep.bcoeff(m, tag) G, H = gauss(raw, l_file, lmax_out=11) n_, ok_ = match(s, d[:, 0]) for name, f in (("true", 1.0), ("divided", 1 / SQ2)): tot = 0.0 for l in range(1, 12): e = (l + 1) * G[(l, 0)][n_[ok_]] ** 2 for mm in range(1, l + 1): e = e + (l + 1) * ((G[(l, mm)][n_[ok_]] * f) ** 2 + (H[(l, mm)][n_[ok_]] * f) ** 2) if l == 1: dip = e tot = tot + e res[name]["dip_share_l11_relerr_median"] = float(f"{np.median(np.abs(dip / tot / d[ok_, 8] - 1)):.3g}") res[name]["dip_share_l11_relerr_p99"] = float(f"{np.percentile(np.abs(dip / tot / d[ok_, 8] - 1), 99):.3g}") chk[f"model{m}"] = res OUT["normalisation_check_against_dipole_file"] = chk # -------------------------------------------------------------- misfits, both recipes, every snapshot own = {} worst = 0.0 n_cmp = 0 maxdiff = 0.0 meddiff = [] for m in RANKED: s = series[m] g3 = {k: v for k, v in s.g.items() if k[0] <= 3} h3 = {k: v for k, v in s.h.items() if k[0] <= 3} for A in (0.7, 0.75, 0.8): d = dep.morpho(m, A) near, ok = match(s, d[:, 0]) for name, col in (("U_HB96", 1), ("U_AH5", 2), ("N_HB96", 3), ("N_O8", 4)): own[(m, A, name, "true")] = misfit(g3, h3, A, *obs[name]) own[(m, A, name, "divided")] = misfit(divided(g3), divided(h3), A, *obs[name]) worst = max(worst, float(np.max(np.abs(own[(m, A, name, "divided")][near[ok]] - d[ok, col])))) n_cmp += 1 dd = np.abs(own[(m, A, name, "true")] - own[(m, A, name, "divided")]) maxdiff = max(maxdiff, float(dd.max())) meddiff.append(float(np.median(dd))) OUT["misfit_check"] = {"comparisons_with_deposit": n_cmp, "largest_difference_divided_recipe": float(f"{worst:.2g}"), "true_minus_divided_largest": r(maxdiff, 3), "true_minus_divided_median_of_medians": r(float(np.median(meddiff)), 3)} # -------------------------------------------------------------- whole runs whole = {} wins = {} for m, s in series.items(): whole[m] = {} for c, (A, R_) in clock.items(): tn = tau_nu_years(m, A, R_) W = 40.0 / tn w = windows(s, W) if c == "U": wins[m] = w whole[m][c] = {k: shares(w[k]) for k in ("END", "RANGE", "AXIS")} whole[m][c]["END"]["ci95"] = block_ci(w["END"], int(round(10 * W / s.dt)), rng) whole[m][c]["nonoverlapping_windows"] = r(s.span() / W, 0) p = windows(pub[m], 40.0 / tau_nu_years(m, 0.7, R_U)) whole[m]["U_published_tags_END"] = shares(p["END"]) OUT["whole_run_40yr"] = {str(k): v for k, v in whole.items()} # -------------------------------------------------------------- the paper's numbers paper = {} tn11, tn6 = tau_nu_years(11, 0.7, R_U), tau_nu_years(6, 0.7, R_U) m11 = dep.morpho(11, 0.7) t0_11 = m11[m11[:, 0] >= 39.33, 0][0] - 10.0 / tn11 t0_6 = 42.688 - 250.0 / tn6 s11, s6 = Series(dep, 11, ["2.11"]), Series(dep, 6, ["4.6"]) for lab, s, t0, tn, a_, b_ in (("model11_84", s11, t0_11, tn11, 51.0, 91.0), ("model6_13", s6, t0_6, tn6, 234.0, 274.0)): ta, tb = t0 + a_ / tn, t0 + b_ / tn mask = (s.t >= ta) & (s.t <= tb) vals = np.concatenate([s.theta[mask], [s.at(ta), s.at(tb)]]) ax_ = lambda x: np.array([np.interp(x, s.t, s.g[(1, 1)]), np.interp(x, s.t, s.h[(1, 1)]), np.interp(x, s.t, s.g[(1, 0)])]) ua, ub = ax_(ta), ax_(tb) ua, ub = ua / np.linalg.norm(ua), ub / np.linalg.norm(ub) P = {} for l in (1, 2, 3): p_ = (l + 1) * 0.7 ** (2 * l + 4) * s.g[(l, 0)] ** 2 for mm in range(1, l + 1): p_ = p_ + (l + 1) * 0.7 ** (2 * l + 4) * (s.g[(l, mm)] ** 2 + s.h[(l, mm)] ** 2) P[l] = p_ sh = P[1] / (P[1] + P[2] + P[3]) paper[lab] = {"tilt_start": r(s.at(ta), 2), "tilt_end": r(s.at(tb), 2), "END": r(abs(s.at(tb) - s.at(ta)), 2), "RANGE": r(vals.max() - vals.min(), 2), "AXIS": r(np.degrees(np.arccos(np.clip(ua @ ub, -1, 1))), 1), "dipole_share_l3_start": r(np.interp(ta, s.t, sh), 3), "dipole_share_l3_end": r(np.interp(tb, s.t, sh), 3), "dipole_share_l3_min": r(sh[mask].min(), 3)} pctl = {} for lab, m, val in (("84_in_model11", 11, 84.0), ("13_in_model6", 6, 13.0)): pctl[lab] = {"percent_of_whole_run_windows_at_or_below": r(np.mean(wins[m]["END"] <= val) * 100, 1)} paper["percentile"] = pctl # 5 degrees in 50 years on the 1e4 clock. Windows start at snapshots, as everywhere else, and include their interpolated ends: rule C9 w50s = windows(s6, 50.0 / tn6) tt50 = (s6.t[w50s["i"]] - t0_6) * tn6 near50 = (tt50 >= 150) & (tt50 <= 350) w50 = windows(series[6], 50.0 / tn6) paper["five_deg_in_50yr"] = {"min_range": r(w50s["RANGE"][near50].min(), 2), "range_le5_starts_yr": [r(tt50[near50][w50s["RANGE"][near50] <= 5].min(), 0), r(tt50[near50][w50s["RANGE"][near50] <= 5].max(), 0)], "whole_run_share_range_le5": r(np.mean(w50["RANGE"] <= 5), 4), "whole_run_share_end_le5": r(np.mean(w50["END"] <= 5), 4)} # Figure 3's 32 years fig3 = {} for lab, m, tag, A, R_, name in (("model6_uranus", 6, ["4.6"], 0.7, R_U, "U_HB96"), ("model11_neptune", 11, ["2.11"], 0.8, R_N, "N_HB96")): d = dep.morpho(m, A) s = series[m] tn = tau_nu_years(m, A, R_) near, ok = match(s, d[:, 0]) rows = own[(m, A, name, "divided")][near[ok]] i = near[ok][int(np.argmin(rows))] j = int(np.argmin(np.abs(s.t - (s.t[i] + 32.0 / tn)))) fig3[lab] = {"t_nu": r(s.t[i], 4), "misfit": r(own[(m, A, name, "divided")][i], 3), "misfit_32yr": r(own[(m, A, name, "divided")][j], 3), "misfit_true": r(own[(m, A, name, "true")][i], 3), "tilt": r(s.theta[i], 2), "tilt_32yr": r(s.theta[j], 2)} paper["figure3"] = fig3 OUT["paper_numbers"] = paper # -------------------------------------------------------------- source data sd2 = read_xlsx(os.path.join(folder, "MOESM5.xlsx")) sd3 = read_xlsx(os.path.join(folder, "MOESM6.xlsx")) src = {} for sheet in ("Fig3c", "Fig3e", "Fig3d", "Fig3f"): rows = {(int(x[0]), int(x[1])): (x[2], x[3]) for x in sd2[sheet][1:]} g10, (g11, h11) = rows[(1, 0)][0], rows[(1, 1)] src[sheet] = {"tilt_from_sheet": r(math.degrees(math.atan2(math.hypot(g11, h11), g10)), 2), "tilt_if_m1_times_sqrt2": r(math.degrees(math.atan2(math.hypot(g11, h11) * SQ2, g10)), 2)} for sheet, lab, a_, b_ in (("Fig4gh", "fig4_model11_END", 51.0, 91.0), ("Fig4ab", "fig4_model6_END", 234.0, 274.0)): x = np.array([[v[0], v[1]] for v in sd3[sheet][1:]], dtype=float) src[lab] = r(abs(np.interp(a_, x[:, 0], x[:, 1]) - np.interp(b_, x[:, 0], x[:, 1])), 2) OUT["source_data_checks"] = src # -------------------------------------------------------------- like stretches and anchors REFS = (("Uranus_HB96", "U_HB96", 0.7, R_U, 0.54, 1), ("Uranus_AH5", "U_AH5", 0.7, R_U, 0.54, 2), ("Neptune_HB96", "N_HB96", 0.8, R_N, 0.68, 3), ("Neptune_O8", "N_O8", 0.8, R_N, 0.68, 4)) like = {} for lab, name, A, R_, thr, col in REFS: for m in RANKED: s = series[m] tn = tau_nu_years(m, A, R_) W = 40.0 / tn w = windows(s, W) d = dep.morpho(m, A) near, ok = match(s, d[:, 0]) for key, times, rows in (("slice_divided", d[:, 0], d[:, col]), ("all_divided", s.t, own[(m, A, name, "divided")]), ("all_true", s.t, own[(m, A, name, "true")]), ("slice_true", s.t[near[ok]], own[(m, A, name, "true")][near[ok]])): ni, _ = match(s, times) below = rows < thr bset = set(map(int, ni[below])) mask = np.array([int(i) in bset for i in w["i"]], dtype=bool) t2i = {int(i): k for k, i in enumerate(w["i"])} eps = [] for e in episodes(times * tn, below): k = e[np.argmin(rows[e])] first, best, last = times[e[0]], times[k], times[e[-1]] inside = [int(ni[q]) for q in e] vals = [w["END"][t2i[i]] for i in inside if i in t2i] pos_best = t2i.get(int(ni[k])) pos_first = t2i.get(int(ni[e[0]])) eps.append({"t_nu_first": r(first, 4), "yr_long": r((last - first) * tn, 1), "snapshots": int(len(e)), "min_misfit": r(rows[e].min(), 3), "tilt_at_best": r(s.theta[ni[k]], 1), "END_from_first": None if pos_first is None else r(w["END"][pos_first], 1), "END_from_best": None if pos_best is None else r(w["END"][pos_best], 1), "END_min": r(min(vals), 1) if vals else None, "END_max": r(max(vals), 1) if vals else None}) like.setdefault(lab, {}).setdefault(key, {})[str(m)] = {"share_below": r(np.mean(below), 4), "min_misfit": r(rows.min(), 3), "END": shares(w["END"][mask]), "episodes": eps} OUT["like_by_model"] = {lab: {key: {m: (v if key == "slice_divided" else {"share_below": v["share_below"], "min_misfit": v["min_misfit"], "END": v["END"], "END_from_best_by_episode": [x["END_from_best"] for x in v["episodes"]]}) for m, v in recs.items()} for key, recs in keys.items()} for lab, keys in like.items()} pools = {} for lab, name, A, R_, thr, col in REFS: models = {"Uranus_HB96": (6, 10, 11), "Uranus_AH5": (6, 10, 11), "Neptune_HB96": (9, 6, 10, 11), "Neptune_O8": (11, 6, 10)}[lab] for key in ("slice_divided", "all_divided", "all_true"): vals, eps = [], [] for m in models: s = series[m] tn = tau_nu_years(m, A, R_) w = windows(s, 40.0 / tn) if key == "slice_divided": d = dep.morpho(m, A) ni, _ = match(s, d[:, 0]) bset = set(map(int, ni[d[:, col] < thr])) else: bset = set(map(int, np.where(own[(m, A, name, "divided" if key == "all_divided" else "true")] < thr)[0])) mask = np.array([int(i) in bset for i in w["i"]], dtype=bool) vals.append(w["END"][mask]) eps += [x["END_from_best"] for x in like[lab][key][str(m)]["episodes"] if x["END_from_best"] is not None] v = np.concatenate(vals) ee_ = np.array(eps) # episodes_total below counts those without a best-match window too: rule C10 pools[f"{lab}|{key}"] = dict(shares(v), models=list(models), episodes=len(eps), episodes_total=sum(len(like[lab][key][str(m)]["episodes"]) for m in models), episode_median=r(np.median(ee_), 1), episodes_le20=int(np.sum(ee_ <= 20)), episodes_gt30=int(np.sum(ee_ > 30)), episode_values=[r(x, 0) for x in eps] if len(eps) <= 8 else None) OUT["like_pooled"] = pools # -------------------------------------------------------------- baselines of the actual observations base = {} for lab, name, A, R_, thr, col, years, models in (("Uranus_1986_2023", "U_HB96", 0.7, R_U, 0.54, 1, 37.0, (6, 10, 11)), ("Neptune_1989_2023", "N_HB96", 0.8, R_N, 0.68, 3, 34.0, (9, 6, 10, 11)), ("Uranus_1986_2023_AH5", "U_AH5", 0.7, R_U, 0.54, 2, 37.0, (6, 10, 11)), ("Neptune_1989_2023_O8", "N_O8", 0.8, R_N, 0.68, 4, 34.0, (11, 6, 10))): # the last two: rule C1 vals = [] for m in models: s = series[m] w = windows(s, years / tau_nu_years(m, A, R_)) d = dep.morpho(m, A) ni, _ = match(s, d[:, 0]) bset = set(map(int, ni[d[:, col] < thr])) vals.append(w["END"][np.array([int(i) in bset for i in w["i"]], dtype=bool)]) v = np.concatenate(vals) base[lab] = {"years": years, "n": int(len(v)), "le10": r(np.mean(v <= 10), 3), "le20": r(np.mean(v <= 20), 3), "ge20": r(np.mean(v >= 20), 3), "ge30": r(np.mean(v >= 30), 3), "median": r(np.median(v), 1)} OUT["baselines"] = base # -------------------------------------------------------------- rescaling sigma sig = {} for m in (6, 10, 11): sig[m] = {} for label, factor in (("2e3", 0.2), ("1e4", 1.0), ("1e5", 10.0)): W = 40.0 / (tau_nu_years(m, 0.7, R_U) * factor) v = shares(windows(series[m], W)["END"]) v["window_in_snapshots"] = r(W / series[m].dt, 2) sig[m][label] = v OUT["sigma_rescaled_whole_run"] = {str(k): v for k, v in sig.items()} # -------------------------------------------------------------- Earth and the controls vals = {} with open(os.path.join(folder, "igrf14coeffs.txt"), encoding="utf-8", errors="replace") as f: for line in f: if line.startswith("g/h"): names = line.split() epochs = [float(x) for x in names[3:-1]] elif line[:2] in ("g ", "h "): p = line.split() vals[(p[0], int(p[1]), int(p[2]))] = [float(x) for x in p[3:]] g10 = np.array(vals[("g", 1, 0)][:len(epochs)]) g11 = np.array(vals[("g", 1, 1)][:len(epochs)]) h11 = np.array(vals[("h", 1, 1)][:len(epochs)]) te = np.degrees(np.arctan2(np.hypot(g11, h11), -g10)) vec = np.stack((g11, h11, g10), axis=-1) vec /= np.linalg.norm(vec, axis=1, keepdims=True) pairs = [] for i, a_ in enumerate(epochs): for j, b_ in enumerate(epochs): if b_ - a_ == 50: pairs.append((a_, b_, float(abs(te[j] - te[i])), float(np.degrees(np.arccos(np.clip(vec[i] @ vec[j], -1, 1)))))) ix25 = epochs.index(2025.0) gE = {(l, m): vals[("g", l, m)][ix25] for (c, l, m) in vals if c == "g"} hE = {(l, m): vals[("h", l, m)][ix25] if ("h", l, m) in vals else 0.0 for (c, l, m) in vals if c == "g"} tot = sum((l + 1) * gE[(l, m)] ** 2 + (l + 1) * hE[(l, m)] ** 2 for (l, m) in gE if l <= 13) tail = {"tilt": {str(int(e)): r(x, 2) for e, x in zip(epochs, te)}, "pairs_50yr": [[int(a_), int(b_), r(c_, 2), r(d_, 2)] for a_, b_, c_, d_ in pairs], "END_50yr_min": r(min(x[2] for x in pairs), 2), "END_50yr_max": r(max(x[2] for x in pairs), 2), "END_50yr_median": r(np.median([x[2] for x in pairs]), 2), "axial_dipole_share_2025_l13": r((2 * gE[(1, 0)] ** 2) / tot, 3), "spots_2025_l3": br_spots(gE, hE, 3)} D_e = 2_260e3 tn_e = MU0 * 1e6 * D_e * D_e / YEAR / PM tail["model0_on_earth_clock_50yr"] = dict(shares(windows(series[0], 50.0 / tn_e)["END"]), tau_lambda_kyr=r(tn_e * PM / 1e3, 0)) OUT["earth"] = tail # -------------------------------------------------------------- context ctx = {"random_direction": {"share_within_10_of_59": r((math.cos(math.radians(49)) - math.cos(math.radians(69))) / 2, 3), "share_within_10_of_47": r((math.cos(math.radians(37)) - math.cos(math.radians(57))) / 2, 3)}} pol = {} for m, s in series.items(): tn = tau_nu_years(m, 0.7, R_U) state, count = 0, 0 for th in s.theta: if th < 60: count += state == -1 state = 1 elif th > 120: count += state == 1 state = -1 pol[m] = {"changes": int(count), "span_yr": r(s.span() * tn, 0), "per_1000yr": r(count / (s.span() * tn) * 1000, 2)} ctx["polarity_changes_uranus_clock"] = {str(k): v for k, v in pol.items()} fields = {} for name, (go, ho) in obs.items(): lmax = 4 if name == "U_AH5" else 3 P = {(l, m): (l + 1) * (go[(l, m)] ** 2 + ho[(l, m)] ** 2) for l in range(1, lmax + 1) for m in range(0, l + 1)} total = sum(P.values()) p0 = sum(v for k, v in P.items() if k[1] == 0) p1 = sum(v for k, v in P.items() if k[1] == 1) fields[name] = dict(br_spots(go, ho, lmax), tilt=r(math.degrees(math.atan2(math.hypot(go[(1, 1)], ho[(1, 1)]), go[(1, 0)])), 1), tilt_if_divided=r(math.degrees(math.atan2(math.hypot(go[(1, 1)], ho[(1, 1)]) / SQ2, go[(1, 0)])), 1), f_M1=r(p1 / p0, 2), # tilt_if_divided: rule C4 axial_dipole_share=r(P[(1, 0)] / total, 3), dipole_share=r(sum(P[(1, m)] for m in (0, 1)) / total, 3)) ctx["observed_fields"] = fields weak = {} for m in (6, 7, 9, 10, 11): s = series[m] W = 40.0 / tau_nu_years(m, 0.7, R_U) amp = np.sqrt(s.g[(1, 0)] ** 2 + s.g[(1, 1)] ** 2 + s.h[(1, 1)] ** 2) j = np.searchsorted(s.t, s.t + W, side="right") - 1 idx = np.where(s.t + W <= s.t[-1])[0] end = np.abs(np.interp(s.t[idx] + W, s.t, s.theta) - s.theta[idx]) minamp = np.array([amp[i:jj + 1].min() for i, jj in zip(idx, j[idx])]) P = {} for l in (1, 2, 3): p_ = (l + 1) * 0.7 ** (2 * l + 4) * s.g[(l, 0)] ** 2 for mm in range(1, l + 1): p_ = p_ + (l + 1) * 0.7 ** (2 * l + 4) * (s.g[(l, mm)] ** 2 + s.h[(l, mm)] ** 2) P[l] = p_ weak[m] = {"large_swings_with_weak_dipole": r(np.mean(minamp[end > 60] < 0.5 * np.median(amp)), 3), "small_changes_with_weak_dipole": r(np.mean(minamp[end < 10] < 0.5 * np.median(amp)), 3), "median_dipole_share_l3": r(np.median(P[1] / (P[1] + P[2] + P[3])), 3)} ctx["weak_dipole"] = {str(k): v for k, v in weak.items()} OUT["context"] = ctx # -------------------------------------------------------------- all 15 models against the thresholds, true coefficients allm = {} for m in range(15): s = series[m] g3 = {k: v for k, v in s.g.items() if k[0] <= 3} h3 = {k: v for k, v in s.h.items() if k[0] <= 3} row = {} for lab, name, A, R_, thr, col in REFS: x = own.get((m, A, name, "true")) x = misfit(g3, h3, A, *obs[name]) if x is None else x row[name] = {"min": r(x.min(), 3), "share_below": r(np.mean(x < thr), 4)} if m in CONTROLS: row[name]["min_divided_recipe"] = r(misfit(divided(g3), divided(h3), A, *obs[name]).min(), 3) allm[m] = row OUT["all_models_true_misfit"] = {str(k): v for k, v in allm.items()} # -------------------------------------------------------------- chance baseline rng2 = np.random.default_rng(SEED + 1) chance = {} def scramble(g, h, nrep): gout, hout = {}, {} n = len(g[(1, 0)]) for l in (1, 2, 3): keys = [(l, 0, "g")] for mm in range(1, l + 1): keys += [(l, mm, "g"), (l, mm, "h")] pw = g[(l, 0)] ** 2 for mm in range(1, l + 1): pw = pw + g[(l, mm)] ** 2 + h[(l, mm)] ** 2 z = rng2.normal(size=(n * nrep, len(keys))) z /= np.linalg.norm(z, axis=1, keepdims=True) z = z * np.repeat(np.sqrt(pw), nrep)[:, None] for q, key in enumerate(keys): (gout if key[2] == "g" else hout)[(key[0], key[1])] = z[:, q] hout[(l, 0)] = np.zeros(n * nrep) return gout, hout for lab, models, A, name, thr, col in (("Uranus_HB96", (6, 10, 11), 0.7, "U_HB96", 0.54, 1), ("Neptune_HB96", (9, 6, 10, 11), 0.8, "N_HB96", 0.68, 3)): chance[lab] = {} for m in models: s = series[m] d = dep.morpho(m, A) near, ok = match(s, d[:, 0]) i = near[ok] for key in ("divided", "true"): g = {k: v[i] for k, v in s.g.items() if k[0] <= 3} h = {k: v[i] for k, v in s.h.items() if k[0] <= 3} if key == "divided": g, h = divided(g), divided(h) real = misfit(g, h, A, *obs[name]) gs, hs = scramble(g, h, 20) sim = misfit(gs, hs, A, *obs[name]) chance[lab].setdefault(str(m), {})[key] = {"real_share_below": r(np.mean(real < thr), 4), "scrambled_share_below": r(np.mean(sim < thr), 4), "ratio": r(np.mean(real < thr) / np.mean(sim < thr), 1)} OUT["chance_baseline"] = chance # -------------------------------------------------------------- Supplementary Tables 2 and 3, divided and true fobs = {"U": 2.3, "N": 2.1} ranks = {} pool_store = {} for planet, refs in (("U", ("U_HB96", "U_AH5")), ("N", ("N_HB96", "N_O8"))): for name in refs: for A in (0.7, 0.75, 0.8): for key in ("divided", "true"): pooled, ntot, fm1 = [], {}, {} for m in RANKED: s = series[m] d = dep.morpho(m, A) near, ok = match(s, d[:, 0]) rows = own[(m, A, name, key)][near[ok]] ntot[m] = len(rows) pooled += [(x, m, tq) for x, tq in zip(rows, s.t[near[ok]])] g = {k: v[near[ok]] for k, v in s.g.items()} h = {k: v[near[ok]] for k, v in s.h.items()} p0 = sum(np.mean(power(g, h, A, l, 0)) for l in range(1, 4)) p1 = sum(np.mean(power(g, h, A, l, 1)) for l in range(1, 4)) fm1[m] = float(p1 / p0) pooled.sort(key=lambda x: x[0]) pool_store[(name, A, key)] = (planet, [(x[0], x[1]) for x in pooled[:200]], ntot, fm1) top = pooled[:100] table = {} for m in RANKED: rms = np.array([x[0] for x in top if x[1] == m]) if not len(rms): continue srms = -math.log(np.sum(np.exp(-0.5 * (rms / 0.2) ** 2)) / ntot[m]) sm1 = 0.5 * (math.log(fm1[m] / fobs[planet]) / math.log(1.5)) ** 2 ts = sorted(x[2] for x in top if x[1] == m) tn = tau_nu_years(m, A, R_U if planet == "U" else R_N) table[m] = {"N100": int(len(rms)), "S_rms": r(srms, 3), "S_M1": r(sm1, 3), "S_tot": r(srms + sm1, 3), "episodes": 1 + sum(1 for a_, b_ in zip(ts[:-1], ts[1:]) if (b_ - a_) * tn >= 40.0)} order = sorted(table, key=lambda k: table[k]["S_tot"]) ranks[f"{name}|A{A}|{key}"] = {"order": order, "episodes_total": int(sum(v["episodes"] for v in table.values())), "table": {str(k): v for k, v in table.items()}} OUT["rankings"] = ranks # -------------------------------------------------------------- Table 2 t2 = {} for m in range(15): # 12-14 and the Elsasser number: rule C7; the divided columns: rule C4 tag = PUBLISHED_TAG[m][-1] d = dep.table(m, "dipole", tag, 3) i0 = int(np.argmin(np.abs(d[:, 0] - (d[-1, 0] - 1.0)))) if d[-1, 0] - d[0, 0] >= 1 else 0 th = d[i0:, 1] par = dep.table(m, "par", tag, 16) k0 = int(np.argmin(np.abs(par[:, 0] - (par[-1, 0] - 1.0)))) if par[-1, 0] - par[0, 0] >= 1 else 0 s = pub[m] q = int(np.argmin(np.abs(s.t - (s.t[-1] - 0.5)))) g = {k: v[q:] for k, v in s.g.items()} h = {k: v[q:] for k, v in s.h.items()} p0 = sum(power(g, h, 0.8, l, 0) for l in range(1, 7)) p1 = sum(power(g, h, 0.8, l, 1) for l in range(1, 7)) pl = {l: sum(power(g, h, 0.8, l, mm) for mm in range(0, l + 1)) for l in (1, 2, 3)} gd, hd = divided(g), divided(h) p0d = sum(power(gd, hd, 0.8, l, 0) for l in range(1, 7)) p1d = sum(power(gd, hd, 0.8, l, 1) for l in range(1, 7)) pld = {l: sum(power(gd, hd, 0.8, l, mm) for mm in range(0, l + 1)) for l in (1, 2, 3)} t2[m] = {"paper": TABLE2[m], "Rm": r(np.mean(par[k0:, 1]), 0), "Rol": r(np.mean(par[k0:, 3]), 2), "tilt_mean": r(np.mean(th), 1), "tilt_sd": r(np.std(th), 1), "p_tilt_U": r(np.mean(np.abs(th - 59) <= 10) * 100, 1), "p_tilt_N": r(np.mean(np.abs(th - 47) <= 10) * 100, 1), "f_M1": r(np.mean(p1) / np.mean(p0), 2), "p_M": r(np.mean(p1 > p0) * 100, 1), "p_l": r(np.mean((pl[2] > pl[1]) | (pl[3] > pl[1])) * 100, 1), "Elsasser_paper": TABLE2_ELSASSER[m], "Elsasser": float(f"{np.mean(par[k0:, 15]):.3g}"), "f_M1_divided": r(np.mean(p1d) / np.mean(p0d), 2), "p_M_divided": r(np.mean(p1d > p0d) * 100, 1), "p_l_divided": r(np.mean((pld[2] > pld[1]) | (pld[3] > pld[1])) * 100, 1)} OUT["table2"] = {str(k): v for k, v in t2.items()} # -------------------------------------------------------------- C2: the shaded intervals on both recipes (HB96, A = 0.7, threshold 0.54) shade = {} for lab, m, t0, tn in (("model6", 6, t0_6, tn6), ("model11", 11, t0_11, tn11)): s = series[m] w = windows(s, 40.0 / tn) t2i = {int(i): k for k, i in enumerate(w["i"])} near, ok = match(s, dep.morpho(m, 0.7)[:, 0]) idx = near[ok] shade[lab] = {} for key in ("divided", "true"): rows = own[(m, 0.7, "U_HB96", key)][idx] eps = [] for e in episodes(s.t[idx] * tn, rows < 0.54): q = idx[e] vals = np.array([w["END"][t2i[int(i)]] for i in q if int(i) in t2i]) best = int(idx[e[np.argmin(rows[e])]]) eps.append({"t_first": r((s.t[q[0]] - t0) * tn, 1), "t_last": r((s.t[q[-1]] - t0) * tn, 1), "snapshots": int(len(e)), "END_from_first": r(w["END"][t2i[int(q[0])]], 1), "END_from_best": r(w["END"][t2i[best]], 1), "END_min": r(vals.min(), 1), "END_max": r(vals.max(), 1), "windows_within_20": int(np.sum(vals <= 20)), "misfit_at_first_divided": r(own[(m, 0.7, "U_HB96", "divided")][q[0]], 3), "misfit_at_first_true": r(own[(m, 0.7, "U_HB96", "true")][q[0]], 3)}) shade[lab][key] = eps OUT["shaded_intervals_both_recipes"] = shade # -------------------------------------------------------------- C3: secular-variation timescales on both recipes def sv_tau(s, A, lmax, div): n = len(s.t) lo, hi = np.maximum(np.arange(n) - 1, 0), np.minimum(np.arange(n) + 1, n - 1) dt = s.t[hi] - s.t[lo] fac = lambda mm: (1.0 / SQ2 if div and mm > 0 else 1.0) val = lambda l, mm, c: (s.g if c == "g" else s.h)[(l, mm)] * A ** (l + 2) * fac(mm) rate = lambda l, mm, c: (val(l, mm, c)[hi] - val(l, mm, c)[lo]) / dt def rms(get, l0, l1): p_ = np.zeros(n) for l in range(l0, l1 + 1): p_ += wl(l) * get(l, 0, "g") ** 2 for mm in range(1, l + 1): p_ += wl(l) * (get(l, mm, "g") ** 2 + get(l, mm, "h") ** 2) return np.sqrt(p_) return rms(val, 1, lmax) / rms(rate, 1, lmax), rms(val, 1, 1) / rms(rate, 1, 1) def pct(x): return {"median": r(np.nanmedian(x), 3), "p5": r(np.nanpercentile(x, 5), 3), "p95": r(np.nanpercentile(x, 95), 3)} svb = {} for lab, m, s, tn in (("model6", 6, s6, tn6), ("model11", 11, s11, tn11)): rows = [] for line in dep.text_rows(f"derived/Model{m:02d}_sv_dipsplit_A0.7.txt"): if line.strip() and not line.startswith("#"): rows.append([float(x) for x in line.split()]) rows = np.array(rows) near, ok = match(s, rows[:, 0]) at_d, ad_d = sv_tau(s, 0.7, 3, True) at_u, ad_u = sv_tau(s, 0.7, 3, False) ep = like["Uranus_HB96"]["slice_divided"][str(m)]["episodes"] main_ep = max(ep, key=lambda x: x["snapshots"]) if m == 6 else ep[0] mask = (s.t >= main_ep["t_nu_first"] - 1e-4) & (s.t <= main_ep["t_nu_first"] + main_ep["yr_long"] / tn + 1e-4) svb[lab] = {"rows_matched": int(ok.sum()), "largest_rel_diff_from_deposit_tau_tot": float(f"{np.nanmax(np.abs(at_d[near[ok]] / rows[ok, 7] - 1)):.2g}"), "largest_rel_diff_from_deposit_tau_dip": float(f"{np.nanmax(np.abs(ad_d[near[ok]] / rows[ok, 8] - 1)):.2g}"), "undivided_over_divided_tau_tot": pct(at_u / at_d), "undivided_over_divided_tau_dip": pct(ad_u / ad_d), "shaded_interval_snapshots": int(mask.sum()), "shaded_interval_mean_ratio_tau_tot": r(np.nanmean(at_u[mask]) / np.nanmean(at_d[mask]), 3), "shaded_interval_mean_ratio_tau_dip": r(np.nanmean(ad_u[mask]) / np.nanmean(ad_d[mask]), 3)} OUT["sv_timescales_both_recipes"] = svb # -------------------------------------------------------------- C5: a longer scramble per snapshot, and a stricter one that keeps the time structure N_SNAP, N_COH = 200, 400 rng3 = np.random.default_rng(SEED + 2) def haar(n): q_, r_ = np.linalg.qr(rng3.normal(size=(n, n))) return q_ * np.sign(np.diag(r_)) def deg_vec(g, h, l): cols = [g[(l, 0)]] for mm in range(1, l + 1): cols += [g[(l, mm)], h[(l, mm)]] return np.stack(cols, axis=1) def from_vecs(vecs, n): gs, hs = {}, {} for l, v in vecs.items(): gs[(l, 0)] = v[:, 0] hs[(l, 0)] = np.zeros(n) for mm in range(1, l + 1): gs[(l, mm)] = v[:, 2 * mm - 1] hs[(l, mm)] = v[:, 2 * mm] return gs, hs strict = {} runs = [("Uranus_HB96", (6, 10, 11), 0.7, R_U, "U_HB96", 0.54, ("divided", "true")), ("Uranus_AH5", (6, 10, 11), 0.7, R_U, "U_AH5", 0.54, ("divided", "true")), ("Neptune_HB96", (9, 6, 10, 11), 0.8, R_N, "N_HB96", 0.68, ("divided",)), ("Neptune_O8", (11, 6, 10), 0.8, R_N, "N_O8", 0.68, ("divided",))] for lab, models, A, R_, name, thr, keys in runs: strict[lab] = {} for m in models: s = series[m] tn = tau_nu_years(m, A, R_) near, ok = match(s, dep.morpho(m, A)[:, 0]) i = near[ok] n = len(i) for key in keys: g = {k: v[i] for k, v in s.g.items() if k[0] <= 3} h = {k: v[i] for k, v in s.h.items() if k[0] <= 3} if key == "divided": g, h = divided(g), divided(h) vecs = {l: deg_vec(g, h, l) for l in (1, 2, 3)} real = misfit(g, h, A, *obs[name]) share = float(np.mean(real < thr)) n_ep = len(episodes(s.t[i] * tn, real < thr)) hits = 0 for _ in range(N_SNAP): out = {} for l, v in vecs.items(): u = rng3.normal(size=v.shape) u /= np.linalg.norm(u, axis=1, keepdims=True) out[l] = u * np.linalg.norm(v, axis=1, keepdims=True) hits += int(np.sum(misfit(*from_vecs(out, n), A, *obs[name]) < thr)) sh_c, ep_c = [], [] for _ in range(N_COH): mf = misfit(*from_vecs({l: v @ haar(2 * l + 1).T for l, v in vecs.items()}, n), A, *obs[name]) sh_c.append(np.mean(mf < thr)) ep_c.append(len(episodes(s.t[i] * tn, mf < thr))) sh_c, ep_c = np.array(sh_c), np.array(ep_c) strict[lab].setdefault(str(m), {})[key] = {"real_share": r(share, 4), "real_episodes": n_ep, "per_snapshot_hits": hits, "per_snapshot_share": r(hits / (n * N_SNAP), 5), "per_snapshot_ratio": r(share / (hits / (n * N_SNAP)), 1), "coherent_mean_share": r(sh_c.mean(), 4), "coherent_mean_episodes": r(ep_c.mean(), 2), "P_share": r(np.mean(sh_c >= share), 4), "P_episodes": r(np.mean(ep_c >= n_ep), 4)} OUT["chance_stricter"] = {"draws_per_snapshot": N_SNAP, "coherent_draws": N_COH, "results": strict} # -------------------------------------------------------------- C6: the score's tolerance and top-N grid, and the snapshot score alone grid = {"sigma_rms": [0.1, 0.15, 0.2, 0.25, 0.3], "top_n": [50, 100, 150, 200], "cells": 0, "cells_family_holds": 0, "cells_set_same_as_table": 0, "tables": {}} alone = {} for (name, A, key), (planet, pooled, ntot, fm1) in pool_store.items(): if key == "divided": base = None rec = {} for sig_ in grid["sigma_rms"]: for top_n in grid["top_n"]: top = pooled[:top_n] sc = {} for m in RANKED: rms = np.array([x[0] for x in top if x[1] == m]) if len(rms): sc[m] = -math.log(np.sum(np.exp(-0.5 * (rms / sig_) ** 2)) / ntot[m]) + 0.5 * (math.log(fm1[m] / fobs[planet]) / math.log(1.5)) ** 2 top3 = sorted(sc, key=sc.get)[:3] grid["cells"] += 1 held = set(top3) <= FAMILY grid["cells_family_holds"] += int(held) rec[f"{sig_}|{top_n}"] = top3 if not held: grid.setdefault("outside_family", []).append([name, A, sig_, top_n, top3]) base = set(rec["0.2|100"]) grid["cells_set_same_as_table"] += sum(set(v) == base for v in rec.values()) grid["tables"][f"{name}|A{A}"] = sorted({tuple(sorted(v)) for v in rec.values()}) tbl = ranks[f"{name}|A{A}|{key}"]["table"] alone[f"{name}|A{A}|{key}"] = {"S_rms_order": sorted(map(int, tbl), key=lambda k: tbl[str(k)]["S_rms"]), "S_tot_order": ranks[f"{name}|A{A}|{key}"]["order"], "model1_N100": tbl["1"]["N100"] if "1" in tbl else 0, "model1_S_M1": tbl["1"]["S_M1"] if "1" in tbl else None} OUT["ranking_grid"] = grid OUT["ranking_snapshot_score_alone"] = alone # -------------------------------------------------------------- write with open(os.path.join(HERE, "ice-giant-numbers.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(OUT, f, indent=1, ensure_ascii=False) with open(os.path.join(HERE, "ice-giant-end40-ecdf.csv"), "w", encoding="utf-8", newline="\n") as f: w_ = csv.writer(f, lineterminator="\n") w_.writerow(["degrees"] + [f"model_{m}" for m in range(15)]) for x in range(0, 181): w_.writerow([x] + [f"{np.mean(wins[m]['END'] <= x):.4f}" for m in range(15)]) t6 = (s6.t - t0_6) * tn6 d6 = dep.morpho(6, 0.7) n6, _ = match(s6, d6[:, 0]) mis = np.full(len(s6.t), np.nan) mis[n6] = d6[:, 1] keep = (t6 >= 150) & (t6 <= 360) w6 = windows(s6, 40.0 / tn6) t2i6 = {int(i): k for k, i in enumerate(w6["i"])} below6 = [int(i) for i, x in zip(n6, d6[:, 1]) if x < 0.54 and 225 <= t6[int(i)] <= 275] interval = [[r(t6[i], 1), r(w6["END"][t2i6[i]], 1), r(s6.theta[i], 1)] for i in below6] OUT["model6_interval_40yr_END_by_start"] = interval with open(os.path.join(HERE, "ice-giant-numbers.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(OUT, f, indent=1, ensure_ascii=False) series6 = {"note": "Model 6, tag 4.6, on the paper's Uranus clock. t_yr counts from the origin of the deposit's Figure 4 script. misfit is the deposit's series against HB96.", "t_yr": [r(x, 1) for x in t6[keep]], "tilt": [r(x, 2) for x in s6.theta[keep]], "misfit": [None if np.isnan(x) else r(x, 3) for x in mis[keep]], "interval_t_yr_END_tilt": interval, "maps_note": "Surface B_r to l = 3 from the published coefficients: Uranus and Neptune HB96 (Holme & Bloxham 1996), Earth IGRF-14 for 2025. Longitude in each model's own system.", "maps": {"Uranus_HB96": br_map(*obs["U_HB96"], 3), "Neptune_HB96": br_map(*obs["N_HB96"], 3), "Earth_2025": br_map(gE, hE, 3)}} with open(os.path.join(HERE, "ice-giant-chart-series.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(series6, f, indent=0, ensure_ascii=False) print("done") if __name__ == "__main__": main()