"""CHAOS-8.7 internal field from the DTU core and lithospheric SHC files."""
from __future__ import annotations
import warnings
from functools import lru_cache
from pathlib import Path
import numpy as np
from numba import njit
from ADCS.helpers.math.spherical_harmonics import _eval_one, _schmidt_table
from ADCS.environment.ephemeris._download import kernel_path as default_kernel_path
from ._coefficients import coordinate_dates, ensure_kernel, evaluate_static, shaped_field
from .magnetic_field import MagneticField
CHAOS8_VERSION = "8.7"
@lru_cache(maxsize=4)
def _read_shc(path: str, expected_min: int, expected_max: int):
r"""Read CHAOS SHC snapshots and normalize their Gauss coefficients.
:param path: Local SHC file path.
:type path: str
:param expected_min: First expected harmonic degree.
:type expected_min: int
:param expected_max: Last expected harmonic degree.
:type expected_max: int
:return: Decimal years and normalized cosine/sine coefficient arrays.
:rtype: tuple
:raises ValueError: If SHC metadata or coefficient rows are invalid.
"""
with open(path, encoding="ascii") as stream:
data = (line for line in stream if line.strip() and not line.lstrip().startswith("#"))
nmin, nmax, ntimes, order, step = map(int, next(data).split()[:5])
if (nmin, nmax) != (expected_min, expected_max):
raise ValueError(f"Unexpected CHAOS degree range in {path}: {nmin}-{nmax}")
if (nmin == 1 and (order, step) != (6, 5)) or (nmin == 21 and ntimes != 1):
raise ValueError(f"Unsupported CHAOS snapshot layout in {path}")
times = np.fromstring(next(data), sep=" ")
if times.size != ntimes or not np.all(np.diff(times) > 0):
raise ValueError(f"Invalid CHAOS time axis in {path}")
g = np.zeros((ntimes, nmax + 1, nmax + 1))
h = np.zeros_like(g)
count = 0
seen = set()
for line in data:
values = np.fromstring(line, sep=" ")
if values.size != ntimes + 2:
raise ValueError(f"Malformed CHAOS coefficient row in {path}")
n, signed_m = int(values[0]), int(values[1])
if n < nmin or n > nmax or abs(signed_m) > n or (n, signed_m) in seen:
raise ValueError(f"Invalid CHAOS degree/order in {path}: {(n, signed_m)}")
seen.add((n, signed_m))
if signed_m >= 0:
g[:, n, signed_m] = values[2:]
else:
h[:, n, -signed_m] = values[2:]
count += 1
if count != (nmax + 1) ** 2 - nmin ** 2:
raise ValueError(f"Incomplete CHAOS coefficient file: {path}")
s = _schmidt_table(nmax)
return times, g * s[None, :, :], h * s[None, :, :]
def _chaos_years(dates):
r"""Map UTC dates to CHAOS's 365.25-day decimal year convention.
:param dates: UTC dates as a NumPy datetime array.
:type dates: numpy.ndarray
:return: Decimal years used by the CHAOS SHC snapshots.
:rtype: numpy.ndarray
"""
# ChaosMagPy maps SHC decimal years to MJD2000 using 365.25 days/year.
days = (dates - np.datetime64("2000-01-01T00:00:00", "ns")) / np.timedelta64(1, "D")
return 2000.0 + np.asarray(days, dtype=float) / 365.25
def _segment(times, years):
r"""Locate the degree five polynomial segment for each query date.
:param times: SHC snapshot decimal years.
:type times: numpy.ndarray
:param years: Query dates as CHAOS decimal years.
:type years: numpy.ndarray
:return: First snapshot index for each six-point segment.
:rtype: numpy.ndarray
"""
# Each 6 snapshots define one degree-5 polynomial; adjacent segments
# share the boundary snapshot (SHC N_STEP = 5).
boundaries = times[::5]
return np.clip(np.searchsorted(boundaries, years, side="right") - 1, 0, len(boundaries) - 2) * 5
@njit(cache=True, fastmath=True, nogil=True)
def _weights(times, start, year):
r"""Compute six Lagrange weights inside one CHAOS time segment.
Before the first or after the last snapshot (the segment ``_segment``
picks there is the first or last one), the weights continue the model
linearly: the value at that end plus the end slope times the distance.
This is ChaosMagPy's default (``extrapolate='linear'``).
:param times: SHC snapshot decimal years.
:type times: numpy.ndarray
:param start: First snapshot index of the selected segment.
:type start: int
:param year: Query time as a CHAOS decimal year.
:type year: float
:return: Interpolation weights for the six snapshots.
:rtype: numpy.ndarray
"""
weights = np.empty(6)
if year > times[start + 5]:
edge = 5
elif year < times[start]:
edge = 0
else:
edge = -1
if edge >= 0:
te = times[start + edge]
for j in range(6):
# Derivative of the j-th Lagrange basis polynomial at te.
slope = 0.0
for k in range(6):
if k == j:
continue
term = 1.0 / (times[start + j] - times[start + k])
for m in range(6):
if m != j and m != k:
term *= (te - times[start + m]) / (times[start + j] - times[start + m])
slope += term
weights[j] = (1.0 if j == edge else 0.0) + (year - te) * slope
return weights
for j in range(6):
value = 1.0
for k in range(6):
if k != j:
value *= (year - times[start + k]) / (times[start + j] - times[start + k])
weights[j] = value
return weights
@njit(cache=True, fastmath=True, nogil=True)
def _core_varying(r, theta, phi, times, years, starts, g, h, br, bt, bp):
r"""Interpolate and evaluate degree 20 core fields for paired dates.
Inputs are flat arrays of equal length. Output arrays are filled in place.
:param r: Geocentric radii [km].
:type r: numpy.ndarray
:param theta: Geocentric colatitudes [deg].
:type theta: numpy.ndarray
:param phi: East longitudes [deg].
:type phi: numpy.ndarray
:param times: SHC snapshot decimal years.
:type times: numpy.ndarray
:param years: Query decimal years.
:type years: numpy.ndarray
:param starts: First snapshot index per query.
:type starts: numpy.ndarray
:param g: Core cosine Gauss coefficients [nT].
:type g: numpy.ndarray
:param h: Core sine Gauss coefficients [nT].
:type h: numpy.ndarray
:param br: Output radial components [nT].
:type br: numpy.ndarray
:param bt: Output southward components [nT].
:type bt: numpy.ndarray
:param bp: Output eastward components [nT].
:type bp: numpy.ndarray
:return: None; output arrays are filled in place.
:rtype: None
"""
nmax = 20
pc = np.zeros(nmax + 2); p1 = np.zeros(nmax + 2); p2 = np.zeros(nmax + 2)
dc = np.zeros(nmax + 2); d1 = np.zeros(nmax + 2); d2 = np.zeros(nmax + 2)
cosmp = np.zeros(nmax + 1); sinmp = np.zeros(nmax + 1)
gb = np.zeros((nmax + 1, nmax + 1)); hb = np.zeros_like(gb)
for i in range(r.size):
start = starts[i]
w = _weights(times, start, years[i])
for n in range(1, nmax + 1):
for m in range(n + 1):
gv = 0.0; hv = 0.0
for j in range(6):
gv += w[j] * g[start + j, n, m]
hv += w[j] * h[start + j, n, m]
gb[n, m] = gv; hb[n, m] = hv
br[i], bt[i], bp[i] = _eval_one(
r[i], theta[i], phi[i], gb, hb, nmax,
pc, p1, p2, dc, d1, d2, cosmp, sinmp,
)
[docs]
class CHAOS8(MagneticField):
"""CHAOS-8.7 core plus static lithospheric internal magnetic field.
The two official SHC kernels are downloaded on first use. This evaluates
CHAOS's *internal* field; its external and induced field terms require
additional activity indices and are outside this model's interface.
The core coefficients span about 1997.1 to 2027.1. Outside that span the
core field continues linearly from the nearest end (ChaosMagPy's
default), with a warning; accuracy then degrades with the unmodelled
secular acceleration, roughly as for IGRF's predictive secular
variation.
"""
name = "chaos8"
def __init__(
self,
core_path: str | Path | None = None,
static_path: str | Path | None = None,
*,
include_static: bool = True,
):
r"""Choose the core and static CHAOS coefficient files.
:param core_path: Optional path for the core SHC file.
:type core_path: str or pathlib.Path or None
:param static_path: Optional path for the lithospheric SHC file.
:type static_path: str or pathlib.Path or None
:param include_static: Include degrees 21 through 185 when true.
:type include_static: bool
:return: None
:rtype: None
"""
self.core_path = Path(core_path) if core_path is not None else default_kernel_path("CHAOS-8.7_core.shc")
self.static_path = Path(static_path) if static_path is not None else default_kernel_path("CHAOS-8.7_static.shc")
self.include_static = bool(include_static)
[docs]
def field_gc(self, r, theta, phi, date):
r"""Evaluate the CHAOS-8.7 internal field in spherical coordinates.
:param r: Geocentric radius [km].
:type r: float or numpy.ndarray
:param theta: Geocentric colatitude [deg].
:type theta: float or numpy.ndarray
:param phi: East longitude [deg].
:type phi: float or numpy.ndarray
:param date: One UTC date or one date per position.
:type date: datetime.datetime or sequence
:return: Radial, southward, and eastward components [nT].
:rtype: tuple
:raises ValueError: If the date count does not match the positions.
"""
shape, r, theta, phi, dates = coordinate_dates(r, theta, phi, date)
core_path = ensure_kernel(
self.core_path, "chaos8_core", "a90a67e45d2a4613629d6c37fc9a0418"
)
times, g, h = _read_shc(str(core_path), 1, 20)
years = _chaos_years(dates)
if np.any((years < times[0]) | (years > times[-1])):
warnings.warn(
f"CHAOS-{CHAOS8_VERSION} core coefficients cover {times[0]:.3f} to {times[-1]:.3f}; "
"extrapolating linearly from the nearest end.",
RuntimeWarning,
stacklevel=2,
)
if dates.size == 1 or np.all(years == years[0]):
start = int(_segment(times, years[:1])[0])
weights = _weights(times, start, float(years[0]))
gb = np.tensordot(weights, g[start:start + 6], axes=(0, 0))
hb = np.tensordot(weights, h[start:start + 6], axes=(0, 0))
components = evaluate_static(r, theta, phi, gb, hb)
else:
years = np.ascontiguousarray(years)
if years.size != r.size:
raise ValueError(f"date has {years.size} entries; expected 1 or {r.size}")
starts = np.ascontiguousarray(_segment(times, years), dtype=np.int64)
components = tuple(np.empty(r.size) for _ in range(3))
_core_varying(r, theta, phi, times, years, starts, g, h, *components)
if self.include_static:
static_path = ensure_kernel(
self.static_path, "chaos8_static", "5730a1b3a155a698eae5e2f0b60f2433"
)
_, gs, hs = _read_shc(str(static_path), 21, 185)
static_field = evaluate_static(r, theta, phi, gs[0], hs[0])
components = tuple(core + lith for core, lith in zip(components, static_field))
return shaped_field(shape, components)