"""Field-model library for the note 007 checks (factchecked.science, south-atlantic-anomaly-growth, wave 1). Readers for IGRF-14 (and IGRF-13), gufm1, COV-OBS.x2 and CHAOS-8 spline files (all parsed as data), a numpy grid synthesis, an independent pure-Python point synthesis, WGS84 geometry, the South Atlantic Anomaly's minimum / area / centre, the north dip pole, the dipole and great-circle speeds. Conventions: Schmidt semi-normalised Legendre functions; X north, Y east, Z down in the geodetic frame; reference radius a = 6371.2 km; WGS84 surface at h = 0 unless stated. """ import math import numpy as np from scipy import ndimage from scipy.interpolate import BSpline, CubicSpline from scipy.optimize import minimize, root A_REF = 6371.2 WGS84_A = 6378.137 WGS84_F = 1.0 / 298.257223563 E2 = WGS84_F * (2.0 - WGS84_F) WGS84_B = WGS84_A * (1.0 - WGS84_F) R_SPEED = 6371.0 MU0_OVER_4PI = 1e-7 # ------------------------------------------------------------------ readers def _numbers(path, skip_hash=True): out = [] with open(path, encoding="ascii", errors="strict") as f: for line in f: s = line.strip() if not s or (skip_hash and s.startswith("#")): continue out.append(s) return out class IGRF: """IGRF coefficient file: linear interpolation between epochs, SV extrapolation after the last epoch.""" def __init__(self, path, nmax=13): self.nmax = nmax rows = {} epochs = None with open(path, encoding="ascii") as f: for line in f: if line.startswith("g/h"): p = line.split() epochs = [float(x) for x in p[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:]] self.epochs = np.array(epochs) ne = len(epochs) self.G = np.zeros((ne, nmax + 1, nmax + 1)) self.H = np.zeros((ne, nmax + 1, nmax + 1)) self.Gsv = np.zeros((nmax + 1, nmax + 1)) self.Hsv = np.zeros((nmax + 1, nmax + 1)) for (gh, n, m), v in rows.items(): if n > nmax: continue A, S = (self.G, self.Gsv) if gh == "g" else (self.H, self.Hsv) A[:, n, m] = v[:ne] S[n, m] = v[ne] self._cubic = None def gh(self, t): e = self.epochs if t >= e[-1]: return self.G[-1] + (t - e[-1]) * self.Gsv, self.H[-1] + (t - e[-1]) * self.Hsv if t < e[0]: raise ValueError("before IGRF's first epoch") i = int(np.searchsorted(e, t, side="right") - 1) w = (t - e[i]) / (e[i + 1] - e[i]) return self.G[i] + w * (self.G[i + 1] - self.G[i]), self.H[i] + w * (self.H[i + 1] - self.H[i]) def sv(self, t): """Slope of the linear segment in force at t (or the forecast SV after the last epoch).""" e = self.epochs if t >= e[-1]: return self.Gsv.copy(), self.Hsv.copy() i = int(np.searchsorted(e, t, side="right") - 1) d = e[i + 1] - e[i] return (self.G[i + 1] - self.G[i]) / d, (self.H[i + 1] - self.H[i]) / d def gh_cubic(self, t): """Control: each coefficient through its epoch values plus the 5-yr forecast knot, cubic (not-a-knot).""" if self._cubic is None: tt = np.append(self.epochs, self.epochs[-1] + 5.0) G = np.concatenate([self.G, (self.G[-1] + 5.0 * self.Gsv)[None]], axis=0) H = np.concatenate([self.H, (self.H[-1] + 5.0 * self.Hsv)[None]], axis=0) self._cubic = (CubicSpline(tt, G, axis=0, bc_type="not-a-knot"), CubicSpline(tt, H, axis=0, bc_type="not-a-knot")) return self._cubic[0](t), self._cubic[1](t) class SplineModel: """gufm1, COV-OBS.x2 or CHAOS spline-coefficient file. Coefficient order g10, g11, h11, g20, g21, h21, ...""" def __init__(self, path, kind, nmax_use=None): lines = _numbers(path) if kind == "gufm1": # title; then nmax nspl knots...; then coefficients (order 4) nums = " ".join(lines[1:]).split() nmax, nspl = int(nums[0]), int(nums[1]) order = 4 knots = [float(x) for x in nums[2:2 + nspl + order]] vals = [float(x) for x in nums[2 + nspl + order:]] elif kind == "covobs": # title; then nmax nspl order knots...; then coefficients nums = " ".join(lines[1:]).split() nmax, nspl, order = int(nums[0]), int(nums[1]), int(nums[2]) knots = [float(x) for x in nums[3:3 + nspl + order]] vals = [float(x) for x in nums[3 + nspl + order:]] elif kind == "chaos": # '#' header lines; then nmax nspl order; knots; coefficients nums = " ".join(lines).split() nmax, nspl, order = int(nums[0]), int(nums[1]), int(nums[2]) knots = [float(x) for x in nums[3:3 + nspl + order]] vals = [float(x) for x in nums[3 + nspl + order:]] else: raise ValueError(kind) ncoef = nmax * (nmax + 2) if len(vals) != nspl * ncoef: raise ValueError("unexpected layout: %d values, expected %d" % (len(vals), nspl * ncoef)) self.kind, self.nmax_file, self.nspl, self.order = kind, nmax, nspl, order self.nmax = nmax if nmax_use is None else min(nmax, nmax_use) self.knots = np.array(knots) self.coefs = np.array(vals).reshape(nspl, ncoef) self.k = order - 1 self.t_first, self.t_last = self.knots[self.k], self.knots[nspl] self.spl = BSpline(self.knots, self.coefs, self.k, extrapolate=False) self._der = {} self.g10_override = None # callable t -> g10 (for the Gubbins alternative) def flat(self, t, deriv=0): if not (self.t_first - 1e-9 <= t <= self.t_last + 1e-9): raise ValueError("t=%s outside %s-%s" % (t, self.t_first, self.t_last)) if deriv == 0: return self.spl(t) if deriv not in self._der: self._der[deriv] = self.spl.derivative(deriv) return self._der[deriv](t) def gh(self, t, deriv=0, nmax=None): nm = self.nmax if nmax is None else min(nmax, self.nmax_file) c = self.flat(t, deriv) g = np.zeros((nm + 1, nm + 1)) h = np.zeros((nm + 1, nm + 1)) for n in range(1, nm + 1): base = (n - 1) * (n + 1) g[n, 0] = c[base] for m in range(1, n + 1): g[n, m] = c[base + 2 * m - 1] h[n, m] = c[base + 2 * m] if self.g10_override is not None and deriv == 0: v = self.g10_override(t) if v is not None: g[1, 0] = v return g, h # ------------------------------------------------------------------ geometry def geodetic_to_geocentric(lat_deg, h_km=0.0): phi = np.radians(lat_deg) s, c = np.sin(phi), np.cos(phi) N = WGS84_A / np.sqrt(1.0 - E2 * s * s) x = (N + h_km) * c z = (N * (1.0 - E2) + h_km) * s phic = np.arctan2(z, x) return np.hypot(x, z), phic, phi - phic def band_area(lat1, lat2): """WGS84 ellipsoid area between geodetic latitudes (deg), km^2 per radian of longitude.""" e = math.sqrt(E2) def q(phi): s = np.sin(phi) return s / (1 - E2 * s * s) + (1 / (2 * e)) * np.log((1 + e * s) / (1 - e * s)) return 0.5 * WGS84_B ** 2 * (q(np.radians(lat2)) - q(np.radians(lat1))) EARTH_AREA = float(2 * math.pi * band_area(-90.0, 90.0)) def haversine_km(lat1, lon1, lat2, lon2, R=R_SPEED): p1, p2 = np.radians(lat1), np.radians(lat2) dphi = p2 - p1 dl = np.radians(np.asarray(lon2) - np.asarray(lon1)) a = np.sin(dphi / 2) ** 2 + np.cos(p1) * np.cos(p2) * np.sin(dl / 2) ** 2 return 2 * R * np.arcsin(np.sqrt(np.clip(a, 0, 1))) # ------------------------------------------------------------------ Legendre (vectorised) and grid synthesis def schmidt(theta, nmax): theta = np.atleast_1d(np.asarray(theta, dtype=float)) ct, st = np.cos(theta), np.sin(theta) K = theta.size P = np.zeros((K, nmax + 1, nmax + 1)) D = np.zeros_like(P) P[:, 0, 0] = 1.0 if nmax >= 1: P[:, 1, 0], D[:, 1, 0], P[:, 1, 1], D[:, 1, 1] = 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 class Rows: """Everything that depends only on (geodetic or spherical) latitude, for a grid of longitudes.""" def __init__(self, lats_deg, lons_deg, nmax, sphere=False, h_km=0.0): lats = np.asarray(lats_deg, dtype=float) if sphere: r = np.full(lats.shape, A_REF + h_km) phic = np.radians(lats) delta = np.zeros(lats.shape) else: r, phic, delta = geodetic_to_geocentric(lats, h_km) theta = np.pi / 2 - phic P, D = schmidt(theta, nmax) n = np.arange(nmax + 1) rr = (A_REF / r)[:, None] ** (n + 2)[None, :] self.nmax = nmax self.Pr = P * ((n + 1)[None, :] * rr)[:, :, None] self.Pt = D * rr[:, :, None] m = np.arange(nmax + 1) self.Pp = P * rr[:, :, None] * m[None, None, :] / np.sin(theta)[:, None, None] self.cd, self.sd = np.cos(delta), np.sin(delta) lam = np.radians(np.asarray(lons_deg, dtype=float)) self.C = np.cos(m[:, None] * lam[None, :]) self.S = np.sin(m[:, None] * lam[None, :]) def xyz(self, g, h): nm = self.nmax g = np.asarray(g)[:nm + 1, :nm + 1] h = np.asarray(h)[:nm + 1, :nm + 1] if g.shape[0] < nm + 1: gg = np.zeros((nm + 1, nm + 1)); hh = np.zeros((nm + 1, nm + 1)) gg[:g.shape[0], :g.shape[1]] = g; hh[:h.shape[0], :h.shape[1]] = h g, h = gg, hh Ag = np.einsum("knm,nm->km", self.Pr, g); Ah = np.einsum("knm,nm->km", self.Pr, h) Br = Ag @ self.C + Ah @ self.S Tg = np.einsum("knm,nm->km", self.Pt, g); Th = np.einsum("knm,nm->km", self.Pt, h) Xc = Tg @ self.C + Th @ self.S # = -B_theta Pg = np.einsum("knm,nm->km", self.Pp, g); Ph = np.einsum("knm,nm->km", self.Pp, h) Y = Pg @ self.S - Ph @ self.C # = B_phi Zc = -Br cd, sd = self.cd[:, None], self.sd[:, None] return Xc * cd + Zc * sd, Y, Zc * cd - Xc * sd # ------------------------------------------------------------------ independent pure-Python point synthesis def point_xyz(g, h, lat, lon, nmax, sphere=False, h_km=0.0): if sphere: r, phic, delta = A_REF + h_km, math.radians(lat), 0.0 else: phi = math.radians(lat) s, c = math.sin(phi), math.cos(phi) N = WGS84_A / math.sqrt(1.0 - E2 * s * s) x, z = (N + h_km) * c, (N * (1.0 - E2) + h_km) * s phic = math.atan2(z, x) r, delta = math.hypot(x, z), phi - phic theta = math.pi / 2 - phic ct, st = math.cos(theta), math.sin(theta) P = [[0.0] * (nmax + 1) for _ in range(nmax + 1)] D = [[0.0] * (nmax + 1) for _ in range(nmax + 1)] P[0][0] = 1.0 P[1][0], D[1][0], P[1][1], D[1][1] = 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 lam = math.radians(lon) br = bt = bp = 0.0 ar = A_REF / r for n in range(1, nmax + 1): f = ar ** (n + 2) for m in range(n + 1): gnm, hnm = float(g[n][m]), float(h[n][m]) if gnm == 0.0 and hnm == 0.0: continue cm, sm = math.cos(m * lam), math.sin(m * lam) q = gnm * cm + hnm * sm br += (n + 1) * f * q * P[n][m] bt -= f * q * D[n][m] bp -= f * m * (-gnm * sm + hnm * cm) * 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 point_F(g, h, lat, lon, nmax, sphere=False): X, Y, Z = point_xyz(g, h, lat, lon, nmax, sphere) return math.sqrt(X * X + Y * Y + Z * Z) # ------------------------------------------------------------------ the anomaly class Grid: def __init__(self, step=0.25, nmax=14, sphere=False, lat_range=(-90.0, 90.0)): n_lat = int(round((lat_range[1] - lat_range[0]) / step)) self.lat = lat_range[0] + step / 2 + step * np.arange(n_lat) self.lon = -180.0 + step / 2 + step * np.arange(int(round(360 / step))) self.step, self.sphere, self.nmax = step, sphere, nmax self.rows = Rows(self.lat, self.lon, nmax, sphere=sphere) self.row_area = band_area(self.lat - step / 2, self.lat + step / 2) * math.radians(step) phi = np.radians(self.lat) if sphere: phic = phi else: phic = geodetic_to_geocentric(self.lat)[1] lam = np.radians(self.lon) self.uv_geodetic = (np.cos(phi)[:, None] * np.cos(lam)[None, :], np.cos(phi)[:, None] * np.sin(lam)[None, :], np.sin(phi)[:, None] * np.ones_like(lam)[None, :]) self.uv_geocentric = (np.cos(phic)[:, None] * np.cos(lam)[None, :], np.cos(phic)[:, None] * np.sin(lam)[None, :], np.sin(phic)[:, None] * np.ones_like(lam)[None, :]) def fields(self, g, h): X, Y, Z = self.rows.xyz(g, h) return np.sqrt(X * X + Y * Y + Z * Z), np.hypot(X, Y) def connected_component(mask, seed, eight=True): structure = np.ones((3, 3), dtype=int) if eight else ndimage.generate_binary_structure(2, 1) lab, nlab = ndimage.label(mask, structure=structure) parent = list(range(nlab + 1)) def find(a): while parent[a] != a: parent[a] = parent[parent[a]] a = parent[a] return a nr = mask.shape[0] for i in range(nr): if not mask[i, -1]: continue for di in ((-1, 0, 1) if eight else (0,)): ii = i + di if 0 <= ii < nr and mask[ii, 0]: a, b = find(lab[i, -1]), find(lab[ii, 0]) if a != b: parent[a] = b root0 = find(lab[seed]) roots = np.array([find(k) for k in range(nlab + 1)]) return (roots[lab] == root0) & mask def anomaly(grid, g, h, nmax, threshold=32000.0, refine=True, F=None): if F is None: F, _ = grid.fields(g, h) i, j = np.unravel_index(np.argmin(F), F.shape) out = {"grid_min_F": float(F[i, j]), "grid_min_lat": float(grid.lat[i]), "grid_min_lon": float(grid.lon[j])} if refine: fun = lambda p: point_F(g, h, p[0], p[1], nmax, sphere=grid.sphere) x0 = np.array([grid.lat[i], grid.lon[j]]) simplex = np.array([x0, x0 + [grid.step, 0.0], x0 + [0.0, grid.step]]) res = minimize(fun, x0, method="Nelder-Mead", options={"xatol": 1e-7, "fatol": 1e-6, "initial_simplex": simplex, "maxiter": 4000}) out.update({"min_F": float(res.fun), "min_lat": float(res.x[0]), "min_lon": float(((res.x[1] + 180) % 360) - 180)}) for eight in (True, False): comp = connected_component(F < threshold, (i, j), eight=eight) w = comp * grid.row_area[:, None] area = float(w.sum()) key = "8" if eight else "4" out["area_km2_" + key] = area out["area_pct_" + key] = 100.0 * area / EARTH_AREA if eight: for name, uv in (("geodetic", grid.uv_geodetic), ("geocentric", grid.uv_geocentric)): sx, sy, sz = (float((w * c).sum()) for c in uv) out["centre_lon_" + name] = math.degrees(math.atan2(sy, sx)) out["centre_lat_" + name] = math.degrees(math.atan2(sz, math.hypot(sx, sy))) below = F < threshold out["area_km2_all_below"] = float((below * grid.row_area[:, None]).sum()) return out # ------------------------------------------------------------------ the north dip pole class PoleSeeder: def __init__(self, nmax, step=0.25): self.g = Grid(step=step, nmax=nmax, lat_range=(55.0, 90.0)) def seed(self, g, h): _, H = self.g.fields(g, h) i, j = np.unravel_index(np.argmin(H), H.shape) return float(self.g.lat[i]), float(self.g.lon[j]) def dip_pole(g, h, nmax, seed, tol_nT=1e-3): lat0, lon0 = seed def to_ll(uv): u, v = uv return 90.0 - math.hypot(u, v), math.degrees(math.atan2(v, u)) def fun(uv): la, lo = to_ll(uv) X, Y, _ = point_xyz(g, h, la, lo, nmax) return [X, Y] c = 90.0 - lat0 x0 = [c * math.cos(math.radians(lon0)), c * math.sin(math.radians(lon0))] res = root(fun, x0, method="hybr", options={"xtol": 1e-15}) la, lo = to_ll(res.x) X, Y, Z = point_xyz(g, h, la, lo, nmax) H = math.hypot(X, Y) if H >= tol_nT: # fall back: minimise H, then root again r2 = minimize(lambda uv: math.hypot(*fun(uv)), x0, method="Nelder-Mead", options={"xatol": 1e-10, "fatol": 1e-9, "maxiter": 5000}) res = root(fun, r2.x, method="hybr", options={"xtol": 1e-15}) la, lo = to_ll(res.x) X, Y, Z = point_xyz(g, h, la, lo, nmax) H = math.hypot(X, Y) return {"lat": la, "lon": lo, "H_nT": H, "Z_nT": Z, "ok": H < tol_nT} # ------------------------------------------------------------------ the dipole def dipole(g, h): g10, g11, h11 = float(g[1][0]), float(g[1][1]), float(h[1][1]) b0 = math.sqrt(g10 * g10 + g11 * g11 + h11 * h11) M = (A_REF * 1e3) ** 3 * (b0 * 1e-9) / MU0_OVER_4PI / 1e22 tilt = math.degrees(math.acos(-g10 / b0)) return {"g10": g10, "absg10": abs(g10), "B0": b0, "M": M, "tilt": tilt, "pole_lat": 90.0 - tilt, "pole_lon": math.degrees(math.atan2(-h11, -g11))}