Skip to content

hfpytrace.model.rt3d

Package

Profile-first 3D ionospheric ray-tracing module for gridded workflows.

This module provides:

  • 3D profile construction/validation (RT3DProfile)
  • IRI / NRLMSISE / geomag fetch helpers on (lat, lon, alt) grids
  • refractive-index volume construction from dispersion relations
  • Cartesian and spherical oblique tracing (gradient, hamiltonian)
  • helper interpolation/evaluation APIs used by solver kernels

Key Classes

Class RT3DProfile
Class RT3D

Key Methods

Method RT3DProfile.from_cfg() Method RT3DProfile.fetch_iri() Method RT3DProfile.fetch_msise() Method RT3DProfile.fetch_geomag() Method RT3DProfile.force_zero_density_below() Method RT3D.build_refractive_index_interpolators() Method RT3D.trace_cartesian_gradient() Method RT3D.trace_cartesian_hamiltonian() Method RT3D.trace_spherical_gradient() Method RT3D.oblique_trace()

Runtime Notes

  • build_refractive_index_interpolators(...) is the expensive preparation step.
  • Solver calls use the prepared interpolators and return SimpleNamespace outputs with trajectory arrays and summary metrics (group_path_km, group_delay_sec, status, reason).
  • Domain-edge and non-finite refractive-index handling are implemented in the Hamiltonian kernel to reduce NaN-driven failures.

Multi-Hop Ground Reflections

RT3D.oblique_trace accepts an nhops keyword (default 1) to model multiple ionospheric reflections in a single call.

Algorithm

For each hop beyond the first:

  1. The ODE is restarted at the domain left edge (x=0, y=0) so the full n-field grid is available (horizontal-homogeneity assumption).
  2. Output x_km / y_km are offset by the accumulated physical ground-hit position of the previous hop so that concatenated segments form a continuous path.
  3. Specular reflection geometry is applied at each ground hit:
  4. Cartesian: vz → −vz, azimuth = atan2(vy, vx) (unchanged)
  5. Spherical: vr → −vr, azimuth = atan2(vlon, vlat) (unchanged)

Output namespace additions

Attribute Type Description
nhops_completed int Actual hops traced (≤ nhops)
group_path_km float Accumulated across all hops
group_delay_sec float Accumulated across all hops

Usage

# 2-hop trace (one ground reflection)
out = rt.oblique_trace(
    freq_hz=8e6,
    elevation_deg=30.0,
    azimuth_deg=45.0,
    coordinate_system="cartesian",
    nhops=2,
    x0_km=0.0, y0_km=0.0, z0_km=0.0,
    s_max_km=2000.0,
)
print(out.nhops_completed, out.group_path_km)

# 3-hop spherical trace
out3 = rt.oblique_trace(
    freq_hz=8e6,
    elevation_deg=25.0,
    coordinate_system="spherical",
    nhops=3,
    s_max_km=4000.0,
)

Notes

  • If the ray does not reach the ground on hop k (penetrates, hits domain edge, or runs out of s_max_km), the loop stops and nhops_completed < nhops.
  • s_max_km applies independently to each hop — increase it proportionally when requesting multiple hops.
  • The Hamiltonian solver supports nhops for the cartesian coordinate system. Spherical Hamiltonian falls back to the gradient solver automatically.

API

hfpytrace.model.rt3d

3D ionospheric profile assembly and PHaRLAP-driven ray tracing.

Provides a 3D (lat × lon × alt) gridded profile container and a thin wrapper around the PHaRLAP MATLAB engine for full 3D oblique HF ray tracing.

Classes

RT3DProfile Dataclass holding all 3D (nlat × nlon × nalt) ionospheric fields — electron density, neutral atmosphere, geomagnetic field, and collision frequency. Supports IRI, SAMI3, WACCM-X, GEMINI, and GITM density sources through fetch_* methods and a from_cfg factory. RT3D Entry-point that owns an :class:RT3DProfile and drives PHaRLAP ray tracing via the MATLAB engine. Key methods:

* ``build_iono_grids()`` — assemble ``iono_en_grid`` and ``iono_grid_parms``
  ready for ``raytrace_3d`` / ``raytrace_3d_sp``.
* ``build_geomag_grids()`` — assemble ``Bx``, ``By``, ``Bz``, and
  ``geomag_grid_parms`` arrays.
* ``raytrace(engine, ...)`` — call PHaRLAP through :class:`~hfpytrace.pharlap.Engine`
  and return ``(ray_data, ray_path_data, ray_state_vec)``.

Collision types

Supported collision_type strings for :meth:RT3D.fetch_collision: "FT" (Friedrich-Tonker), "FT_CC", "FT_MB", "SN_EN", "SN_EI", "SN" (full Schunk-Nagy), "ATM".

Typical usage

from hfpytrace.model import RT3D, RT3DProfile from hfpytrace.pharlap import Engine profile = RT3DProfile.from_cfg(cfg, fetch_iri=True, fetch_geomag=True) rt = RT3D(profile=profile) engine = Engine() ray_data, path_data, state = rt.raytrace(engine, elevs=[15, 30, 45, 60], nhops=2) engine.close()

RT3DProfile dataclass

3D gridded ionosphere/background container.

Axis convention: - lats: latitude axis, shape (nlat,) - lons: longitude axis, shape (nlon,) - alts_km: altitude axis, shape (nalt,) - 3D fields use shape (nlat, nlon, nalt)

Source code in hfpytrace/model/rt3d.py
@dataclass
class RT3DProfile:
    """
    3D gridded ionosphere/background container.

    Axis convention:
    - ``lats``: latitude axis, shape ``(nlat,)``
    - ``lons``: longitude axis, shape ``(nlon,)``
    - ``alts_km``: altitude axis, shape ``(nalt,)``
    - 3D fields use shape ``(nlat, nlon, nalt)``
    """

    lats: np.ndarray
    lons: np.ndarray
    alts_km: np.ndarray
    time: dt.datetime
    ne_m3: np.ndarray | None = None
    ne_cm3: np.ndarray | None = None
    source: str = "iri"
    msise: SimpleNamespace | None = None
    geomag: SimpleNamespace | None = None
    collision: object | None = (
        None  # ComputeCollision instance after compute_collision()
    )

    def __post_init__(self) -> None:
        self.lats = np.asarray(self.lats, dtype=float).ravel()
        self.lons = np.asarray(self.lons, dtype=float).ravel()
        self.alts_km = np.asarray(self.alts_km, dtype=float).ravel()
        if not isinstance(self.time, dt.datetime):
            self.time = dt.datetime.fromisoformat(str(self.time))
        self.validate()

    def validate(self) -> None:
        if self.lats.size < 2 or self.lons.size < 2 or self.alts_km.size < 2:
            raise ValueError("lats, lons, alts_km must each contain at least 2 points")
        if not np.all(np.diff(self.lats) > 0):
            raise ValueError("lats must be strictly increasing")
        if not np.all(np.diff(self.lons) > 0):
            raise ValueError("lons must be strictly increasing")
        if not np.all(np.diff(self.alts_km) > 0):
            raise ValueError("alts_km must be strictly increasing")

        shape = (self.lats.size, self.lons.size, self.alts_km.size)
        if self.ne_m3 is not None:
            ne = np.asarray(self.ne_m3, dtype=float)
            if ne.shape != shape:
                raise ValueError(f"ne_m3 must have shape {shape}")
            if np.any(ne < 0):
                raise ValueError("ne_m3 must be non-negative")
            self.ne_m3 = ne
            self.ne_cm3 = ne * 1e-6
        elif self.ne_cm3 is not None:
            ne = np.asarray(self.ne_cm3, dtype=float)
            if ne.shape != shape:
                raise ValueError(f"ne_cm3 must have shape {shape}")
            if np.any(ne < 0):
                raise ValueError("ne_cm3 must be non-negative")
            self.ne_cm3 = ne
            self.ne_m3 = ne * 1e6

        if self.msise is not None:
            for k in ("N2", "O2", "O", "H", "He", "Tn"):
                if not hasattr(self.msise, k):
                    raise ValueError(f"msise missing required field: {k}")
                arr = np.asarray(getattr(self.msise, k), dtype=float)
                if arr.shape != shape:
                    raise ValueError(f"msise.{k} must have shape {shape}")
                setattr(self.msise, k, arr)

        if self.geomag is not None:
            for k in ("Bx", "By", "Bz", "bmag_t", "inc_deg", "psi_deg"):
                if not hasattr(self.geomag, k):
                    raise ValueError(f"geomag missing required field: {k}")
                arr = np.asarray(getattr(self.geomag, k), dtype=float)
                if arr.shape != shape:
                    raise ValueError(f"geomag.{k} must have shape {shape}")
                setattr(self.geomag, k, arr)

    @staticmethod
    def _axis_from_cfg(start: float, step: float, count: int, name: str) -> np.ndarray:
        n = int(count)
        if n < 2:
            raise ValueError(f"{name} count must be >= 2")
        return float(start) + float(step) * np.arange(n, dtype=float)

    @classmethod
    def from_cfg(
        cls,
        cfg,
        time: dt.datetime | None = None,
        lats: np.ndarray | None = None,
        lons: np.ndarray | None = None,
        alts_km: np.ndarray | None = None,
        fetch_iri: bool = True,
        fetch_msise: bool = False,
        fetch_geomag: bool = False,
        workers: int = 1,
    ) -> "RT3DProfile":
        """
        Build a profile from explicit axes or config-driven 3D grid settings.

        Grid source priority:
        1) explicit lats/lons/alts_km
        2) ``cfg.iono_grid`` fields
        3) fallback from global 2D-style height settings and coarse CONUS-like lat/lon grid
        """
        t = time if time is not None else dt.datetime.fromisoformat(str(cfg.event))

        if lats is None or lons is None or alts_km is None:
            if hasattr(cfg, "iono_grid"):
                ig = cfg.iono_grid
                lats = cls._axis_from_cfg(
                    start=float(ig.lat_start),
                    step=float(ig.lat_step),
                    count=int(ig.num_lats),
                    name="lat",
                )
                lons = cls._axis_from_cfg(
                    start=float(ig.lon_start),
                    step=float(ig.lon_step),
                    count=int(ig.num_lons),
                    name="lon",
                )
                alts_km = cls._axis_from_cfg(
                    start=float(ig.height_start_km),
                    step=float(ig.height_step_km),
                    count=int(ig.num_heights),
                    name="height",
                )
            else:
                logger.warning(
                    "cfg.iono_grid not found; using fallback lat/lon axes and cfg height settings."
                )
                lats = np.linspace(24.0, 50.0, 53)
                lons = np.linspace(-125.0, -66.0, 119)
                h0 = float(getattr(cfg, "start_height_km", 100.0))
                h1 = float(getattr(cfg, "end_height_km", 500.0))
                dh = float(getattr(cfg, "height_incriment_km", 5.0))
                alts_km = np.arange(h0, h1, dh, dtype=float)

        p = cls(
            lats=np.asarray(lats, dtype=float).ravel(),
            lons=np.asarray(lons, dtype=float).ravel(),
            alts_km=np.asarray(alts_km, dtype=float).ravel(),
            time=t,
        )
        logger.info(
            "RT3DProfile created: nlat={}, nlon={}, nalt={}",
            p.lats.size,
            p.lons.size,
            p.alts_km.size,
        )
        if fetch_iri:
            p.fetch_iri(cfg=cfg, workers=int(workers))
        if fetch_msise:
            p.fetch_msise(workers=int(workers))
        if fetch_geomag:
            gm_cfg = getattr(cfg, "geomag_grid", SimpleNamespace(coord_input="GEO"))
            p.fetch_geomag(
                coord_input=str(getattr(gm_cfg, "coord_input", "GEO")),
                coeff_dir=getattr(gm_cfg, "coeff_dir", None),
            )
        p.validate()
        return p

    def set_electron_density(
        self,
        ne_m3: np.ndarray | None = None,
        ne_cm3: np.ndarray | None = None,
        source: str = "iri",
    ) -> None:
        if (ne_m3 is None) == (ne_cm3 is None):
            raise ValueError("Provide exactly one of ne_m3 or ne_cm3")
        self.source = str(source)
        if ne_m3 is not None:
            self.ne_m3 = np.asarray(ne_m3, dtype=float)
            self.ne_cm3 = self.ne_m3 * 1e-6
        else:
            self.ne_cm3 = np.asarray(ne_cm3, dtype=float)
            self.ne_m3 = self.ne_cm3 * 1e6
        self.validate()

    def force_zero_density_below(self, min_alt_km: float) -> int:
        """Set all density values to zero for ``alt < min_alt_km``."""
        if self.ne_m3 is None or self.ne_cm3 is None:
            raise ValueError(
                "Electron density is not initialized; call fetch_iri() or set_electron_density() first."
            )
        below = np.asarray(self.alts_km, dtype=float) < float(min_alt_km)
        n_rows = int(np.count_nonzero(below))
        if n_rows == 0:
            return 0
        self.ne_m3[:, :, below] = 0.0
        self.ne_cm3[:, :, below] = 0.0
        self.validate()
        return n_rows

    def fetch_iri(self, cfg, workers: int = 1) -> np.ndarray:
        logger.info(
            "Fetching 3D IRI profile: nlat={}, nlon={}, nalt={}",
            self.lats.size,
            self.lons.size,
            self.alts_km.size,
        )
        model = IRI3d(cfg, self.time)
        ne_cm3, _ = model.fetch_dataset(
            time=self.time,
            lats=self.lats,
            lons=self.lons,
            alts=self.alts_km,
            workers=int(workers),
        )
        self.ne_cm3 = np.asarray(ne_cm3, dtype=float)
        self.ne_m3 = self.ne_cm3 * 1e6
        self.source = "iri"
        self.validate()
        return self.ne_m3

    def fetch_msise(
        self,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ) -> SimpleNamespace:
        logger.info(
            "Fetching 3D NRLMSISE profile: nlat={}, nlon={}, nalt={}, workers={}",
            self.lats.size,
            self.lons.size,
            self.alts_km.size,
            int(workers),
        )
        ms = NRLMSISE3D(
            date=self.time,
            lats=self.lats,
            lons=self.lons,
            heights_km=self.alts_km,
            workers=int(workers),
            update_spaceweather=bool(update_spaceweather),
            suppress_spaceweather_warning=bool(suppress_spaceweather_warning),
        ).msise
        self.msise = SimpleNamespace(
            N2=np.asarray(ms["N2"], dtype=float),
            O2=np.asarray(ms["O2"], dtype=float),
            O=np.asarray(ms["O"], dtype=float),
            H=np.asarray(ms["H"], dtype=float),
            He=np.asarray(ms["He"], dtype=float),
            Tn=np.asarray(ms["Tn"], dtype=float),
            t_nn=np.asarray(ms["t_nn"], dtype=float),
        )
        self.validate()
        return self.msise

    def fetch_geomag(
        self,
        coord_input: str = "GEO",
        coeff_dir: str | None = None,
    ) -> SimpleNamespace:
        logger.info(
            "Fetching 3D geomag profile: nlat={}, nlon={}, nalt={}",
            self.lats.size,
            self.lons.size,
            self.alts_km.size,
        )
        gm = build_geomag_grid(
            lats=self.lats,
            lons=self.lons,
            alts_km=self.alts_km,
            time=self.time,
            coord_input=coord_input,
            coeff_dir=coeff_dir,
        )
        self.geomag = SimpleNamespace(
            Bx=np.asarray(gm.Bx, dtype=float),
            By=np.asarray(gm.By, dtype=float),
            Bz=np.asarray(gm.Bz, dtype=float),
            bmag_t=np.asarray(gm.bmag_t, dtype=float),
            inc_deg=np.asarray(gm.inc_deg, dtype=float),
            dec_deg=np.asarray(gm.dec_deg, dtype=float),
            psi_deg=np.asarray(gm.psi_deg, dtype=float),
            lat_geo=np.asarray(gm.lat_geo, dtype=float),
            lon_geo=np.asarray(gm.lon_geo, dtype=float),
            qd=gm.qd,
            apex=gm.apex,
        )
        self.validate()
        return self.geomag

    def compute_collision(
        self,
        Te: np.ndarray | float | None = None,
        Ti: np.ndarray | float | None = None,
        edens: np.ndarray | None = None,
        O2p: np.ndarray | None = None,
        Op: np.ndarray | None = None,
    ) -> object:
        """
        Compute collision frequencies using the already-fetched MSIS neutral data.

        Requires ``self.msise`` (call ``fetch_msise()`` first) and electron
        density (call ``fetch_iri()`` or ``set_electron_density()`` first).

        Parameters
        ----------
        Te, Ti : array-like or float, optional
            Electron/ion temperature [K], shape (nlat, nlon, nalt) or broadcastable.
            Defaults to MSIS neutral temperature Tn.
        edens : array-like, optional
            Electron density [cm^-3], shape (nlat, nlon, nalt).
            Defaults to ``self.ne_cm3``.
        O2p, Op : array-like, optional
            O2+ and O+ densities [cm^-3]. Defaults to 10%/90% of edens.

        Returns
        -------
        ComputeCollision
            Also stored on ``self.collision`` for retrieval via
            ``collision_type`` in :class:`RT3D`.

        Notes
        -----
        Supported ``collision_type`` keys:

        +-------------+--------------------------------------------------+
        | Key         | Model                                            |
        +=============+==================================================+
        | ``"FT"``    | Friedrich-Tonker (ν_ft, a=1.0)                   |
        | ``"FT_cc"`` | Friedrich-Tonker (ν_av_cc, a=2.5)                |
        | ``"FT_mb"`` | Friedrich-Tonker (ν_av_mb, a=1.5)                |
        | ``"SN_en"`` | Schunk-Nagy electron-neutral total               |
        | ``"SN_ei"`` | Schunk-Nagy electron-ion total                   |
        | ``"SN"``    | Schunk-Nagy full (en + ei)                       |
        | ``"atm"``   | Atmospheric ion-neutral approximation            |
        +-------------+--------------------------------------------------+
        """
        from hfpytrace.collision import ComputeCollision

        if self.msise is None:
            raise ValueError(
                "MSIS neutral data not available. Call fetch_msise() first."
            )
        if self.ne_cm3 is None:
            raise ValueError(
                "Electron density not set. "
                "Call fetch_iri() or set_electron_density() first."
            )

        Tn = np.asarray(self.msise.Tn, dtype=float)  # shape (nlat, nlon, nalt)
        ne = np.asarray(self.ne_cm3, dtype=float)

        Te_use = np.asarray(Te, dtype=float) if Te is not None else Tn.copy()
        Ti_use = np.asarray(Ti, dtype=float) if Ti is not None else Tn.copy()
        edens_use = np.asarray(edens, dtype=float) if edens is not None else ne.copy()
        Op_use = np.asarray(Op, dtype=float) if Op is not None else 0.9 * ne
        O2p_use = np.asarray(O2p, dtype=float) if O2p is not None else 0.1 * ne

        cc = ComputeCollision(
            Te=Te_use,
            Ti=Ti_use,
            Tn=Tn,
            edens=edens_use,
            O2p=O2p_use,
            Op=Op_use,
            N2=np.asarray(self.msise.N2, dtype=float),
            O2=np.asarray(self.msise.O2, dtype=float),
            O=np.asarray(self.msise.O, dtype=float),
            H=np.asarray(self.msise.H, dtype=float),
            He=np.asarray(self.msise.He, dtype=float),
            date=self.time,
        )
        self.collision = cc
        logger.info(
            "3D collision computed: nu_ft=[{:.3e},{:.3e}] Hz, nu_sn=[{:.3e},{:.3e}] Hz",
            float(np.nanmin(cc.collision.nu_ft)),
            float(np.nanmax(cc.collision.nu_ft)),
            float(np.nanmin(cc.collision.nu_sn.total)),
            float(np.nanmax(cc.collision.nu_sn.total)),
        )
        return cc

from_cfg(cfg, time=None, lats=None, lons=None, alts_km=None, fetch_iri=True, fetch_msise=False, fetch_geomag=False, workers=1) classmethod

Build a profile from explicit axes or config-driven 3D grid settings.

Grid source priority: 1) explicit lats/lons/alts_km 2) cfg.iono_grid fields 3) fallback from global 2D-style height settings and coarse CONUS-like lat/lon grid

Source code in hfpytrace/model/rt3d.py
@classmethod
def from_cfg(
    cls,
    cfg,
    time: dt.datetime | None = None,
    lats: np.ndarray | None = None,
    lons: np.ndarray | None = None,
    alts_km: np.ndarray | None = None,
    fetch_iri: bool = True,
    fetch_msise: bool = False,
    fetch_geomag: bool = False,
    workers: int = 1,
) -> "RT3DProfile":
    """
    Build a profile from explicit axes or config-driven 3D grid settings.

    Grid source priority:
    1) explicit lats/lons/alts_km
    2) ``cfg.iono_grid`` fields
    3) fallback from global 2D-style height settings and coarse CONUS-like lat/lon grid
    """
    t = time if time is not None else dt.datetime.fromisoformat(str(cfg.event))

    if lats is None or lons is None or alts_km is None:
        if hasattr(cfg, "iono_grid"):
            ig = cfg.iono_grid
            lats = cls._axis_from_cfg(
                start=float(ig.lat_start),
                step=float(ig.lat_step),
                count=int(ig.num_lats),
                name="lat",
            )
            lons = cls._axis_from_cfg(
                start=float(ig.lon_start),
                step=float(ig.lon_step),
                count=int(ig.num_lons),
                name="lon",
            )
            alts_km = cls._axis_from_cfg(
                start=float(ig.height_start_km),
                step=float(ig.height_step_km),
                count=int(ig.num_heights),
                name="height",
            )
        else:
            logger.warning(
                "cfg.iono_grid not found; using fallback lat/lon axes and cfg height settings."
            )
            lats = np.linspace(24.0, 50.0, 53)
            lons = np.linspace(-125.0, -66.0, 119)
            h0 = float(getattr(cfg, "start_height_km", 100.0))
            h1 = float(getattr(cfg, "end_height_km", 500.0))
            dh = float(getattr(cfg, "height_incriment_km", 5.0))
            alts_km = np.arange(h0, h1, dh, dtype=float)

    p = cls(
        lats=np.asarray(lats, dtype=float).ravel(),
        lons=np.asarray(lons, dtype=float).ravel(),
        alts_km=np.asarray(alts_km, dtype=float).ravel(),
        time=t,
    )
    logger.info(
        "RT3DProfile created: nlat={}, nlon={}, nalt={}",
        p.lats.size,
        p.lons.size,
        p.alts_km.size,
    )
    if fetch_iri:
        p.fetch_iri(cfg=cfg, workers=int(workers))
    if fetch_msise:
        p.fetch_msise(workers=int(workers))
    if fetch_geomag:
        gm_cfg = getattr(cfg, "geomag_grid", SimpleNamespace(coord_input="GEO"))
        p.fetch_geomag(
            coord_input=str(getattr(gm_cfg, "coord_input", "GEO")),
            coeff_dir=getattr(gm_cfg, "coeff_dir", None),
        )
    p.validate()
    return p

force_zero_density_below(min_alt_km)

Set all density values to zero for alt < min_alt_km.

Source code in hfpytrace/model/rt3d.py
def force_zero_density_below(self, min_alt_km: float) -> int:
    """Set all density values to zero for ``alt < min_alt_km``."""
    if self.ne_m3 is None or self.ne_cm3 is None:
        raise ValueError(
            "Electron density is not initialized; call fetch_iri() or set_electron_density() first."
        )
    below = np.asarray(self.alts_km, dtype=float) < float(min_alt_km)
    n_rows = int(np.count_nonzero(below))
    if n_rows == 0:
        return 0
    self.ne_m3[:, :, below] = 0.0
    self.ne_cm3[:, :, below] = 0.0
    self.validate()
    return n_rows

compute_collision(Te=None, Ti=None, edens=None, O2p=None, Op=None)

Compute collision frequencies using the already-fetched MSIS neutral data.

Requires self.msise (call fetch_msise() first) and electron density (call fetch_iri() or set_electron_density() first).

Parameters

Te, Ti : array-like or float, optional Electron/ion temperature [K], shape (nlat, nlon, nalt) or broadcastable. Defaults to MSIS neutral temperature Tn.

array-like, optional

Electron density [cm^-3], shape (nlat, nlon, nalt). Defaults to self.ne_cm3.

O2p, Op : array-like, optional O2+ and O+ densities [cm^-3]. Defaults to 10%/90% of edens.

Returns

ComputeCollision Also stored on self.collision for retrieval via collision_type in :class:RT3D.

Notes

Supported collision_type keys:

+-------------+--------------------------------------------------+ | Key | Model | +=============+==================================================+ | "FT" | Friedrich-Tonker (ν_ft, a=1.0) | | "FT_cc" | Friedrich-Tonker (ν_av_cc, a=2.5) | | "FT_mb" | Friedrich-Tonker (ν_av_mb, a=1.5) | | "SN_en" | Schunk-Nagy electron-neutral total | | "SN_ei" | Schunk-Nagy electron-ion total | | "SN" | Schunk-Nagy full (en + ei) | | "atm" | Atmospheric ion-neutral approximation | +-------------+--------------------------------------------------+

Source code in hfpytrace/model/rt3d.py
def compute_collision(
    self,
    Te: np.ndarray | float | None = None,
    Ti: np.ndarray | float | None = None,
    edens: np.ndarray | None = None,
    O2p: np.ndarray | None = None,
    Op: np.ndarray | None = None,
) -> object:
    """
    Compute collision frequencies using the already-fetched MSIS neutral data.

    Requires ``self.msise`` (call ``fetch_msise()`` first) and electron
    density (call ``fetch_iri()`` or ``set_electron_density()`` first).

    Parameters
    ----------
    Te, Ti : array-like or float, optional
        Electron/ion temperature [K], shape (nlat, nlon, nalt) or broadcastable.
        Defaults to MSIS neutral temperature Tn.
    edens : array-like, optional
        Electron density [cm^-3], shape (nlat, nlon, nalt).
        Defaults to ``self.ne_cm3``.
    O2p, Op : array-like, optional
        O2+ and O+ densities [cm^-3]. Defaults to 10%/90% of edens.

    Returns
    -------
    ComputeCollision
        Also stored on ``self.collision`` for retrieval via
        ``collision_type`` in :class:`RT3D`.

    Notes
    -----
    Supported ``collision_type`` keys:

    +-------------+--------------------------------------------------+
    | Key         | Model                                            |
    +=============+==================================================+
    | ``"FT"``    | Friedrich-Tonker (ν_ft, a=1.0)                   |
    | ``"FT_cc"`` | Friedrich-Tonker (ν_av_cc, a=2.5)                |
    | ``"FT_mb"`` | Friedrich-Tonker (ν_av_mb, a=1.5)                |
    | ``"SN_en"`` | Schunk-Nagy electron-neutral total               |
    | ``"SN_ei"`` | Schunk-Nagy electron-ion total                   |
    | ``"SN"``    | Schunk-Nagy full (en + ei)                       |
    | ``"atm"``   | Atmospheric ion-neutral approximation            |
    +-------------+--------------------------------------------------+
    """
    from hfpytrace.collision import ComputeCollision

    if self.msise is None:
        raise ValueError(
            "MSIS neutral data not available. Call fetch_msise() first."
        )
    if self.ne_cm3 is None:
        raise ValueError(
            "Electron density not set. "
            "Call fetch_iri() or set_electron_density() first."
        )

    Tn = np.asarray(self.msise.Tn, dtype=float)  # shape (nlat, nlon, nalt)
    ne = np.asarray(self.ne_cm3, dtype=float)

    Te_use = np.asarray(Te, dtype=float) if Te is not None else Tn.copy()
    Ti_use = np.asarray(Ti, dtype=float) if Ti is not None else Tn.copy()
    edens_use = np.asarray(edens, dtype=float) if edens is not None else ne.copy()
    Op_use = np.asarray(Op, dtype=float) if Op is not None else 0.9 * ne
    O2p_use = np.asarray(O2p, dtype=float) if O2p is not None else 0.1 * ne

    cc = ComputeCollision(
        Te=Te_use,
        Ti=Ti_use,
        Tn=Tn,
        edens=edens_use,
        O2p=O2p_use,
        Op=Op_use,
        N2=np.asarray(self.msise.N2, dtype=float),
        O2=np.asarray(self.msise.O2, dtype=float),
        O=np.asarray(self.msise.O, dtype=float),
        H=np.asarray(self.msise.H, dtype=float),
        He=np.asarray(self.msise.He, dtype=float),
        date=self.time,
    )
    self.collision = cc
    logger.info(
        "3D collision computed: nu_ft=[{:.3e},{:.3e}] Hz, nu_sn=[{:.3e},{:.3e}] Hz",
        float(np.nanmin(cc.collision.nu_ft)),
        float(np.nanmax(cc.collision.nu_ft)),
        float(np.nanmin(cc.collision.nu_sn.total)),
        float(np.nanmax(cc.collision.nu_sn.total)),
    )
    return cc

RT3D

Minimal RT3D container for downstream 3D tracing implementations.

This class currently focuses on profile management and data integrity checks.

Source code in hfpytrace/model/rt3d.py
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
class RT3D:
    """
    Minimal RT3D container for downstream 3D tracing implementations.

    This class currently focuses on profile management and data integrity checks.
    """

    _VALID_COLLISION_TYPES: frozenset[str] = frozenset(
        {"FT", "FT_CC", "FT_MB", "SN_EN", "SN_EI", "SN", "ATM"}
    )

    @staticmethod
    def _extract_collision_hz(cc, collision_type: str) -> np.ndarray:
        """
        Extract a collision-frequency array from a ``ComputeCollision`` object.

        The returned array has the same shape as the 3D profile fields
        ``(nlat, nlon, nalt)`` and can be sliced/interpolated for ray tracing.

        Parameters
        ----------
        cc : ComputeCollision
        collision_type : str
            One of ``"FT"``, ``"FT_cc"``, ``"FT_mb"``, ``"SN_en"``,
            ``"SN_ei"``, ``"SN"``, ``"atm"`` (case-insensitive).
        """
        ct = str(collision_type).strip().upper()
        _map = {
            "FT": lambda c: np.asarray(c.collision.nu_ft, dtype=float),
            "FT_CC": lambda c: np.asarray(c.collision.nu_av_cc, dtype=float),
            "FT_MB": lambda c: np.asarray(c.collision.nu_av_mb, dtype=float),
            "SN_EN": lambda c: np.asarray(c.collision.nu_sn.en.total, dtype=float),
            "SN_EI": lambda c: np.asarray(c.collision.nu_sn.ei.total, dtype=float),
            "SN": lambda c: np.asarray(c.collision.nu_sn.total, dtype=float),
            "ATM": lambda c: np.asarray(
                c.atmospheric_ion_neutral_collision_frequency(), dtype=float
            ),
        }
        if ct not in _map:
            raise ValueError(
                f"Unknown collision_type '{collision_type}'. "
                f"Valid options: {sorted(_map.keys())}"
            )
        return _map[ct](cc)

    def fetch_collision(
        self,
        Te: np.ndarray | float | None = None,
        Ti: np.ndarray | float | None = None,
        edens: np.ndarray | None = None,
        O2p: np.ndarray | None = None,
        Op: np.ndarray | None = None,
    ) -> object:
        """
        Compute and attach collision frequencies to the profile.

        Convenience wrapper around :meth:`RT3DProfile.compute_collision`.
        Requires that ``fetch_msise()`` has been called on the profile.

        Returns
        -------
        ComputeCollision
        """
        return self.profile.compute_collision(
            Te=Te,
            Ti=Ti,
            edens=edens,
            O2p=O2p,
            Op=Op,
        )

    def __init__(
        self,
        *,
        profile: RT3DProfile | None = None,
        cfg=None,
        time: dt.datetime | str | None = None,
        lats: np.ndarray | None = None,
        lons: np.ndarray | None = None,
        alts_km: np.ndarray | None = None,
        ne_m3: np.ndarray | None = None,
        ne_cm3: np.ndarray | None = None,
        source: str = "iri",
        fetch_iri: bool = False,
        fetch_msise: bool = False,
        fetch_geomag: bool = False,
        workers: int = 1,
    ):
        if profile is not None:
            if not isinstance(profile, RT3DProfile):
                raise TypeError("profile must be an RT3DProfile")
            profile.validate()
            self.profile = profile
        else:
            if cfg is None:
                raise ValueError("Provide profile or cfg for RT3D initialization")
            t = time if time is not None else dt.datetime.fromisoformat(str(cfg.event))
            self.profile = RT3DProfile.from_cfg(
                cfg=cfg,
                time=t,
                lats=lats,
                lons=lons,
                alts_km=alts_km,
                fetch_iri=bool(fetch_iri),
                fetch_msise=bool(fetch_msise),
                fetch_geomag=bool(fetch_geomag),
                workers=int(workers),
            )

        if (ne_m3 is not None) or (ne_cm3 is not None):
            self.profile.set_electron_density(ne_m3=ne_m3, ne_cm3=ne_cm3, source=source)
        self.profile.validate()
        if self.profile.ne_m3 is None:
            logger.warning(
                "RT3D initialized without electron density; set ne_m3/ne_cm3 or fetch_iri=True."
            )
        logger.info(
            "RT3D initialized: nlat={}, nlon={}, nalt={}, source={}",
            self.profile.lats.size,
            self.profile.lons.size,
            self.profile.alts_km.size,
            self.profile.source,
        )
        # Cache for expensive refractive-index/interpolator construction.
        self._interp_cache_key = None
        self._interp_cache_out = None

    @property
    def lats(self) -> np.ndarray:
        return self.profile.lats

    @property
    def lons(self) -> np.ndarray:
        return self.profile.lons

    @property
    def alts_km(self) -> np.ndarray:
        return self.profile.alts_km

    @property
    def ne_m3(self) -> np.ndarray | None:
        return self.profile.ne_m3

    @staticmethod
    def _resolve_dispersion_model_name(formulation: str) -> str:
        name = str(formulation).strip().lower().replace("_", "-")
        alias_map = {
            "appleton": "appleton-hartree",
            "appleton-hartree": "appleton-hartree",
            "ah": "appleton-hartree",
            "senwyller": "sen-wyller",
            "sen-wyller": "sen-wyller",
            "sw": "sen-wyller",
        }
        if name not in alias_map:
            raise ValueError(
                "Unsupported dispersion model. Use 'appleton-hartree' or 'sen-wyller'."
            )
        return alias_map[name]

    def _build_local_xy_axes(self) -> tuple[np.ndarray, np.ndarray, float, float]:
        lat0 = float(np.mean(self.lats))
        lon0 = float(np.mean(self.lons))
        km_per_deg_lat = 111.32
        km_per_deg_lon = km_per_deg_lat * np.cos(np.deg2rad(lat0))
        x_km = (np.asarray(self.lons, dtype=float) - lon0) * km_per_deg_lon
        y_km = (np.asarray(self.lats, dtype=float) - lat0) * km_per_deg_lat
        return x_km, y_km, lat0, lon0

    def build_refractive_index_interpolators(
        self,
        freq_hz: float,
        b_abs_t: np.ndarray | float | None = None,
        b_psi_deg: np.ndarray | float | None = None,
        collision_hz: np.ndarray | float | None = None,
        mode: str = "O",
        formulation: str = "appleton-hartree",
    ) -> SimpleNamespace:
        cache_key = (
            float(freq_hz),
            str(mode),
            str(formulation),
            id(b_abs_t) if b_abs_t is not None else None,
            id(b_psi_deg) if b_psi_deg is not None else None,
            id(collision_hz) if collision_hz is not None else None,
            id(self.profile.ne_m3),
        )
        if self._interp_cache_key == cache_key and self._interp_cache_out is not None:
            return self._interp_cache_out

        if self.ne_m3 is None:
            raise ValueError("RT3D profile has no electron density.")
        ne = np.asarray(self.ne_m3, dtype=float)
        shape = ne.shape
        model_name = self._resolve_dispersion_model_name(formulation)

        if b_abs_t is None:
            if self.profile.geomag is not None:
                b_t = np.asarray(self.profile.geomag.bmag_t, dtype=float)
            else:
                b_t = np.zeros(shape, dtype=float)
        else:
            b_t = np.asarray(b_abs_t, dtype=float)
            if b_t.ndim == 0:
                b_t = np.full(shape, float(b_t), dtype=float)
        if b_psi_deg is None:
            if self.profile.geomag is not None:
                theta = np.asarray(self.profile.geomag.psi_deg, dtype=float)
            else:
                theta = np.zeros(shape, dtype=float)
        else:
            theta = np.asarray(b_psi_deg, dtype=float)
            if theta.ndim == 0:
                theta = np.full(shape, float(theta), dtype=float)
        if collision_hz is None:
            nu = np.zeros(shape, dtype=float)
        else:
            nu = np.asarray(collision_hz, dtype=float)
            if nu.ndim == 0:
                nu = np.full(shape, float(nu), dtype=float)
            if nu.shape != shape:
                raise ValueError(f"collision_hz must have shape {shape}")

        if model_name == "appleton-hartree":
            disp = AppletonHartreeDispersion(
                frequency_hz=float(freq_hz),
                ne_m3=ne,
                collision_hz=nu,
                b_t=b_t,
                theta_deg=theta,
            )
        else:
            disp = SenWyllerDispersion(
                frequency_hz=float(freq_hz),
                ne_m3=ne,
                collision_hz=nu,
                b_t=b_t,
                theta_deg=theta,
            )

        n_complex = disp.refractive_index(mode=mode)
        n = np.real(n_complex)
        # Harden against singular/invalid dispersion outputs.
        n = np.where(np.isfinite(n), np.clip(n, 0.0, None), np.nan)
        if np.any(~np.isfinite(n)):
            n = np.nan_to_num(n, nan=0.0, posinf=0.0, neginf=0.0)
        n = np.clip(n, N_FLOOR, None)
        mup = 1.0 / np.clip(n, N_FLOOR, None)

        # 3D interpolators on physical local axes (z, y, x).
        x_km, y_km, lat_ref_deg, lon_ref_deg = self._build_local_xy_axes()
        z_km = np.asarray(self.alts_km, dtype=float)
        n_zyx = np.transpose(n, (2, 0, 1))
        mup_zyx = np.transpose(mup, (2, 0, 1))
        dn_dz, dn_dy, dn_dx = np.gradient(n_zyx, z_km, y_km, x_km, edge_order=2)

        self._x_km = x_km
        self._y_km = y_km
        self._z_km = z_km
        self._lat_ref_deg = lat_ref_deg
        self._lon_ref_deg = lon_ref_deg

        self._n_interp_zyx = RegularGridInterpolator(
            (z_km, y_km, x_km), n_zyx, bounds_error=False, fill_value=np.nan
        )
        self._mup_interp_zyx = RegularGridInterpolator(
            (z_km, y_km, x_km), mup_zyx, bounds_error=False, fill_value=np.nan
        )
        self._dn_dx_interp_zyx = RegularGridInterpolator(
            (z_km, y_km, x_km), dn_dx, bounds_error=False, fill_value=np.nan
        )
        self._dn_dy_interp_zyx = RegularGridInterpolator(
            (z_km, y_km, x_km), dn_dy, bounds_error=False, fill_value=np.nan
        )
        self._dn_dz_interp_zyx = RegularGridInterpolator(
            (z_km, y_km, x_km), dn_dz, bounds_error=False, fill_value=np.nan
        )

        # Also keep altitude-lat-lon interpolators for spherical mode.
        self._n_interp_altll = RegularGridInterpolator(
            (self.alts_km, self.lats, self.lons),
            np.transpose(n, (2, 0, 1)),
            bounds_error=False,
            fill_value=np.nan,
        )
        self._mup_interp_altll = RegularGridInterpolator(
            (self.alts_km, self.lats, self.lons),
            np.transpose(mup, (2, 0, 1)),
            bounds_error=False,
            fill_value=np.nan,
        )
        logger.info(
            "RT3D refractive index interpolators ready: freq={} Hz, mode={}, model={}",
            float(freq_hz),
            mode,
            model_name,
        )
        out = SimpleNamespace(n=n, mup=mup)
        self._interp_cache_key = cache_key
        self._interp_cache_out = out
        return out

    def _eval_n_grad_cart(
        self, x_km: np.ndarray, y_km: np.ndarray, z_km: np.ndarray
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        x = np.atleast_1d(np.asarray(x_km, dtype=float))
        y = np.atleast_1d(np.asarray(y_km, dtype=float))
        z = np.atleast_1d(np.asarray(z_km, dtype=float))
        x, y, z = np.broadcast_arrays(x, y, z)
        if hasattr(self, "_x_km") and hasattr(self, "_y_km") and hasattr(self, "_z_km"):
            eps = 1e-6
            x = np.clip(x, float(self._x_km[0]) + eps, float(self._x_km[-1]) - eps)
            y = np.clip(y, float(self._y_km[0]) + eps, float(self._y_km[-1]) - eps)
            z = np.clip(z, float(self._z_km[0]) + eps, float(self._z_km[-1]) - eps)
        pts = np.column_stack([z.ravel(), y.ravel(), x.ravel()])
        n = self._n_interp_zyx(pts).reshape(x.shape)
        dnx = self._dn_dx_interp_zyx(pts).reshape(x.shape)
        dny = self._dn_dy_interp_zyx(pts).reshape(x.shape)
        dnz = self._dn_dz_interp_zyx(pts).reshape(x.shape)
        return n, dnx, dny, dnz

    def _eval_mup_cart(
        self, x_km: np.ndarray, y_km: np.ndarray, z_km: np.ndarray
    ) -> np.ndarray:
        x = np.atleast_1d(np.asarray(x_km, dtype=float))
        y = np.atleast_1d(np.asarray(y_km, dtype=float))
        z = np.atleast_1d(np.asarray(z_km, dtype=float))
        x, y, z = np.broadcast_arrays(x, y, z)
        if hasattr(self, "_x_km") and hasattr(self, "_y_km") and hasattr(self, "_z_km"):
            eps = 1e-6
            x = np.clip(x, float(self._x_km[0]) + eps, float(self._x_km[-1]) - eps)
            y = np.clip(y, float(self._y_km[0]) + eps, float(self._y_km[-1]) - eps)
            z = np.clip(z, float(self._z_km[0]) + eps, float(self._z_km[-1]) - eps)
        pts = np.column_stack([z.ravel(), y.ravel(), x.ravel()])
        return self._mup_interp_zyx(pts).reshape(x.shape)

    @staticmethod
    def _rhs_cart(_s: float, y: np.ndarray, n_grad_fn) -> np.ndarray:
        x, yy, z, vx, vy, vz = y
        n, dnx, dny, dnz = n_grad_fn(np.array([x]), np.array([yy]), np.array([z]))
        n = float(n[0])
        dnx = float(dnx[0])
        dny = float(dny[0])
        dnz = float(dnz[0])
        if not np.isfinite(n) or n <= 0.0:
            return np.zeros(6, dtype=float)
        dot = dnx * vx + dny * vy + dnz * vz
        dvx = (dnx - dot * vx) / n
        dvy = (dny - dot * vy) / n
        dvz = (dnz - dot * vz) / n
        return np.array([vx, vy, vz, dvx, dvy, dvz], dtype=float)

    def trace_cartesian_gradient(
        self,
        freq_hz: float,
        elevation_deg: float,
        azimuth_deg: float = 0.0,
        x0_km: float = 0.0,
        y0_km: float = 0.0,
        z0_km: float = 0.0,
        s_max_km: float = 6000.0,
        mode: str = "O",
        collision_hz: np.ndarray | float | None = None,
        b_abs_t: np.ndarray | float | None = None,
        b_psi_deg: np.ndarray | float | None = None,
        formulation: str = "appleton-hartree",
        rtol: float = 1e-7,
        atol: float = 1e-9,
        max_step_km: float | None = None,
    ) -> SimpleNamespace:
        self.build_refractive_index_interpolators(
            freq_hz=freq_hz,
            b_abs_t=b_abs_t,
            b_psi_deg=b_psi_deg,
            collision_hz=collision_hz,
            mode=mode,
            formulation=formulation,
        )
        elev = np.deg2rad(float(elevation_deg))
        az = np.deg2rad(float(azimuth_deg))
        vx0 = np.cos(elev) * np.cos(az)
        vy0 = np.cos(elev) * np.sin(az)
        vz0 = np.sin(elev)
        vnorm = np.linalg.norm([vx0, vy0, vz0])
        vx0, vy0, vz0 = vx0 / vnorm, vy0 / vnorm, vz0 / vnorm
        yinit = np.array([x0_km, y0_km, z0_km, vx0, vy0, vz0], dtype=float)

        zmin, zmax = float(self._z_km[0]), float(self._z_km[-1])
        ymin, ymax = float(self._y_km[0]), float(self._y_km[-1])
        xmin, xmax = float(self._x_km[0]), float(self._x_km[-1])

        def ev_zmin(_s, y):
            return y[2] - zmin - 1e-3

        def ev_zmax(_s, y):
            return zmax - y[2]

        def ev_ymin(_s, y):
            return y[1] - ymin

        def ev_ymax(_s, y):
            return ymax - y[1]

        def ev_xmin(_s, y):
            return y[0] - xmin

        def ev_xmax(_s, y):
            return xmax - y[0]

        for ev in (ev_zmin, ev_zmax, ev_ymin, ev_ymax, ev_xmin, ev_xmax):
            ev.terminal = True
            ev.direction = -1.0

        sol = solve_ivp(
            lambda s, y: self._rhs_cart(s, y, self._eval_n_grad_cart),
            (0.0, float(s_max_km)),
            yinit,
            rtol=float(rtol),
            atol=float(atol),
            max_step=float(max_step_km) if max_step_km is not None else np.inf,
            events=[ev_zmin, ev_zmax, ev_ymin, ev_ymax, ev_xmin, ev_xmax],
        )
        x = sol.y[0, :]
        yy = sol.y[1, :]
        z = sol.y[2, :]
        ds = np.sqrt(np.diff(x) ** 2 + np.diff(yy) ** 2 + np.diff(z) ** 2)
        group_path_km = float(np.nansum(ds))
        xm = 0.5 * (x[:-1] + x[1:])
        ym = 0.5 * (yy[:-1] + yy[1:])
        zm = 0.5 * (z[:-1] + z[1:])
        mup = np.asarray(self._eval_mup_cart(xm, ym, zm), dtype=float)
        valid = np.isfinite(mup)
        group_delay_sec = float(np.nansum((mup[valid] / C_KM_S) * ds[valid]))
        status = "length"
        if sol.status == 1:
            status = "ground" if len(sol.t_events[0]) > 0 else "domain"
        elif sol.status == -1:
            status = "failure"
        return SimpleNamespace(
            x_km=x,
            y_km=yy,
            z_km=z,
            vx=sol.y[3, :],
            vy=sol.y[4, :],
            vz=sol.y[5, :],
            t=sol.t,
            status=status,
            reason=status,
            group_path_km=group_path_km,
            group_delay_sec=group_delay_sec,
            mode=mode,
            coordinate_system="cartesian",
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            azimuth_deg=float(azimuth_deg),
        )

    def trace_cartesian_hamiltonian(
        self,
        freq_hz: float,
        elevation_deg: float,
        azimuth_deg: float = 0.0,
        x0_km: float = 0.0,
        y0_km: float = 0.0,
        z0_km: float = 0.0,
        s_max_km: float = 6000.0,
        mode: str = "O",
        collision_hz: np.ndarray | float | None = None,
        b_abs_t: np.ndarray | float | None = None,
        b_psi_deg: np.ndarray | float | None = None,
        formulation: str = "appleton-hartree",
        h0_km: float = 2.0,
        h_min_km: float = 0.25,
        h_max_km: float = 8.0,
        max_step_km: float | None = None,
        local_err_tol_km: float = 5e-3,
        max_steps: int = 20000,
        boundary_eps_km: float = 1e-3,
    ) -> SimpleNamespace:
        """
        Adaptive 3D Cartesian Hamiltonian solver for isotropic n(x).

        Hamiltonian:
            H(x, p) = 0.5 (|p|^2 - n(x)^2) = 0
        Equations:
            dx/dtau = p
            dp/dtau = 0.5 * grad(n^2) = n * grad(n)
        """
        self.build_refractive_index_interpolators(
            freq_hz=freq_hz,
            b_abs_t=b_abs_t,
            b_psi_deg=b_psi_deg,
            collision_hz=collision_hz,
            mode=mode,
            formulation=formulation,
        )

        zmin, zmax = float(self._z_km[0]), float(self._z_km[-1])
        ymin, ymax = float(self._y_km[0]), float(self._y_km[-1])
        xmin, xmax = float(self._x_km[0]), float(self._x_km[-1])
        beps = max(0.0, float(boundary_eps_km))

        def _inside_domain(x: float, yv: float, z: float, margin: float = 0.0) -> bool:
            return (
                (xmin + margin) <= float(x) <= (xmax - margin)
                and (ymin + margin) <= float(yv) <= (ymax - margin)
                and (zmin + margin) <= float(z) <= (zmax - margin)
            )

        def _deriv(yvec: np.ndarray):
            x, yy, z, px, py, pz = yvec
            n, dnx, dny, dnz = self._eval_n_grad_cart(
                np.array([x]), np.array([yy]), np.array([z])
            )
            n = float(n[0])
            dnx = float(dnx[0])
            dny = float(dny[0])
            dnz = float(dnz[0])
            if (not np.isfinite(n)) or (n <= 0.0):
                return None
            dxdt = np.array([px, py, pz], dtype=float)
            dpdt = np.array([n * dnx, n * dny, n * dnz], dtype=float)
            return np.concatenate([dxdt, dpdt])

        def _rk4(yvec: np.ndarray, h: float):
            k1 = _deriv(yvec)
            if k1 is None:
                return None
            k2 = _deriv(yvec + 0.5 * h * k1)
            if k2 is None:
                return None
            k3 = _deriv(yvec + 0.5 * h * k2)
            if k3 is None:
                return None
            k4 = _deriv(yvec + h * k3)
            if k4 is None:
                return None
            return yvec + (h / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4)

        # Initial canonical momentum p0 = n0 * ray_direction_unit
        elev = np.deg2rad(float(elevation_deg))
        az = np.deg2rad(float(azimuth_deg))
        ux = np.cos(elev) * np.cos(az)
        uy = np.cos(elev) * np.sin(az)
        uz = np.sin(elev)
        u = np.array([ux, uy, uz], dtype=float)
        un = np.linalg.norm(u)
        if un <= 0:
            raise ValueError("Invalid launch direction norm")
        u /= un
        n0_arr = self._eval_n_grad_cart(
            np.array([x0_km]), np.array([y0_km]), np.array([z0_km])
        )[0]
        n0 = float(n0_arr[0])
        if (not np.isfinite(n0)) or (n0 <= 0.0):
            raise ValueError("Launch point refractive index is invalid")
        p0 = n0 * u
        y = np.array([x0_km, y0_km, z0_km, p0[0], p0[1], p0[2]], dtype=float)

        if max_step_km is not None:
            h_max_km = min(float(h_max_km), float(max_step_km))
        h = float(np.clip(h0_km, h_min_km, h_max_km))
        tau = 0.0
        tau_max = float(s_max_km)
        xs = [float(y[0])]
        ys = [float(y[1])]
        zs = [float(y[2])]
        pxs = [float(y[3])]
        pys = [float(y[4])]
        pzs = [float(y[5])]
        status = "length"

        for _ in range(int(max_steps)):
            if tau >= tau_max:
                status = "length"
                break
            # Boundary handling: allow starts on boundaries if the ray points inward.
            if y[2] <= zmin + 1e-3 and y[5] < 0:
                status = "ground"
                break
            if (
                (y[2] >= zmax and y[5] > 0)
                or (y[1] <= ymin and y[4] < 0)
                or (y[1] >= ymax and y[4] > 0)
                or (y[0] <= xmin and y[3] < 0)
                or (y[0] >= xmax and y[3] > 0)
            ):
                status = "domain"
                break

            h_try = min(h, tau_max - tau)
            y_big = _rk4(y, h_try)
            if y_big is None:
                if h_try > h_min_km:
                    h = max(h_min_km, 0.5 * h_try)
                    continue
                status = "failure"
                break
            y_half = _rk4(y, 0.5 * h_try)
            if y_half is None:
                if h_try > h_min_km:
                    h = max(h_min_km, 0.5 * h_try)
                    continue
                status = "failure"
                break
            y_half2 = _rk4(y_half, 0.5 * h_try)
            if y_half2 is None:
                if h_try > h_min_km:
                    h = max(h_min_km, 0.5 * h_try)
                    continue
                status = "failure"
                break

            # If the candidate step exits the safe interpolation interior,
            # reduce step first; if already at minimum step, terminate as domain.
            if not _inside_domain(y_half2[0], y_half2[1], y_half2[2], margin=beps):
                if h_try > h_min_km:
                    h = max(h_min_km, 0.5 * h_try)
                    continue
                status = "domain" if y_half2[2] > zmin + beps else "ground"
                break

            err = np.linalg.norm(y_half2[:3] - y_big[:3], ord=2)
            if np.isfinite(err) and err > local_err_tol_km and h_try > h_min_km:
                h = max(h_min_km, 0.5 * h_try)
                continue

            # Accept higher-accuracy step (step-doubling result)
            y = y_half2
            # Project momentum back to |p| = n to reduce drift.
            n_now = self._eval_n_grad_cart(
                np.array([y[0]]), np.array([y[1]]), np.array([y[2]])
            )[0][0]
            pnorm = np.linalg.norm(y[3:6])
            if np.isfinite(n_now) and n_now > 0 and pnorm > 0:
                y[3:6] = y[3:6] * (float(n_now) / float(pnorm))

            tau += h_try
            xs.append(float(y[0]))
            ys.append(float(y[1]))
            zs.append(float(y[2]))
            pxs.append(float(y[3]))
            pys.append(float(y[4]))
            pzs.append(float(y[5]))

            if np.isfinite(err) and err < 0.25 * local_err_tol_km:
                h = min(h_max_km, 2.0 * h_try)
            else:
                h = h_try
        else:
            status = "failure"

        x = np.asarray(xs, dtype=float)
        yy = np.asarray(ys, dtype=float)
        z = np.asarray(zs, dtype=float)
        px = np.asarray(pxs, dtype=float)
        py = np.asarray(pys, dtype=float)
        pz = np.asarray(pzs, dtype=float)

        ds = np.sqrt(np.diff(x) ** 2 + np.diff(yy) ** 2 + np.diff(z) ** 2)
        group_path_km = float(np.nansum(ds))
        xm = 0.5 * (x[:-1] + x[1:])
        ym = 0.5 * (yy[:-1] + yy[1:])
        zm = 0.5 * (z[:-1] + z[1:])
        mup = np.asarray(self._eval_mup_cart(xm, ym, zm), dtype=float)
        valid = np.isfinite(mup)
        group_delay_sec = float(np.nansum((mup[valid] / C_KM_S) * ds[valid]))

        # Direction estimates from canonical momentum.
        pnorm = np.sqrt(px**2 + py**2 + pz**2)
        vx = np.divide(px, pnorm, out=np.zeros_like(px), where=pnorm > 0)
        vy = np.divide(py, pnorm, out=np.zeros_like(py), where=pnorm > 0)
        vz = np.divide(pz, pnorm, out=np.zeros_like(pz), where=pnorm > 0)

        return SimpleNamespace(
            x_km=x,
            y_km=yy,
            z_km=z,
            vx=vx,
            vy=vy,
            vz=vz,
            px=px,
            py=py,
            pz=pz,
            t=np.linspace(0.0, tau, x.size),
            status=status,
            reason=status,
            group_path_km=group_path_km,
            group_delay_sec=group_delay_sec,
            mode=mode,
            coordinate_system="cartesian",
            solver="hamiltonian",
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            azimuth_deg=float(azimuth_deg),
        )

    def _eval_n_sph(
        self, alt_km: np.ndarray, lat_deg: np.ndarray, lon_deg: np.ndarray
    ) -> np.ndarray:
        alt = np.atleast_1d(np.asarray(alt_km, dtype=float))
        lat = np.atleast_1d(np.asarray(lat_deg, dtype=float))
        lon = np.atleast_1d(np.asarray(lon_deg, dtype=float))
        alt, lat, lon = np.broadcast_arrays(alt, lat, lon)
        pts = np.column_stack([alt.ravel(), lat.ravel(), lon.ravel()])
        return self._n_interp_altll(pts).reshape(alt.shape)

    def _eval_mup_sph(
        self, alt_km: np.ndarray, lat_deg: np.ndarray, lon_deg: np.ndarray
    ) -> np.ndarray:
        alt = np.atleast_1d(np.asarray(alt_km, dtype=float))
        lat = np.atleast_1d(np.asarray(lat_deg, dtype=float))
        lon = np.atleast_1d(np.asarray(lon_deg, dtype=float))
        alt, lat, lon = np.broadcast_arrays(alt, lat, lon)
        pts = np.column_stack([alt.ravel(), lat.ravel(), lon.ravel()])
        return self._mup_interp_altll(pts).reshape(alt.shape)

    def _eval_n_grad_sph(
        self,
        r_km: np.ndarray,
        lat_rad: np.ndarray,
        lon_rad: np.ndarray,
        r_earth_km: float,
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        r = np.atleast_1d(np.asarray(r_km, dtype=float))
        lat = np.atleast_1d(np.asarray(lat_rad, dtype=float))
        lon = np.atleast_1d(np.asarray(lon_rad, dtype=float))
        r, lat, lon = np.broadcast_arrays(r, lat, lon)
        alt = r - float(r_earth_km)
        lat_deg = np.rad2deg(lat)
        lon_deg = np.rad2deg(lon)
        n = self._eval_n_sph(alt, lat_deg, lon_deg)

        dr = 1.0
        da = np.deg2rad(0.02)
        dl = np.deg2rad(0.02)
        n_rp = self._eval_n_sph(alt + dr, lat_deg, lon_deg)
        n_rm = self._eval_n_sph(alt - dr, lat_deg, lon_deg)
        n_ap = self._eval_n_sph(alt, np.rad2deg(lat + da), lon_deg)
        n_am = self._eval_n_sph(alt, np.rad2deg(lat - da), lon_deg)
        n_lp = self._eval_n_sph(alt, lat_deg, np.rad2deg(lon + dl))
        n_lm = self._eval_n_sph(alt, lat_deg, np.rad2deg(lon - dl))

        dn_dr = (n_rp - n_rm) / (2.0 * dr)
        dn_dlat = (n_ap - n_am) / (2.0 * da)
        dn_dlon = (n_lp - n_lm) / (2.0 * dl)
        return n, dn_dr, dn_dlat, dn_dlon

    @staticmethod
    def _rhs_sph(_s: float, y: np.ndarray, n_grad_fn) -> np.ndarray:
        r, lat, lon, vr, vlat, vlon = y
        n, dn_dr, dn_dlat, dn_dlon = n_grad_fn(
            np.array([r]), np.array([lat]), np.array([lon])
        )
        n = float(n[0])
        dn_dr = float(dn_dr[0])
        dn_dlat = float(dn_dlat[0])
        dn_dlon = float(dn_dlon[0])
        cl = max(np.cos(lat), 1e-6)
        if not np.isfinite(n) or n <= 0.0 or r <= 0.0:
            return np.zeros(6, dtype=float)
        grad_dot_v = dn_dr * vr + (dn_dlat / r) * vlat + (dn_dlon / (r * cl)) * vlon
        drds = vr
        dlatds = vlat / r
        dlonds = vlon / (r * cl)
        dvr = (dn_dr - grad_dot_v * vr) / n + (vlat * vlat + vlon * vlon) / r
        dvlat = (
            ((dn_dlat / r) - grad_dot_v * vlat) / n
            - (vr * vlat) / r
            + (vlon * vlon * np.tan(lat)) / r
        )
        dvlon = (
            ((dn_dlon / (r * cl)) - grad_dot_v * vlon) / n
            - (vr * vlon) / r
            - (vlat * vlon * np.tan(lat)) / r
        )
        return np.array([drds, dlatds, dlonds, dvr, dvlat, dvlon], dtype=float)

    def trace_spherical_gradient(
        self,
        freq_hz: float,
        elevation_deg: float,
        azimuth_deg: float = 0.0,
        x0_km: float = 0.0,
        y0_km: float = 0.0,
        z0_km: float = 0.0,
        s_max_km: float = 7000.0,
        mode: str = "O",
        collision_hz: np.ndarray | float | None = None,
        b_abs_t: np.ndarray | float | None = None,
        b_psi_deg: np.ndarray | float | None = None,
        formulation: str = "appleton-hartree",
        r_earth_km: float = 6371.0,
        rtol: float = 1e-7,
        atol: float = 1e-9,
        max_step_km: float | None = None,
    ) -> SimpleNamespace:
        self.build_refractive_index_interpolators(
            freq_hz=freq_hz,
            b_abs_t=b_abs_t,
            b_psi_deg=b_psi_deg,
            collision_hz=collision_hz,
            mode=mode,
            formulation=formulation,
        )
        km_per_deg_lat = 111.32
        km_per_deg_lon = km_per_deg_lat * np.cos(np.deg2rad(self._lat_ref_deg))
        lat0_deg = self._lat_ref_deg + float(y0_km) / km_per_deg_lat
        lon0_deg = self._lon_ref_deg + float(x0_km) / max(km_per_deg_lon, 1e-6)
        r0 = float(r_earth_km) + float(z0_km)
        lat0 = np.deg2rad(lat0_deg)
        lon0 = np.deg2rad(lon0_deg)

        elev = np.deg2rad(float(elevation_deg))
        az = np.deg2rad(float(azimuth_deg))
        vr0 = np.sin(elev)
        vh = np.cos(elev)
        vlat0 = vh * np.cos(az)
        vlon0 = vh * np.sin(az)
        vnorm = np.linalg.norm([vr0, vlat0, vlon0])
        vr0, vlat0, vlon0 = vr0 / vnorm, vlat0 / vnorm, vlon0 / vnorm
        yinit = np.array([r0, lat0, lon0, vr0, vlat0, vlon0], dtype=float)

        rmin = float(r_earth_km) + float(self.alts_km[0])
        rmax = float(r_earth_km) + float(self.alts_km[-1])
        lat_min = np.deg2rad(float(self.lats[0]))
        lat_max = np.deg2rad(float(self.lats[-1]))
        lon_min = np.deg2rad(float(self.lons[0]))
        lon_max = np.deg2rad(float(self.lons[-1]))

        def ev_rmin(_s, y):
            return y[0] - rmin - 1e-3

        def ev_rmax(_s, y):
            return rmax - y[0]

        def ev_latmin(_s, y):
            return y[1] - lat_min

        def ev_latmax(_s, y):
            return lat_max - y[1]

        def ev_lonmin(_s, y):
            return y[2] - lon_min

        def ev_lonmax(_s, y):
            return lon_max - y[2]

        for ev in (ev_rmin, ev_rmax, ev_latmin, ev_latmax, ev_lonmin, ev_lonmax):
            ev.terminal = True
            ev.direction = -1.0

        sol = solve_ivp(
            lambda s, y: self._rhs_sph(
                s,
                y,
                lambda r, lat, lon: self._eval_n_grad_sph(
                    r_km=r, lat_rad=lat, lon_rad=lon, r_earth_km=float(r_earth_km)
                ),
            ),
            (0.0, float(s_max_km)),
            yinit,
            rtol=float(rtol),
            atol=float(atol),
            max_step=float(max_step_km) if max_step_km is not None else np.inf,
            events=[ev_rmin, ev_rmax, ev_latmin, ev_latmax, ev_lonmin, ev_lonmax],
        )

        r = sol.y[0, :]
        lat = sol.y[1, :]
        lon = sol.y[2, :]
        z = r - float(r_earth_km)
        lat_deg = np.rad2deg(lat)
        lon_deg = np.rad2deg(lon)
        x = (lon_deg - self._lon_ref_deg) * km_per_deg_lon
        yy = (lat_deg - self._lat_ref_deg) * km_per_deg_lat
        ds = np.sqrt(
            np.diff(r) ** 2
            + (0.5 * (r[:-1] + r[1:]) * np.diff(lat)) ** 2
            + (
                0.5
                * (r[:-1] + r[1:])
                * np.cos(0.5 * (lat[:-1] + lat[1:]))
                * np.diff(lon)
            )
            ** 2
        )
        group_path_km = float(np.nansum(ds))
        alt_mid = 0.5 * (z[:-1] + z[1:])
        lat_mid = 0.5 * (lat_deg[:-1] + lat_deg[1:])
        lon_mid = 0.5 * (lon_deg[:-1] + lon_deg[1:])
        mup = np.asarray(self._eval_mup_sph(alt_mid, lat_mid, lon_mid), dtype=float)
        valid = np.isfinite(mup)
        group_delay_sec = float(np.nansum((mup[valid] / C_KM_S) * ds[valid]))
        status = "length"
        if sol.status == 1:
            status = "ground" if len(sol.t_events[0]) > 0 else "domain"
        elif sol.status == -1:
            status = "failure"
        return SimpleNamespace(
            x_km=x,
            y_km=yy,
            z_km=z,
            lat_deg=lat_deg,
            lon_deg=lon_deg,
            r_km=r,
            vr=sol.y[3, :],
            vlat=sol.y[4, :],
            vlon=sol.y[5, :],
            t=sol.t,
            status=status,
            reason=status,
            group_path_km=group_path_km,
            group_delay_sec=group_delay_sec,
            mode=mode,
            coordinate_system="spherical",
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            azimuth_deg=float(azimuth_deg),
        )

    def oblique_trace(
        self,
        freq_hz: float,
        elevation_deg: float,
        *,
        coordinate_system: str = "cartesian",
        solver: str = "gradient",
        nhops: int = 1,
        **kwargs,
    ) -> SimpleNamespace:
        """Unified 3-D oblique ray-trace entry point.

        Parameters
        ----------
        coordinate_system : ``"cartesian"`` or ``"spherical"``.
        solver : ``"gradient"`` (default) or ``"hamiltonian"`` (cartesian only).
        nhops : int, optional
            Number of ionospheric hops (default 1).  For nhops > 1 each
            ground hit is reflected specularly (vz → −vz for cartesian,
            vr → −vr for spherical) and the ODE restarts from the domain
            left edge with x/y shifted by the accumulated ground-hit
            offset (horizontal-homogeneity assumption).  All hop segments
            are concatenated in the returned namespace.
        """
        nhops = max(1, int(nhops))
        coord = str(coordinate_system).strip().lower()
        solv = str(solver).strip().lower()

        # ── select tracer ──────────────────────────────────────────────────
        if coord in {"cartesian", "cart", "xyz"}:
            _tracer = (
                self.trace_cartesian_hamiltonian
                if solv in {"hamiltonian", "ham"}
                else self.trace_cartesian_gradient
            )
            is_sph = False
        elif coord in {"spherical", "sph", "rll"}:
            if solv in {"hamiltonian", "ham"}:
                logger.warning(
                    "Hamiltonian spherical solver not implemented; using gradient."
                )
            _tracer = self.trace_spherical_gradient
            is_sph = True
        else:
            raise ValueError("coordinate_system must be 'cartesian' or 'spherical'")

        # ── single-hop fast path ───────────────────────────────────────────
        if nhops == 1:
            out = _tracer(freq_hz=freq_hz, elevation_deg=elevation_deg, **kwargs)
            out.nhops_completed = 1
            return out

        # ── multi-hop path ─────────────────────────────────────────────────
        # Extract first-hop origin (consumed here; subsequent hops restart
        # at domain origin with coordinate shift applied to output).
        x0 = float(kwargs.pop("x0_km", 0.0))
        y0 = float(kwargs.pop("y0_km", 0.0))
        z0 = float(kwargs.pop("z0_km", float(self.alts_km[0])))

        all_x: list[np.ndarray] = []
        all_y: list[np.ndarray] = []
        all_z: list[np.ndarray] = []
        total_gpath = 0.0
        total_gdelay = 0.0
        z_apex_best = -np.inf
        last: SimpleNamespace | None = None
        hops_done = 0
        elev = float(elevation_deg)
        az = float(kwargs.get("azimuth_deg", 0.0))

        # Accumulated physical offset for subsequent hops
        x_accum, y_accum = x0, y0

        for _hop in range(nhops):
            x_ode = 0.0 if _hop > 0 else x0
            y_ode = 0.0 if _hop > 0 else y0
            x_sft = x_accum if _hop > 0 else 0.0
            y_sft = y_accum if _hop > 0 else 0.0

            ray = _tracer(
                freq_hz=freq_hz,
                elevation_deg=elev,
                x0_km=x_ode,
                y0_km=y_ode,
                z0_km=z0,
                **kwargs,
            )
            x_arr = np.asarray(ray.x_km, dtype=float) + x_sft
            y_arr = np.asarray(ray.y_km, dtype=float) + y_sft
            z_arr = np.asarray(ray.z_km, dtype=float)
            all_x.append(x_arr)
            all_y.append(y_arr)
            all_z.append(z_arr)
            total_gpath += float(ray.group_path_km)
            total_gdelay += float(getattr(ray, "group_delay_sec", 0.0))
            if z_arr.size:
                z_apex_best = max(z_apex_best, float(np.nanmax(z_arr)))
            last = ray
            hops_done += 1

            if ray.status != "ground" or x_arr.size == 0:
                break  # did not reach ground — no further hops

            # ── specular ground reflection ─────────────────────────────────
            if is_sph:
                # state [r, lat, lon, vr, vlat, vlon]; vr²+vlat²+vlon²=1
                vr_last = float(ray.vr[-1])  # < 0 at descent
                vlat_last = float(ray.vlat[-1])
                vlon_last = float(ray.vlon[-1])
                elev = float(
                    np.degrees(
                        np.arctan2(abs(vr_last), np.sqrt(vlat_last**2 + vlon_last**2))
                    )
                )
                az = float(np.degrees(np.arctan2(vlon_last, vlat_last)))
            else:
                # state [x, y, z, vx, vy, vz]; vx²+vy²+vz²=1
                vx_last = float(ray.vx[-1])
                vy_last = float(ray.vy[-1])
                vz_last = float(ray.vz[-1])  # < 0 at descent
                elev = float(
                    np.degrees(
                        np.arctan2(abs(vz_last), np.sqrt(vx_last**2 + vy_last**2))
                    )
                )
                az = float(np.degrees(np.arctan2(vy_last, vx_last)))

            # Update azimuth in kwargs so the next tracer call uses it
            kwargs["azimuth_deg"] = az

            # Physical ground-hit position becomes the shift for the next hop
            x_accum = float(x_arr[-1])
            y_accum = float(y_arr[-1])
            z0 = float(self.alts_km[0])  # restart at ground level

        # ── concatenate all hop segments ───────────────────────────────────
        x_cat = np.concatenate(all_x) if all_x else np.array([], dtype=float)
        y_cat = np.concatenate(all_y) if all_y else np.array([], dtype=float)
        z_cat = np.concatenate(all_z) if all_z else np.array([], dtype=float)
        final_status = last.status if last is not None else "failure"

        out = SimpleNamespace(
            x_km=x_cat,
            y_km=y_cat,
            z_km=z_cat,
            status=final_status,
            reason=final_status,
            group_path_km=total_gpath,
            group_delay_sec=total_gdelay,
            z_apex_km=float(z_apex_best) if z_apex_best > -np.inf else np.nan,
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            azimuth_deg=float(kwargs.get("azimuth_deg", az)),
            mode=getattr(last, "mode", None),
            coordinate_system=coord,
            solver=getattr(last, "solver", "gradient"),
            nhops_completed=hops_done,
        )
        # Carry terminal velocity components from the final hop
        if last is not None:
            if is_sph:
                out.vr = last.vr
                out.vlat = last.vlat
                out.vlon = last.vlon
            else:
                out.vx = last.vx
                out.vy = last.vy
                out.vz = last.vz
        return out

fetch_collision(Te=None, Ti=None, edens=None, O2p=None, Op=None)

Compute and attach collision frequencies to the profile.

Convenience wrapper around :meth:RT3DProfile.compute_collision. Requires that fetch_msise() has been called on the profile.

Returns

ComputeCollision

Source code in hfpytrace/model/rt3d.py
def fetch_collision(
    self,
    Te: np.ndarray | float | None = None,
    Ti: np.ndarray | float | None = None,
    edens: np.ndarray | None = None,
    O2p: np.ndarray | None = None,
    Op: np.ndarray | None = None,
) -> object:
    """
    Compute and attach collision frequencies to the profile.

    Convenience wrapper around :meth:`RT3DProfile.compute_collision`.
    Requires that ``fetch_msise()`` has been called on the profile.

    Returns
    -------
    ComputeCollision
    """
    return self.profile.compute_collision(
        Te=Te,
        Ti=Ti,
        edens=edens,
        O2p=O2p,
        Op=Op,
    )

trace_cartesian_hamiltonian(freq_hz, elevation_deg, azimuth_deg=0.0, x0_km=0.0, y0_km=0.0, z0_km=0.0, s_max_km=6000.0, mode='O', collision_hz=None, b_abs_t=None, b_psi_deg=None, formulation='appleton-hartree', h0_km=2.0, h_min_km=0.25, h_max_km=8.0, max_step_km=None, local_err_tol_km=0.005, max_steps=20000, boundary_eps_km=0.001)

Adaptive 3D Cartesian Hamiltonian solver for isotropic n(x).

Hamiltonian

H(x, p) = 0.5 (|p|^2 - n(x)^2) = 0

Equations

dx/dtau = p dp/dtau = 0.5 * grad(n^2) = n * grad(n)

Source code in hfpytrace/model/rt3d.py
def trace_cartesian_hamiltonian(
    self,
    freq_hz: float,
    elevation_deg: float,
    azimuth_deg: float = 0.0,
    x0_km: float = 0.0,
    y0_km: float = 0.0,
    z0_km: float = 0.0,
    s_max_km: float = 6000.0,
    mode: str = "O",
    collision_hz: np.ndarray | float | None = None,
    b_abs_t: np.ndarray | float | None = None,
    b_psi_deg: np.ndarray | float | None = None,
    formulation: str = "appleton-hartree",
    h0_km: float = 2.0,
    h_min_km: float = 0.25,
    h_max_km: float = 8.0,
    max_step_km: float | None = None,
    local_err_tol_km: float = 5e-3,
    max_steps: int = 20000,
    boundary_eps_km: float = 1e-3,
) -> SimpleNamespace:
    """
    Adaptive 3D Cartesian Hamiltonian solver for isotropic n(x).

    Hamiltonian:
        H(x, p) = 0.5 (|p|^2 - n(x)^2) = 0
    Equations:
        dx/dtau = p
        dp/dtau = 0.5 * grad(n^2) = n * grad(n)
    """
    self.build_refractive_index_interpolators(
        freq_hz=freq_hz,
        b_abs_t=b_abs_t,
        b_psi_deg=b_psi_deg,
        collision_hz=collision_hz,
        mode=mode,
        formulation=formulation,
    )

    zmin, zmax = float(self._z_km[0]), float(self._z_km[-1])
    ymin, ymax = float(self._y_km[0]), float(self._y_km[-1])
    xmin, xmax = float(self._x_km[0]), float(self._x_km[-1])
    beps = max(0.0, float(boundary_eps_km))

    def _inside_domain(x: float, yv: float, z: float, margin: float = 0.0) -> bool:
        return (
            (xmin + margin) <= float(x) <= (xmax - margin)
            and (ymin + margin) <= float(yv) <= (ymax - margin)
            and (zmin + margin) <= float(z) <= (zmax - margin)
        )

    def _deriv(yvec: np.ndarray):
        x, yy, z, px, py, pz = yvec
        n, dnx, dny, dnz = self._eval_n_grad_cart(
            np.array([x]), np.array([yy]), np.array([z])
        )
        n = float(n[0])
        dnx = float(dnx[0])
        dny = float(dny[0])
        dnz = float(dnz[0])
        if (not np.isfinite(n)) or (n <= 0.0):
            return None
        dxdt = np.array([px, py, pz], dtype=float)
        dpdt = np.array([n * dnx, n * dny, n * dnz], dtype=float)
        return np.concatenate([dxdt, dpdt])

    def _rk4(yvec: np.ndarray, h: float):
        k1 = _deriv(yvec)
        if k1 is None:
            return None
        k2 = _deriv(yvec + 0.5 * h * k1)
        if k2 is None:
            return None
        k3 = _deriv(yvec + 0.5 * h * k2)
        if k3 is None:
            return None
        k4 = _deriv(yvec + h * k3)
        if k4 is None:
            return None
        return yvec + (h / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4)

    # Initial canonical momentum p0 = n0 * ray_direction_unit
    elev = np.deg2rad(float(elevation_deg))
    az = np.deg2rad(float(azimuth_deg))
    ux = np.cos(elev) * np.cos(az)
    uy = np.cos(elev) * np.sin(az)
    uz = np.sin(elev)
    u = np.array([ux, uy, uz], dtype=float)
    un = np.linalg.norm(u)
    if un <= 0:
        raise ValueError("Invalid launch direction norm")
    u /= un
    n0_arr = self._eval_n_grad_cart(
        np.array([x0_km]), np.array([y0_km]), np.array([z0_km])
    )[0]
    n0 = float(n0_arr[0])
    if (not np.isfinite(n0)) or (n0 <= 0.0):
        raise ValueError("Launch point refractive index is invalid")
    p0 = n0 * u
    y = np.array([x0_km, y0_km, z0_km, p0[0], p0[1], p0[2]], dtype=float)

    if max_step_km is not None:
        h_max_km = min(float(h_max_km), float(max_step_km))
    h = float(np.clip(h0_km, h_min_km, h_max_km))
    tau = 0.0
    tau_max = float(s_max_km)
    xs = [float(y[0])]
    ys = [float(y[1])]
    zs = [float(y[2])]
    pxs = [float(y[3])]
    pys = [float(y[4])]
    pzs = [float(y[5])]
    status = "length"

    for _ in range(int(max_steps)):
        if tau >= tau_max:
            status = "length"
            break
        # Boundary handling: allow starts on boundaries if the ray points inward.
        if y[2] <= zmin + 1e-3 and y[5] < 0:
            status = "ground"
            break
        if (
            (y[2] >= zmax and y[5] > 0)
            or (y[1] <= ymin and y[4] < 0)
            or (y[1] >= ymax and y[4] > 0)
            or (y[0] <= xmin and y[3] < 0)
            or (y[0] >= xmax and y[3] > 0)
        ):
            status = "domain"
            break

        h_try = min(h, tau_max - tau)
        y_big = _rk4(y, h_try)
        if y_big is None:
            if h_try > h_min_km:
                h = max(h_min_km, 0.5 * h_try)
                continue
            status = "failure"
            break
        y_half = _rk4(y, 0.5 * h_try)
        if y_half is None:
            if h_try > h_min_km:
                h = max(h_min_km, 0.5 * h_try)
                continue
            status = "failure"
            break
        y_half2 = _rk4(y_half, 0.5 * h_try)
        if y_half2 is None:
            if h_try > h_min_km:
                h = max(h_min_km, 0.5 * h_try)
                continue
            status = "failure"
            break

        # If the candidate step exits the safe interpolation interior,
        # reduce step first; if already at minimum step, terminate as domain.
        if not _inside_domain(y_half2[0], y_half2[1], y_half2[2], margin=beps):
            if h_try > h_min_km:
                h = max(h_min_km, 0.5 * h_try)
                continue
            status = "domain" if y_half2[2] > zmin + beps else "ground"
            break

        err = np.linalg.norm(y_half2[:3] - y_big[:3], ord=2)
        if np.isfinite(err) and err > local_err_tol_km and h_try > h_min_km:
            h = max(h_min_km, 0.5 * h_try)
            continue

        # Accept higher-accuracy step (step-doubling result)
        y = y_half2
        # Project momentum back to |p| = n to reduce drift.
        n_now = self._eval_n_grad_cart(
            np.array([y[0]]), np.array([y[1]]), np.array([y[2]])
        )[0][0]
        pnorm = np.linalg.norm(y[3:6])
        if np.isfinite(n_now) and n_now > 0 and pnorm > 0:
            y[3:6] = y[3:6] * (float(n_now) / float(pnorm))

        tau += h_try
        xs.append(float(y[0]))
        ys.append(float(y[1]))
        zs.append(float(y[2]))
        pxs.append(float(y[3]))
        pys.append(float(y[4]))
        pzs.append(float(y[5]))

        if np.isfinite(err) and err < 0.25 * local_err_tol_km:
            h = min(h_max_km, 2.0 * h_try)
        else:
            h = h_try
    else:
        status = "failure"

    x = np.asarray(xs, dtype=float)
    yy = np.asarray(ys, dtype=float)
    z = np.asarray(zs, dtype=float)
    px = np.asarray(pxs, dtype=float)
    py = np.asarray(pys, dtype=float)
    pz = np.asarray(pzs, dtype=float)

    ds = np.sqrt(np.diff(x) ** 2 + np.diff(yy) ** 2 + np.diff(z) ** 2)
    group_path_km = float(np.nansum(ds))
    xm = 0.5 * (x[:-1] + x[1:])
    ym = 0.5 * (yy[:-1] + yy[1:])
    zm = 0.5 * (z[:-1] + z[1:])
    mup = np.asarray(self._eval_mup_cart(xm, ym, zm), dtype=float)
    valid = np.isfinite(mup)
    group_delay_sec = float(np.nansum((mup[valid] / C_KM_S) * ds[valid]))

    # Direction estimates from canonical momentum.
    pnorm = np.sqrt(px**2 + py**2 + pz**2)
    vx = np.divide(px, pnorm, out=np.zeros_like(px), where=pnorm > 0)
    vy = np.divide(py, pnorm, out=np.zeros_like(py), where=pnorm > 0)
    vz = np.divide(pz, pnorm, out=np.zeros_like(pz), where=pnorm > 0)

    return SimpleNamespace(
        x_km=x,
        y_km=yy,
        z_km=z,
        vx=vx,
        vy=vy,
        vz=vz,
        px=px,
        py=py,
        pz=pz,
        t=np.linspace(0.0, tau, x.size),
        status=status,
        reason=status,
        group_path_km=group_path_km,
        group_delay_sec=group_delay_sec,
        mode=mode,
        coordinate_system="cartesian",
        solver="hamiltonian",
        freq_hz=float(freq_hz),
        elevation_deg=float(elevation_deg),
        azimuth_deg=float(azimuth_deg),
    )

oblique_trace(freq_hz, elevation_deg, *, coordinate_system='cartesian', solver='gradient', nhops=1, **kwargs)

Unified 3-D oblique ray-trace entry point.

Parameters

coordinate_system : "cartesian" or "spherical". solver : "gradient" (default) or "hamiltonian" (cartesian only).

int, optional

Number of ionospheric hops (default 1). For nhops > 1 each ground hit is reflected specularly (vz → −vz for cartesian, vr → −vr for spherical) and the ODE restarts from the domain left edge with x/y shifted by the accumulated ground-hit offset (horizontal-homogeneity assumption). All hop segments are concatenated in the returned namespace.

Source code in hfpytrace/model/rt3d.py
def oblique_trace(
    self,
    freq_hz: float,
    elevation_deg: float,
    *,
    coordinate_system: str = "cartesian",
    solver: str = "gradient",
    nhops: int = 1,
    **kwargs,
) -> SimpleNamespace:
    """Unified 3-D oblique ray-trace entry point.

    Parameters
    ----------
    coordinate_system : ``"cartesian"`` or ``"spherical"``.
    solver : ``"gradient"`` (default) or ``"hamiltonian"`` (cartesian only).
    nhops : int, optional
        Number of ionospheric hops (default 1).  For nhops > 1 each
        ground hit is reflected specularly (vz → −vz for cartesian,
        vr → −vr for spherical) and the ODE restarts from the domain
        left edge with x/y shifted by the accumulated ground-hit
        offset (horizontal-homogeneity assumption).  All hop segments
        are concatenated in the returned namespace.
    """
    nhops = max(1, int(nhops))
    coord = str(coordinate_system).strip().lower()
    solv = str(solver).strip().lower()

    # ── select tracer ──────────────────────────────────────────────────
    if coord in {"cartesian", "cart", "xyz"}:
        _tracer = (
            self.trace_cartesian_hamiltonian
            if solv in {"hamiltonian", "ham"}
            else self.trace_cartesian_gradient
        )
        is_sph = False
    elif coord in {"spherical", "sph", "rll"}:
        if solv in {"hamiltonian", "ham"}:
            logger.warning(
                "Hamiltonian spherical solver not implemented; using gradient."
            )
        _tracer = self.trace_spherical_gradient
        is_sph = True
    else:
        raise ValueError("coordinate_system must be 'cartesian' or 'spherical'")

    # ── single-hop fast path ───────────────────────────────────────────
    if nhops == 1:
        out = _tracer(freq_hz=freq_hz, elevation_deg=elevation_deg, **kwargs)
        out.nhops_completed = 1
        return out

    # ── multi-hop path ─────────────────────────────────────────────────
    # Extract first-hop origin (consumed here; subsequent hops restart
    # at domain origin with coordinate shift applied to output).
    x0 = float(kwargs.pop("x0_km", 0.0))
    y0 = float(kwargs.pop("y0_km", 0.0))
    z0 = float(kwargs.pop("z0_km", float(self.alts_km[0])))

    all_x: list[np.ndarray] = []
    all_y: list[np.ndarray] = []
    all_z: list[np.ndarray] = []
    total_gpath = 0.0
    total_gdelay = 0.0
    z_apex_best = -np.inf
    last: SimpleNamespace | None = None
    hops_done = 0
    elev = float(elevation_deg)
    az = float(kwargs.get("azimuth_deg", 0.0))

    # Accumulated physical offset for subsequent hops
    x_accum, y_accum = x0, y0

    for _hop in range(nhops):
        x_ode = 0.0 if _hop > 0 else x0
        y_ode = 0.0 if _hop > 0 else y0
        x_sft = x_accum if _hop > 0 else 0.0
        y_sft = y_accum if _hop > 0 else 0.0

        ray = _tracer(
            freq_hz=freq_hz,
            elevation_deg=elev,
            x0_km=x_ode,
            y0_km=y_ode,
            z0_km=z0,
            **kwargs,
        )
        x_arr = np.asarray(ray.x_km, dtype=float) + x_sft
        y_arr = np.asarray(ray.y_km, dtype=float) + y_sft
        z_arr = np.asarray(ray.z_km, dtype=float)
        all_x.append(x_arr)
        all_y.append(y_arr)
        all_z.append(z_arr)
        total_gpath += float(ray.group_path_km)
        total_gdelay += float(getattr(ray, "group_delay_sec", 0.0))
        if z_arr.size:
            z_apex_best = max(z_apex_best, float(np.nanmax(z_arr)))
        last = ray
        hops_done += 1

        if ray.status != "ground" or x_arr.size == 0:
            break  # did not reach ground — no further hops

        # ── specular ground reflection ─────────────────────────────────
        if is_sph:
            # state [r, lat, lon, vr, vlat, vlon]; vr²+vlat²+vlon²=1
            vr_last = float(ray.vr[-1])  # < 0 at descent
            vlat_last = float(ray.vlat[-1])
            vlon_last = float(ray.vlon[-1])
            elev = float(
                np.degrees(
                    np.arctan2(abs(vr_last), np.sqrt(vlat_last**2 + vlon_last**2))
                )
            )
            az = float(np.degrees(np.arctan2(vlon_last, vlat_last)))
        else:
            # state [x, y, z, vx, vy, vz]; vx²+vy²+vz²=1
            vx_last = float(ray.vx[-1])
            vy_last = float(ray.vy[-1])
            vz_last = float(ray.vz[-1])  # < 0 at descent
            elev = float(
                np.degrees(
                    np.arctan2(abs(vz_last), np.sqrt(vx_last**2 + vy_last**2))
                )
            )
            az = float(np.degrees(np.arctan2(vy_last, vx_last)))

        # Update azimuth in kwargs so the next tracer call uses it
        kwargs["azimuth_deg"] = az

        # Physical ground-hit position becomes the shift for the next hop
        x_accum = float(x_arr[-1])
        y_accum = float(y_arr[-1])
        z0 = float(self.alts_km[0])  # restart at ground level

    # ── concatenate all hop segments ───────────────────────────────────
    x_cat = np.concatenate(all_x) if all_x else np.array([], dtype=float)
    y_cat = np.concatenate(all_y) if all_y else np.array([], dtype=float)
    z_cat = np.concatenate(all_z) if all_z else np.array([], dtype=float)
    final_status = last.status if last is not None else "failure"

    out = SimpleNamespace(
        x_km=x_cat,
        y_km=y_cat,
        z_km=z_cat,
        status=final_status,
        reason=final_status,
        group_path_km=total_gpath,
        group_delay_sec=total_gdelay,
        z_apex_km=float(z_apex_best) if z_apex_best > -np.inf else np.nan,
        freq_hz=float(freq_hz),
        elevation_deg=float(elevation_deg),
        azimuth_deg=float(kwargs.get("azimuth_deg", az)),
        mode=getattr(last, "mode", None),
        coordinate_system=coord,
        solver=getattr(last, "solver", "gradient"),
        nhops_completed=hops_done,
    )
    # Carry terminal velocity components from the final hop
    if last is not None:
        if is_sph:
            out.vr = last.vr
            out.vlat = last.vlat
            out.vlon = last.vlon
        else:
            out.vx = last.vx
            out.vy = last.vy
            out.vz = last.vz
    return out

Source Code

hfpytrace/model/rt3d.py
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
"""3D ionospheric profile assembly and PHaRLAP-driven ray tracing.

Provides a 3D (lat × lon × alt) gridded profile container and a thin wrapper
around the PHaRLAP MATLAB engine for full 3D oblique HF ray tracing.

Classes
-------
RT3DProfile
    Dataclass holding all 3D (nlat × nlon × nalt) ionospheric fields —
    electron density, neutral atmosphere, geomagnetic field, and collision
    frequency.  Supports IRI, SAMI3, WACCM-X, GEMINI, and GITM density sources
    through ``fetch_*`` methods and a ``from_cfg`` factory.
RT3D
    Entry-point that owns an :class:`RT3DProfile` and drives PHaRLAP ray
    tracing via the MATLAB engine.  Key methods:

    * ``build_iono_grids()`` — assemble ``iono_en_grid`` and ``iono_grid_parms``
      ready for ``raytrace_3d`` / ``raytrace_3d_sp``.
    * ``build_geomag_grids()`` — assemble ``Bx``, ``By``, ``Bz``, and
      ``geomag_grid_parms`` arrays.
    * ``raytrace(engine, ...)`` — call PHaRLAP through :class:`~hfpytrace.pharlap.Engine`
      and return ``(ray_data, ray_path_data, ray_state_vec)``.

Collision types
---------------
Supported ``collision_type`` strings for :meth:`RT3D.fetch_collision`:
``"FT"`` (Friedrich-Tonker), ``"FT_CC"``, ``"FT_MB"``,
``"SN_EN"``, ``"SN_EI"``, ``"SN"`` (full Schunk-Nagy), ``"ATM"``.

Typical usage
-------------
>>> from hfpytrace.model import RT3D, RT3DProfile
>>> from hfpytrace.pharlap import Engine
>>> profile = RT3DProfile.from_cfg(cfg, fetch_iri=True, fetch_geomag=True)
>>> rt = RT3D(profile=profile)
>>> engine = Engine()
>>> ray_data, path_data, state = rt.raytrace(engine, elevs=[15, 30, 45, 60], nhops=2)
>>> engine.close()
"""

from __future__ import annotations

import datetime as dt
from dataclasses import dataclass
from types import SimpleNamespace

import numpy as np
from loguru import logger
from scipy.integrate import solve_ivp
from scipy.interpolate import RegularGridInterpolator

from hfpytrace.collision import NRLMSISE3D
from hfpytrace.density.iri import IRI3d
from hfpytrace.geomag import build_geomag_grid
from hfpytrace.model.dispersion import AppletonHartreeDispersion, SenWyllerDispersion

C_KM_S = 299792.458
N_FLOOR = 1e-6


@dataclass
class RT3DProfile:
    """
    3D gridded ionosphere/background container.

    Axis convention:
    - ``lats``: latitude axis, shape ``(nlat,)``
    - ``lons``: longitude axis, shape ``(nlon,)``
    - ``alts_km``: altitude axis, shape ``(nalt,)``
    - 3D fields use shape ``(nlat, nlon, nalt)``
    """

    lats: np.ndarray
    lons: np.ndarray
    alts_km: np.ndarray
    time: dt.datetime
    ne_m3: np.ndarray | None = None
    ne_cm3: np.ndarray | None = None
    source: str = "iri"
    msise: SimpleNamespace | None = None
    geomag: SimpleNamespace | None = None
    collision: object | None = (
        None  # ComputeCollision instance after compute_collision()
    )

    def __post_init__(self) -> None:
        self.lats = np.asarray(self.lats, dtype=float).ravel()
        self.lons = np.asarray(self.lons, dtype=float).ravel()
        self.alts_km = np.asarray(self.alts_km, dtype=float).ravel()
        if not isinstance(self.time, dt.datetime):
            self.time = dt.datetime.fromisoformat(str(self.time))
        self.validate()

    def validate(self) -> None:
        if self.lats.size < 2 or self.lons.size < 2 or self.alts_km.size < 2:
            raise ValueError("lats, lons, alts_km must each contain at least 2 points")
        if not np.all(np.diff(self.lats) > 0):
            raise ValueError("lats must be strictly increasing")
        if not np.all(np.diff(self.lons) > 0):
            raise ValueError("lons must be strictly increasing")
        if not np.all(np.diff(self.alts_km) > 0):
            raise ValueError("alts_km must be strictly increasing")

        shape = (self.lats.size, self.lons.size, self.alts_km.size)
        if self.ne_m3 is not None:
            ne = np.asarray(self.ne_m3, dtype=float)
            if ne.shape != shape:
                raise ValueError(f"ne_m3 must have shape {shape}")
            if np.any(ne < 0):
                raise ValueError("ne_m3 must be non-negative")
            self.ne_m3 = ne
            self.ne_cm3 = ne * 1e-6
        elif self.ne_cm3 is not None:
            ne = np.asarray(self.ne_cm3, dtype=float)
            if ne.shape != shape:
                raise ValueError(f"ne_cm3 must have shape {shape}")
            if np.any(ne < 0):
                raise ValueError("ne_cm3 must be non-negative")
            self.ne_cm3 = ne
            self.ne_m3 = ne * 1e6

        if self.msise is not None:
            for k in ("N2", "O2", "O", "H", "He", "Tn"):
                if not hasattr(self.msise, k):
                    raise ValueError(f"msise missing required field: {k}")
                arr = np.asarray(getattr(self.msise, k), dtype=float)
                if arr.shape != shape:
                    raise ValueError(f"msise.{k} must have shape {shape}")
                setattr(self.msise, k, arr)

        if self.geomag is not None:
            for k in ("Bx", "By", "Bz", "bmag_t", "inc_deg", "psi_deg"):
                if not hasattr(self.geomag, k):
                    raise ValueError(f"geomag missing required field: {k}")
                arr = np.asarray(getattr(self.geomag, k), dtype=float)
                if arr.shape != shape:
                    raise ValueError(f"geomag.{k} must have shape {shape}")
                setattr(self.geomag, k, arr)

    @staticmethod
    def _axis_from_cfg(start: float, step: float, count: int, name: str) -> np.ndarray:
        n = int(count)
        if n < 2:
            raise ValueError(f"{name} count must be >= 2")
        return float(start) + float(step) * np.arange(n, dtype=float)

    @classmethod
    def from_cfg(
        cls,
        cfg,
        time: dt.datetime | None = None,
        lats: np.ndarray | None = None,
        lons: np.ndarray | None = None,
        alts_km: np.ndarray | None = None,
        fetch_iri: bool = True,
        fetch_msise: bool = False,
        fetch_geomag: bool = False,
        workers: int = 1,
    ) -> "RT3DProfile":
        """
        Build a profile from explicit axes or config-driven 3D grid settings.

        Grid source priority:
        1) explicit lats/lons/alts_km
        2) ``cfg.iono_grid`` fields
        3) fallback from global 2D-style height settings and coarse CONUS-like lat/lon grid
        """
        t = time if time is not None else dt.datetime.fromisoformat(str(cfg.event))

        if lats is None or lons is None or alts_km is None:
            if hasattr(cfg, "iono_grid"):
                ig = cfg.iono_grid
                lats = cls._axis_from_cfg(
                    start=float(ig.lat_start),
                    step=float(ig.lat_step),
                    count=int(ig.num_lats),
                    name="lat",
                )
                lons = cls._axis_from_cfg(
                    start=float(ig.lon_start),
                    step=float(ig.lon_step),
                    count=int(ig.num_lons),
                    name="lon",
                )
                alts_km = cls._axis_from_cfg(
                    start=float(ig.height_start_km),
                    step=float(ig.height_step_km),
                    count=int(ig.num_heights),
                    name="height",
                )
            else:
                logger.warning(
                    "cfg.iono_grid not found; using fallback lat/lon axes and cfg height settings."
                )
                lats = np.linspace(24.0, 50.0, 53)
                lons = np.linspace(-125.0, -66.0, 119)
                h0 = float(getattr(cfg, "start_height_km", 100.0))
                h1 = float(getattr(cfg, "end_height_km", 500.0))
                dh = float(getattr(cfg, "height_incriment_km", 5.0))
                alts_km = np.arange(h0, h1, dh, dtype=float)

        p = cls(
            lats=np.asarray(lats, dtype=float).ravel(),
            lons=np.asarray(lons, dtype=float).ravel(),
            alts_km=np.asarray(alts_km, dtype=float).ravel(),
            time=t,
        )
        logger.info(
            "RT3DProfile created: nlat={}, nlon={}, nalt={}",
            p.lats.size,
            p.lons.size,
            p.alts_km.size,
        )
        if fetch_iri:
            p.fetch_iri(cfg=cfg, workers=int(workers))
        if fetch_msise:
            p.fetch_msise(workers=int(workers))
        if fetch_geomag:
            gm_cfg = getattr(cfg, "geomag_grid", SimpleNamespace(coord_input="GEO"))
            p.fetch_geomag(
                coord_input=str(getattr(gm_cfg, "coord_input", "GEO")),
                coeff_dir=getattr(gm_cfg, "coeff_dir", None),
            )
        p.validate()
        return p

    def set_electron_density(
        self,
        ne_m3: np.ndarray | None = None,
        ne_cm3: np.ndarray | None = None,
        source: str = "iri",
    ) -> None:
        if (ne_m3 is None) == (ne_cm3 is None):
            raise ValueError("Provide exactly one of ne_m3 or ne_cm3")
        self.source = str(source)
        if ne_m3 is not None:
            self.ne_m3 = np.asarray(ne_m3, dtype=float)
            self.ne_cm3 = self.ne_m3 * 1e-6
        else:
            self.ne_cm3 = np.asarray(ne_cm3, dtype=float)
            self.ne_m3 = self.ne_cm3 * 1e6
        self.validate()

    def force_zero_density_below(self, min_alt_km: float) -> int:
        """Set all density values to zero for ``alt < min_alt_km``."""
        if self.ne_m3 is None or self.ne_cm3 is None:
            raise ValueError(
                "Electron density is not initialized; call fetch_iri() or set_electron_density() first."
            )
        below = np.asarray(self.alts_km, dtype=float) < float(min_alt_km)
        n_rows = int(np.count_nonzero(below))
        if n_rows == 0:
            return 0
        self.ne_m3[:, :, below] = 0.0
        self.ne_cm3[:, :, below] = 0.0
        self.validate()
        return n_rows

    def fetch_iri(self, cfg, workers: int = 1) -> np.ndarray:
        logger.info(
            "Fetching 3D IRI profile: nlat={}, nlon={}, nalt={}",
            self.lats.size,
            self.lons.size,
            self.alts_km.size,
        )
        model = IRI3d(cfg, self.time)
        ne_cm3, _ = model.fetch_dataset(
            time=self.time,
            lats=self.lats,
            lons=self.lons,
            alts=self.alts_km,
            workers=int(workers),
        )
        self.ne_cm3 = np.asarray(ne_cm3, dtype=float)
        self.ne_m3 = self.ne_cm3 * 1e6
        self.source = "iri"
        self.validate()
        return self.ne_m3

    def fetch_msise(
        self,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ) -> SimpleNamespace:
        logger.info(
            "Fetching 3D NRLMSISE profile: nlat={}, nlon={}, nalt={}, workers={}",
            self.lats.size,
            self.lons.size,
            self.alts_km.size,
            int(workers),
        )
        ms = NRLMSISE3D(
            date=self.time,
            lats=self.lats,
            lons=self.lons,
            heights_km=self.alts_km,
            workers=int(workers),
            update_spaceweather=bool(update_spaceweather),
            suppress_spaceweather_warning=bool(suppress_spaceweather_warning),
        ).msise
        self.msise = SimpleNamespace(
            N2=np.asarray(ms["N2"], dtype=float),
            O2=np.asarray(ms["O2"], dtype=float),
            O=np.asarray(ms["O"], dtype=float),
            H=np.asarray(ms["H"], dtype=float),
            He=np.asarray(ms["He"], dtype=float),
            Tn=np.asarray(ms["Tn"], dtype=float),
            t_nn=np.asarray(ms["t_nn"], dtype=float),
        )
        self.validate()
        return self.msise

    def fetch_geomag(
        self,
        coord_input: str = "GEO",
        coeff_dir: str | None = None,
    ) -> SimpleNamespace:
        logger.info(
            "Fetching 3D geomag profile: nlat={}, nlon={}, nalt={}",
            self.lats.size,
            self.lons.size,
            self.alts_km.size,
        )
        gm = build_geomag_grid(
            lats=self.lats,
            lons=self.lons,
            alts_km=self.alts_km,
            time=self.time,
            coord_input=coord_input,
            coeff_dir=coeff_dir,
        )
        self.geomag = SimpleNamespace(
            Bx=np.asarray(gm.Bx, dtype=float),
            By=np.asarray(gm.By, dtype=float),
            Bz=np.asarray(gm.Bz, dtype=float),
            bmag_t=np.asarray(gm.bmag_t, dtype=float),
            inc_deg=np.asarray(gm.inc_deg, dtype=float),
            dec_deg=np.asarray(gm.dec_deg, dtype=float),
            psi_deg=np.asarray(gm.psi_deg, dtype=float),
            lat_geo=np.asarray(gm.lat_geo, dtype=float),
            lon_geo=np.asarray(gm.lon_geo, dtype=float),
            qd=gm.qd,
            apex=gm.apex,
        )
        self.validate()
        return self.geomag

    def compute_collision(
        self,
        Te: np.ndarray | float | None = None,
        Ti: np.ndarray | float | None = None,
        edens: np.ndarray | None = None,
        O2p: np.ndarray | None = None,
        Op: np.ndarray | None = None,
    ) -> object:
        """
        Compute collision frequencies using the already-fetched MSIS neutral data.

        Requires ``self.msise`` (call ``fetch_msise()`` first) and electron
        density (call ``fetch_iri()`` or ``set_electron_density()`` first).

        Parameters
        ----------
        Te, Ti : array-like or float, optional
            Electron/ion temperature [K], shape (nlat, nlon, nalt) or broadcastable.
            Defaults to MSIS neutral temperature Tn.
        edens : array-like, optional
            Electron density [cm^-3], shape (nlat, nlon, nalt).
            Defaults to ``self.ne_cm3``.
        O2p, Op : array-like, optional
            O2+ and O+ densities [cm^-3]. Defaults to 10%/90% of edens.

        Returns
        -------
        ComputeCollision
            Also stored on ``self.collision`` for retrieval via
            ``collision_type`` in :class:`RT3D`.

        Notes
        -----
        Supported ``collision_type`` keys:

        +-------------+--------------------------------------------------+
        | Key         | Model                                            |
        +=============+==================================================+
        | ``"FT"``    | Friedrich-Tonker (ν_ft, a=1.0)                   |
        | ``"FT_cc"`` | Friedrich-Tonker (ν_av_cc, a=2.5)                |
        | ``"FT_mb"`` | Friedrich-Tonker (ν_av_mb, a=1.5)                |
        | ``"SN_en"`` | Schunk-Nagy electron-neutral total               |
        | ``"SN_ei"`` | Schunk-Nagy electron-ion total                   |
        | ``"SN"``    | Schunk-Nagy full (en + ei)                       |
        | ``"atm"``   | Atmospheric ion-neutral approximation            |
        +-------------+--------------------------------------------------+
        """
        from hfpytrace.collision import ComputeCollision

        if self.msise is None:
            raise ValueError(
                "MSIS neutral data not available. Call fetch_msise() first."
            )
        if self.ne_cm3 is None:
            raise ValueError(
                "Electron density not set. "
                "Call fetch_iri() or set_electron_density() first."
            )

        Tn = np.asarray(self.msise.Tn, dtype=float)  # shape (nlat, nlon, nalt)
        ne = np.asarray(self.ne_cm3, dtype=float)

        Te_use = np.asarray(Te, dtype=float) if Te is not None else Tn.copy()
        Ti_use = np.asarray(Ti, dtype=float) if Ti is not None else Tn.copy()
        edens_use = np.asarray(edens, dtype=float) if edens is not None else ne.copy()
        Op_use = np.asarray(Op, dtype=float) if Op is not None else 0.9 * ne
        O2p_use = np.asarray(O2p, dtype=float) if O2p is not None else 0.1 * ne

        cc = ComputeCollision(
            Te=Te_use,
            Ti=Ti_use,
            Tn=Tn,
            edens=edens_use,
            O2p=O2p_use,
            Op=Op_use,
            N2=np.asarray(self.msise.N2, dtype=float),
            O2=np.asarray(self.msise.O2, dtype=float),
            O=np.asarray(self.msise.O, dtype=float),
            H=np.asarray(self.msise.H, dtype=float),
            He=np.asarray(self.msise.He, dtype=float),
            date=self.time,
        )
        self.collision = cc
        logger.info(
            "3D collision computed: nu_ft=[{:.3e},{:.3e}] Hz, nu_sn=[{:.3e},{:.3e}] Hz",
            float(np.nanmin(cc.collision.nu_ft)),
            float(np.nanmax(cc.collision.nu_ft)),
            float(np.nanmin(cc.collision.nu_sn.total)),
            float(np.nanmax(cc.collision.nu_sn.total)),
        )
        return cc


class RT3D:
    """
    Minimal RT3D container for downstream 3D tracing implementations.

    This class currently focuses on profile management and data integrity checks.
    """

    _VALID_COLLISION_TYPES: frozenset[str] = frozenset(
        {"FT", "FT_CC", "FT_MB", "SN_EN", "SN_EI", "SN", "ATM"}
    )

    @staticmethod
    def _extract_collision_hz(cc, collision_type: str) -> np.ndarray:
        """
        Extract a collision-frequency array from a ``ComputeCollision`` object.

        The returned array has the same shape as the 3D profile fields
        ``(nlat, nlon, nalt)`` and can be sliced/interpolated for ray tracing.

        Parameters
        ----------
        cc : ComputeCollision
        collision_type : str
            One of ``"FT"``, ``"FT_cc"``, ``"FT_mb"``, ``"SN_en"``,
            ``"SN_ei"``, ``"SN"``, ``"atm"`` (case-insensitive).
        """
        ct = str(collision_type).strip().upper()
        _map = {
            "FT": lambda c: np.asarray(c.collision.nu_ft, dtype=float),
            "FT_CC": lambda c: np.asarray(c.collision.nu_av_cc, dtype=float),
            "FT_MB": lambda c: np.asarray(c.collision.nu_av_mb, dtype=float),
            "SN_EN": lambda c: np.asarray(c.collision.nu_sn.en.total, dtype=float),
            "SN_EI": lambda c: np.asarray(c.collision.nu_sn.ei.total, dtype=float),
            "SN": lambda c: np.asarray(c.collision.nu_sn.total, dtype=float),
            "ATM": lambda c: np.asarray(
                c.atmospheric_ion_neutral_collision_frequency(), dtype=float
            ),
        }
        if ct not in _map:
            raise ValueError(
                f"Unknown collision_type '{collision_type}'. "
                f"Valid options: {sorted(_map.keys())}"
            )
        return _map[ct](cc)

    def fetch_collision(
        self,
        Te: np.ndarray | float | None = None,
        Ti: np.ndarray | float | None = None,
        edens: np.ndarray | None = None,
        O2p: np.ndarray | None = None,
        Op: np.ndarray | None = None,
    ) -> object:
        """
        Compute and attach collision frequencies to the profile.

        Convenience wrapper around :meth:`RT3DProfile.compute_collision`.
        Requires that ``fetch_msise()`` has been called on the profile.

        Returns
        -------
        ComputeCollision
        """
        return self.profile.compute_collision(
            Te=Te,
            Ti=Ti,
            edens=edens,
            O2p=O2p,
            Op=Op,
        )

    def __init__(
        self,
        *,
        profile: RT3DProfile | None = None,
        cfg=None,
        time: dt.datetime | str | None = None,
        lats: np.ndarray | None = None,
        lons: np.ndarray | None = None,
        alts_km: np.ndarray | None = None,
        ne_m3: np.ndarray | None = None,
        ne_cm3: np.ndarray | None = None,
        source: str = "iri",
        fetch_iri: bool = False,
        fetch_msise: bool = False,
        fetch_geomag: bool = False,
        workers: int = 1,
    ):
        if profile is not None:
            if not isinstance(profile, RT3DProfile):
                raise TypeError("profile must be an RT3DProfile")
            profile.validate()
            self.profile = profile
        else:
            if cfg is None:
                raise ValueError("Provide profile or cfg for RT3D initialization")
            t = time if time is not None else dt.datetime.fromisoformat(str(cfg.event))
            self.profile = RT3DProfile.from_cfg(
                cfg=cfg,
                time=t,
                lats=lats,
                lons=lons,
                alts_km=alts_km,
                fetch_iri=bool(fetch_iri),
                fetch_msise=bool(fetch_msise),
                fetch_geomag=bool(fetch_geomag),
                workers=int(workers),
            )

        if (ne_m3 is not None) or (ne_cm3 is not None):
            self.profile.set_electron_density(ne_m3=ne_m3, ne_cm3=ne_cm3, source=source)
        self.profile.validate()
        if self.profile.ne_m3 is None:
            logger.warning(
                "RT3D initialized without electron density; set ne_m3/ne_cm3 or fetch_iri=True."
            )
        logger.info(
            "RT3D initialized: nlat={}, nlon={}, nalt={}, source={}",
            self.profile.lats.size,
            self.profile.lons.size,
            self.profile.alts_km.size,
            self.profile.source,
        )
        # Cache for expensive refractive-index/interpolator construction.
        self._interp_cache_key = None
        self._interp_cache_out = None

    @property
    def lats(self) -> np.ndarray:
        return self.profile.lats

    @property
    def lons(self) -> np.ndarray:
        return self.profile.lons

    @property
    def alts_km(self) -> np.ndarray:
        return self.profile.alts_km

    @property
    def ne_m3(self) -> np.ndarray | None:
        return self.profile.ne_m3

    @staticmethod
    def _resolve_dispersion_model_name(formulation: str) -> str:
        name = str(formulation).strip().lower().replace("_", "-")
        alias_map = {
            "appleton": "appleton-hartree",
            "appleton-hartree": "appleton-hartree",
            "ah": "appleton-hartree",
            "senwyller": "sen-wyller",
            "sen-wyller": "sen-wyller",
            "sw": "sen-wyller",
        }
        if name not in alias_map:
            raise ValueError(
                "Unsupported dispersion model. Use 'appleton-hartree' or 'sen-wyller'."
            )
        return alias_map[name]

    def _build_local_xy_axes(self) -> tuple[np.ndarray, np.ndarray, float, float]:
        lat0 = float(np.mean(self.lats))
        lon0 = float(np.mean(self.lons))
        km_per_deg_lat = 111.32
        km_per_deg_lon = km_per_deg_lat * np.cos(np.deg2rad(lat0))
        x_km = (np.asarray(self.lons, dtype=float) - lon0) * km_per_deg_lon
        y_km = (np.asarray(self.lats, dtype=float) - lat0) * km_per_deg_lat
        return x_km, y_km, lat0, lon0

    def build_refractive_index_interpolators(
        self,
        freq_hz: float,
        b_abs_t: np.ndarray | float | None = None,
        b_psi_deg: np.ndarray | float | None = None,
        collision_hz: np.ndarray | float | None = None,
        mode: str = "O",
        formulation: str = "appleton-hartree",
    ) -> SimpleNamespace:
        cache_key = (
            float(freq_hz),
            str(mode),
            str(formulation),
            id(b_abs_t) if b_abs_t is not None else None,
            id(b_psi_deg) if b_psi_deg is not None else None,
            id(collision_hz) if collision_hz is not None else None,
            id(self.profile.ne_m3),
        )
        if self._interp_cache_key == cache_key and self._interp_cache_out is not None:
            return self._interp_cache_out

        if self.ne_m3 is None:
            raise ValueError("RT3D profile has no electron density.")
        ne = np.asarray(self.ne_m3, dtype=float)
        shape = ne.shape
        model_name = self._resolve_dispersion_model_name(formulation)

        if b_abs_t is None:
            if self.profile.geomag is not None:
                b_t = np.asarray(self.profile.geomag.bmag_t, dtype=float)
            else:
                b_t = np.zeros(shape, dtype=float)
        else:
            b_t = np.asarray(b_abs_t, dtype=float)
            if b_t.ndim == 0:
                b_t = np.full(shape, float(b_t), dtype=float)
        if b_psi_deg is None:
            if self.profile.geomag is not None:
                theta = np.asarray(self.profile.geomag.psi_deg, dtype=float)
            else:
                theta = np.zeros(shape, dtype=float)
        else:
            theta = np.asarray(b_psi_deg, dtype=float)
            if theta.ndim == 0:
                theta = np.full(shape, float(theta), dtype=float)
        if collision_hz is None:
            nu = np.zeros(shape, dtype=float)
        else:
            nu = np.asarray(collision_hz, dtype=float)
            if nu.ndim == 0:
                nu = np.full(shape, float(nu), dtype=float)
            if nu.shape != shape:
                raise ValueError(f"collision_hz must have shape {shape}")

        if model_name == "appleton-hartree":
            disp = AppletonHartreeDispersion(
                frequency_hz=float(freq_hz),
                ne_m3=ne,
                collision_hz=nu,
                b_t=b_t,
                theta_deg=theta,
            )
        else:
            disp = SenWyllerDispersion(
                frequency_hz=float(freq_hz),
                ne_m3=ne,
                collision_hz=nu,
                b_t=b_t,
                theta_deg=theta,
            )

        n_complex = disp.refractive_index(mode=mode)
        n = np.real(n_complex)
        # Harden against singular/invalid dispersion outputs.
        n = np.where(np.isfinite(n), np.clip(n, 0.0, None), np.nan)
        if np.any(~np.isfinite(n)):
            n = np.nan_to_num(n, nan=0.0, posinf=0.0, neginf=0.0)
        n = np.clip(n, N_FLOOR, None)
        mup = 1.0 / np.clip(n, N_FLOOR, None)

        # 3D interpolators on physical local axes (z, y, x).
        x_km, y_km, lat_ref_deg, lon_ref_deg = self._build_local_xy_axes()
        z_km = np.asarray(self.alts_km, dtype=float)
        n_zyx = np.transpose(n, (2, 0, 1))
        mup_zyx = np.transpose(mup, (2, 0, 1))
        dn_dz, dn_dy, dn_dx = np.gradient(n_zyx, z_km, y_km, x_km, edge_order=2)

        self._x_km = x_km
        self._y_km = y_km
        self._z_km = z_km
        self._lat_ref_deg = lat_ref_deg
        self._lon_ref_deg = lon_ref_deg

        self._n_interp_zyx = RegularGridInterpolator(
            (z_km, y_km, x_km), n_zyx, bounds_error=False, fill_value=np.nan
        )
        self._mup_interp_zyx = RegularGridInterpolator(
            (z_km, y_km, x_km), mup_zyx, bounds_error=False, fill_value=np.nan
        )
        self._dn_dx_interp_zyx = RegularGridInterpolator(
            (z_km, y_km, x_km), dn_dx, bounds_error=False, fill_value=np.nan
        )
        self._dn_dy_interp_zyx = RegularGridInterpolator(
            (z_km, y_km, x_km), dn_dy, bounds_error=False, fill_value=np.nan
        )
        self._dn_dz_interp_zyx = RegularGridInterpolator(
            (z_km, y_km, x_km), dn_dz, bounds_error=False, fill_value=np.nan
        )

        # Also keep altitude-lat-lon interpolators for spherical mode.
        self._n_interp_altll = RegularGridInterpolator(
            (self.alts_km, self.lats, self.lons),
            np.transpose(n, (2, 0, 1)),
            bounds_error=False,
            fill_value=np.nan,
        )
        self._mup_interp_altll = RegularGridInterpolator(
            (self.alts_km, self.lats, self.lons),
            np.transpose(mup, (2, 0, 1)),
            bounds_error=False,
            fill_value=np.nan,
        )
        logger.info(
            "RT3D refractive index interpolators ready: freq={} Hz, mode={}, model={}",
            float(freq_hz),
            mode,
            model_name,
        )
        out = SimpleNamespace(n=n, mup=mup)
        self._interp_cache_key = cache_key
        self._interp_cache_out = out
        return out

    def _eval_n_grad_cart(
        self, x_km: np.ndarray, y_km: np.ndarray, z_km: np.ndarray
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        x = np.atleast_1d(np.asarray(x_km, dtype=float))
        y = np.atleast_1d(np.asarray(y_km, dtype=float))
        z = np.atleast_1d(np.asarray(z_km, dtype=float))
        x, y, z = np.broadcast_arrays(x, y, z)
        if hasattr(self, "_x_km") and hasattr(self, "_y_km") and hasattr(self, "_z_km"):
            eps = 1e-6
            x = np.clip(x, float(self._x_km[0]) + eps, float(self._x_km[-1]) - eps)
            y = np.clip(y, float(self._y_km[0]) + eps, float(self._y_km[-1]) - eps)
            z = np.clip(z, float(self._z_km[0]) + eps, float(self._z_km[-1]) - eps)
        pts = np.column_stack([z.ravel(), y.ravel(), x.ravel()])
        n = self._n_interp_zyx(pts).reshape(x.shape)
        dnx = self._dn_dx_interp_zyx(pts).reshape(x.shape)
        dny = self._dn_dy_interp_zyx(pts).reshape(x.shape)
        dnz = self._dn_dz_interp_zyx(pts).reshape(x.shape)
        return n, dnx, dny, dnz

    def _eval_mup_cart(
        self, x_km: np.ndarray, y_km: np.ndarray, z_km: np.ndarray
    ) -> np.ndarray:
        x = np.atleast_1d(np.asarray(x_km, dtype=float))
        y = np.atleast_1d(np.asarray(y_km, dtype=float))
        z = np.atleast_1d(np.asarray(z_km, dtype=float))
        x, y, z = np.broadcast_arrays(x, y, z)
        if hasattr(self, "_x_km") and hasattr(self, "_y_km") and hasattr(self, "_z_km"):
            eps = 1e-6
            x = np.clip(x, float(self._x_km[0]) + eps, float(self._x_km[-1]) - eps)
            y = np.clip(y, float(self._y_km[0]) + eps, float(self._y_km[-1]) - eps)
            z = np.clip(z, float(self._z_km[0]) + eps, float(self._z_km[-1]) - eps)
        pts = np.column_stack([z.ravel(), y.ravel(), x.ravel()])
        return self._mup_interp_zyx(pts).reshape(x.shape)

    @staticmethod
    def _rhs_cart(_s: float, y: np.ndarray, n_grad_fn) -> np.ndarray:
        x, yy, z, vx, vy, vz = y
        n, dnx, dny, dnz = n_grad_fn(np.array([x]), np.array([yy]), np.array([z]))
        n = float(n[0])
        dnx = float(dnx[0])
        dny = float(dny[0])
        dnz = float(dnz[0])
        if not np.isfinite(n) or n <= 0.0:
            return np.zeros(6, dtype=float)
        dot = dnx * vx + dny * vy + dnz * vz
        dvx = (dnx - dot * vx) / n
        dvy = (dny - dot * vy) / n
        dvz = (dnz - dot * vz) / n
        return np.array([vx, vy, vz, dvx, dvy, dvz], dtype=float)

    def trace_cartesian_gradient(
        self,
        freq_hz: float,
        elevation_deg: float,
        azimuth_deg: float = 0.0,
        x0_km: float = 0.0,
        y0_km: float = 0.0,
        z0_km: float = 0.0,
        s_max_km: float = 6000.0,
        mode: str = "O",
        collision_hz: np.ndarray | float | None = None,
        b_abs_t: np.ndarray | float | None = None,
        b_psi_deg: np.ndarray | float | None = None,
        formulation: str = "appleton-hartree",
        rtol: float = 1e-7,
        atol: float = 1e-9,
        max_step_km: float | None = None,
    ) -> SimpleNamespace:
        self.build_refractive_index_interpolators(
            freq_hz=freq_hz,
            b_abs_t=b_abs_t,
            b_psi_deg=b_psi_deg,
            collision_hz=collision_hz,
            mode=mode,
            formulation=formulation,
        )
        elev = np.deg2rad(float(elevation_deg))
        az = np.deg2rad(float(azimuth_deg))
        vx0 = np.cos(elev) * np.cos(az)
        vy0 = np.cos(elev) * np.sin(az)
        vz0 = np.sin(elev)
        vnorm = np.linalg.norm([vx0, vy0, vz0])
        vx0, vy0, vz0 = vx0 / vnorm, vy0 / vnorm, vz0 / vnorm
        yinit = np.array([x0_km, y0_km, z0_km, vx0, vy0, vz0], dtype=float)

        zmin, zmax = float(self._z_km[0]), float(self._z_km[-1])
        ymin, ymax = float(self._y_km[0]), float(self._y_km[-1])
        xmin, xmax = float(self._x_km[0]), float(self._x_km[-1])

        def ev_zmin(_s, y):
            return y[2] - zmin - 1e-3

        def ev_zmax(_s, y):
            return zmax - y[2]

        def ev_ymin(_s, y):
            return y[1] - ymin

        def ev_ymax(_s, y):
            return ymax - y[1]

        def ev_xmin(_s, y):
            return y[0] - xmin

        def ev_xmax(_s, y):
            return xmax - y[0]

        for ev in (ev_zmin, ev_zmax, ev_ymin, ev_ymax, ev_xmin, ev_xmax):
            ev.terminal = True
            ev.direction = -1.0

        sol = solve_ivp(
            lambda s, y: self._rhs_cart(s, y, self._eval_n_grad_cart),
            (0.0, float(s_max_km)),
            yinit,
            rtol=float(rtol),
            atol=float(atol),
            max_step=float(max_step_km) if max_step_km is not None else np.inf,
            events=[ev_zmin, ev_zmax, ev_ymin, ev_ymax, ev_xmin, ev_xmax],
        )
        x = sol.y[0, :]
        yy = sol.y[1, :]
        z = sol.y[2, :]
        ds = np.sqrt(np.diff(x) ** 2 + np.diff(yy) ** 2 + np.diff(z) ** 2)
        group_path_km = float(np.nansum(ds))
        xm = 0.5 * (x[:-1] + x[1:])
        ym = 0.5 * (yy[:-1] + yy[1:])
        zm = 0.5 * (z[:-1] + z[1:])
        mup = np.asarray(self._eval_mup_cart(xm, ym, zm), dtype=float)
        valid = np.isfinite(mup)
        group_delay_sec = float(np.nansum((mup[valid] / C_KM_S) * ds[valid]))
        status = "length"
        if sol.status == 1:
            status = "ground" if len(sol.t_events[0]) > 0 else "domain"
        elif sol.status == -1:
            status = "failure"
        return SimpleNamespace(
            x_km=x,
            y_km=yy,
            z_km=z,
            vx=sol.y[3, :],
            vy=sol.y[4, :],
            vz=sol.y[5, :],
            t=sol.t,
            status=status,
            reason=status,
            group_path_km=group_path_km,
            group_delay_sec=group_delay_sec,
            mode=mode,
            coordinate_system="cartesian",
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            azimuth_deg=float(azimuth_deg),
        )

    def trace_cartesian_hamiltonian(
        self,
        freq_hz: float,
        elevation_deg: float,
        azimuth_deg: float = 0.0,
        x0_km: float = 0.0,
        y0_km: float = 0.0,
        z0_km: float = 0.0,
        s_max_km: float = 6000.0,
        mode: str = "O",
        collision_hz: np.ndarray | float | None = None,
        b_abs_t: np.ndarray | float | None = None,
        b_psi_deg: np.ndarray | float | None = None,
        formulation: str = "appleton-hartree",
        h0_km: float = 2.0,
        h_min_km: float = 0.25,
        h_max_km: float = 8.0,
        max_step_km: float | None = None,
        local_err_tol_km: float = 5e-3,
        max_steps: int = 20000,
        boundary_eps_km: float = 1e-3,
    ) -> SimpleNamespace:
        """
        Adaptive 3D Cartesian Hamiltonian solver for isotropic n(x).

        Hamiltonian:
            H(x, p) = 0.5 (|p|^2 - n(x)^2) = 0
        Equations:
            dx/dtau = p
            dp/dtau = 0.5 * grad(n^2) = n * grad(n)
        """
        self.build_refractive_index_interpolators(
            freq_hz=freq_hz,
            b_abs_t=b_abs_t,
            b_psi_deg=b_psi_deg,
            collision_hz=collision_hz,
            mode=mode,
            formulation=formulation,
        )

        zmin, zmax = float(self._z_km[0]), float(self._z_km[-1])
        ymin, ymax = float(self._y_km[0]), float(self._y_km[-1])
        xmin, xmax = float(self._x_km[0]), float(self._x_km[-1])
        beps = max(0.0, float(boundary_eps_km))

        def _inside_domain(x: float, yv: float, z: float, margin: float = 0.0) -> bool:
            return (
                (xmin + margin) <= float(x) <= (xmax - margin)
                and (ymin + margin) <= float(yv) <= (ymax - margin)
                and (zmin + margin) <= float(z) <= (zmax - margin)
            )

        def _deriv(yvec: np.ndarray):
            x, yy, z, px, py, pz = yvec
            n, dnx, dny, dnz = self._eval_n_grad_cart(
                np.array([x]), np.array([yy]), np.array([z])
            )
            n = float(n[0])
            dnx = float(dnx[0])
            dny = float(dny[0])
            dnz = float(dnz[0])
            if (not np.isfinite(n)) or (n <= 0.0):
                return None
            dxdt = np.array([px, py, pz], dtype=float)
            dpdt = np.array([n * dnx, n * dny, n * dnz], dtype=float)
            return np.concatenate([dxdt, dpdt])

        def _rk4(yvec: np.ndarray, h: float):
            k1 = _deriv(yvec)
            if k1 is None:
                return None
            k2 = _deriv(yvec + 0.5 * h * k1)
            if k2 is None:
                return None
            k3 = _deriv(yvec + 0.5 * h * k2)
            if k3 is None:
                return None
            k4 = _deriv(yvec + h * k3)
            if k4 is None:
                return None
            return yvec + (h / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4)

        # Initial canonical momentum p0 = n0 * ray_direction_unit
        elev = np.deg2rad(float(elevation_deg))
        az = np.deg2rad(float(azimuth_deg))
        ux = np.cos(elev) * np.cos(az)
        uy = np.cos(elev) * np.sin(az)
        uz = np.sin(elev)
        u = np.array([ux, uy, uz], dtype=float)
        un = np.linalg.norm(u)
        if un <= 0:
            raise ValueError("Invalid launch direction norm")
        u /= un
        n0_arr = self._eval_n_grad_cart(
            np.array([x0_km]), np.array([y0_km]), np.array([z0_km])
        )[0]
        n0 = float(n0_arr[0])
        if (not np.isfinite(n0)) or (n0 <= 0.0):
            raise ValueError("Launch point refractive index is invalid")
        p0 = n0 * u
        y = np.array([x0_km, y0_km, z0_km, p0[0], p0[1], p0[2]], dtype=float)

        if max_step_km is not None:
            h_max_km = min(float(h_max_km), float(max_step_km))
        h = float(np.clip(h0_km, h_min_km, h_max_km))
        tau = 0.0
        tau_max = float(s_max_km)
        xs = [float(y[0])]
        ys = [float(y[1])]
        zs = [float(y[2])]
        pxs = [float(y[3])]
        pys = [float(y[4])]
        pzs = [float(y[5])]
        status = "length"

        for _ in range(int(max_steps)):
            if tau >= tau_max:
                status = "length"
                break
            # Boundary handling: allow starts on boundaries if the ray points inward.
            if y[2] <= zmin + 1e-3 and y[5] < 0:
                status = "ground"
                break
            if (
                (y[2] >= zmax and y[5] > 0)
                or (y[1] <= ymin and y[4] < 0)
                or (y[1] >= ymax and y[4] > 0)
                or (y[0] <= xmin and y[3] < 0)
                or (y[0] >= xmax and y[3] > 0)
            ):
                status = "domain"
                break

            h_try = min(h, tau_max - tau)
            y_big = _rk4(y, h_try)
            if y_big is None:
                if h_try > h_min_km:
                    h = max(h_min_km, 0.5 * h_try)
                    continue
                status = "failure"
                break
            y_half = _rk4(y, 0.5 * h_try)
            if y_half is None:
                if h_try > h_min_km:
                    h = max(h_min_km, 0.5 * h_try)
                    continue
                status = "failure"
                break
            y_half2 = _rk4(y_half, 0.5 * h_try)
            if y_half2 is None:
                if h_try > h_min_km:
                    h = max(h_min_km, 0.5 * h_try)
                    continue
                status = "failure"
                break

            # If the candidate step exits the safe interpolation interior,
            # reduce step first; if already at minimum step, terminate as domain.
            if not _inside_domain(y_half2[0], y_half2[1], y_half2[2], margin=beps):
                if h_try > h_min_km:
                    h = max(h_min_km, 0.5 * h_try)
                    continue
                status = "domain" if y_half2[2] > zmin + beps else "ground"
                break

            err = np.linalg.norm(y_half2[:3] - y_big[:3], ord=2)
            if np.isfinite(err) and err > local_err_tol_km and h_try > h_min_km:
                h = max(h_min_km, 0.5 * h_try)
                continue

            # Accept higher-accuracy step (step-doubling result)
            y = y_half2
            # Project momentum back to |p| = n to reduce drift.
            n_now = self._eval_n_grad_cart(
                np.array([y[0]]), np.array([y[1]]), np.array([y[2]])
            )[0][0]
            pnorm = np.linalg.norm(y[3:6])
            if np.isfinite(n_now) and n_now > 0 and pnorm > 0:
                y[3:6] = y[3:6] * (float(n_now) / float(pnorm))

            tau += h_try
            xs.append(float(y[0]))
            ys.append(float(y[1]))
            zs.append(float(y[2]))
            pxs.append(float(y[3]))
            pys.append(float(y[4]))
            pzs.append(float(y[5]))

            if np.isfinite(err) and err < 0.25 * local_err_tol_km:
                h = min(h_max_km, 2.0 * h_try)
            else:
                h = h_try
        else:
            status = "failure"

        x = np.asarray(xs, dtype=float)
        yy = np.asarray(ys, dtype=float)
        z = np.asarray(zs, dtype=float)
        px = np.asarray(pxs, dtype=float)
        py = np.asarray(pys, dtype=float)
        pz = np.asarray(pzs, dtype=float)

        ds = np.sqrt(np.diff(x) ** 2 + np.diff(yy) ** 2 + np.diff(z) ** 2)
        group_path_km = float(np.nansum(ds))
        xm = 0.5 * (x[:-1] + x[1:])
        ym = 0.5 * (yy[:-1] + yy[1:])
        zm = 0.5 * (z[:-1] + z[1:])
        mup = np.asarray(self._eval_mup_cart(xm, ym, zm), dtype=float)
        valid = np.isfinite(mup)
        group_delay_sec = float(np.nansum((mup[valid] / C_KM_S) * ds[valid]))

        # Direction estimates from canonical momentum.
        pnorm = np.sqrt(px**2 + py**2 + pz**2)
        vx = np.divide(px, pnorm, out=np.zeros_like(px), where=pnorm > 0)
        vy = np.divide(py, pnorm, out=np.zeros_like(py), where=pnorm > 0)
        vz = np.divide(pz, pnorm, out=np.zeros_like(pz), where=pnorm > 0)

        return SimpleNamespace(
            x_km=x,
            y_km=yy,
            z_km=z,
            vx=vx,
            vy=vy,
            vz=vz,
            px=px,
            py=py,
            pz=pz,
            t=np.linspace(0.0, tau, x.size),
            status=status,
            reason=status,
            group_path_km=group_path_km,
            group_delay_sec=group_delay_sec,
            mode=mode,
            coordinate_system="cartesian",
            solver="hamiltonian",
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            azimuth_deg=float(azimuth_deg),
        )

    def _eval_n_sph(
        self, alt_km: np.ndarray, lat_deg: np.ndarray, lon_deg: np.ndarray
    ) -> np.ndarray:
        alt = np.atleast_1d(np.asarray(alt_km, dtype=float))
        lat = np.atleast_1d(np.asarray(lat_deg, dtype=float))
        lon = np.atleast_1d(np.asarray(lon_deg, dtype=float))
        alt, lat, lon = np.broadcast_arrays(alt, lat, lon)
        pts = np.column_stack([alt.ravel(), lat.ravel(), lon.ravel()])
        return self._n_interp_altll(pts).reshape(alt.shape)

    def _eval_mup_sph(
        self, alt_km: np.ndarray, lat_deg: np.ndarray, lon_deg: np.ndarray
    ) -> np.ndarray:
        alt = np.atleast_1d(np.asarray(alt_km, dtype=float))
        lat = np.atleast_1d(np.asarray(lat_deg, dtype=float))
        lon = np.atleast_1d(np.asarray(lon_deg, dtype=float))
        alt, lat, lon = np.broadcast_arrays(alt, lat, lon)
        pts = np.column_stack([alt.ravel(), lat.ravel(), lon.ravel()])
        return self._mup_interp_altll(pts).reshape(alt.shape)

    def _eval_n_grad_sph(
        self,
        r_km: np.ndarray,
        lat_rad: np.ndarray,
        lon_rad: np.ndarray,
        r_earth_km: float,
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        r = np.atleast_1d(np.asarray(r_km, dtype=float))
        lat = np.atleast_1d(np.asarray(lat_rad, dtype=float))
        lon = np.atleast_1d(np.asarray(lon_rad, dtype=float))
        r, lat, lon = np.broadcast_arrays(r, lat, lon)
        alt = r - float(r_earth_km)
        lat_deg = np.rad2deg(lat)
        lon_deg = np.rad2deg(lon)
        n = self._eval_n_sph(alt, lat_deg, lon_deg)

        dr = 1.0
        da = np.deg2rad(0.02)
        dl = np.deg2rad(0.02)
        n_rp = self._eval_n_sph(alt + dr, lat_deg, lon_deg)
        n_rm = self._eval_n_sph(alt - dr, lat_deg, lon_deg)
        n_ap = self._eval_n_sph(alt, np.rad2deg(lat + da), lon_deg)
        n_am = self._eval_n_sph(alt, np.rad2deg(lat - da), lon_deg)
        n_lp = self._eval_n_sph(alt, lat_deg, np.rad2deg(lon + dl))
        n_lm = self._eval_n_sph(alt, lat_deg, np.rad2deg(lon - dl))

        dn_dr = (n_rp - n_rm) / (2.0 * dr)
        dn_dlat = (n_ap - n_am) / (2.0 * da)
        dn_dlon = (n_lp - n_lm) / (2.0 * dl)
        return n, dn_dr, dn_dlat, dn_dlon

    @staticmethod
    def _rhs_sph(_s: float, y: np.ndarray, n_grad_fn) -> np.ndarray:
        r, lat, lon, vr, vlat, vlon = y
        n, dn_dr, dn_dlat, dn_dlon = n_grad_fn(
            np.array([r]), np.array([lat]), np.array([lon])
        )
        n = float(n[0])
        dn_dr = float(dn_dr[0])
        dn_dlat = float(dn_dlat[0])
        dn_dlon = float(dn_dlon[0])
        cl = max(np.cos(lat), 1e-6)
        if not np.isfinite(n) or n <= 0.0 or r <= 0.0:
            return np.zeros(6, dtype=float)
        grad_dot_v = dn_dr * vr + (dn_dlat / r) * vlat + (dn_dlon / (r * cl)) * vlon
        drds = vr
        dlatds = vlat / r
        dlonds = vlon / (r * cl)
        dvr = (dn_dr - grad_dot_v * vr) / n + (vlat * vlat + vlon * vlon) / r
        dvlat = (
            ((dn_dlat / r) - grad_dot_v * vlat) / n
            - (vr * vlat) / r
            + (vlon * vlon * np.tan(lat)) / r
        )
        dvlon = (
            ((dn_dlon / (r * cl)) - grad_dot_v * vlon) / n
            - (vr * vlon) / r
            - (vlat * vlon * np.tan(lat)) / r
        )
        return np.array([drds, dlatds, dlonds, dvr, dvlat, dvlon], dtype=float)

    def trace_spherical_gradient(
        self,
        freq_hz: float,
        elevation_deg: float,
        azimuth_deg: float = 0.0,
        x0_km: float = 0.0,
        y0_km: float = 0.0,
        z0_km: float = 0.0,
        s_max_km: float = 7000.0,
        mode: str = "O",
        collision_hz: np.ndarray | float | None = None,
        b_abs_t: np.ndarray | float | None = None,
        b_psi_deg: np.ndarray | float | None = None,
        formulation: str = "appleton-hartree",
        r_earth_km: float = 6371.0,
        rtol: float = 1e-7,
        atol: float = 1e-9,
        max_step_km: float | None = None,
    ) -> SimpleNamespace:
        self.build_refractive_index_interpolators(
            freq_hz=freq_hz,
            b_abs_t=b_abs_t,
            b_psi_deg=b_psi_deg,
            collision_hz=collision_hz,
            mode=mode,
            formulation=formulation,
        )
        km_per_deg_lat = 111.32
        km_per_deg_lon = km_per_deg_lat * np.cos(np.deg2rad(self._lat_ref_deg))
        lat0_deg = self._lat_ref_deg + float(y0_km) / km_per_deg_lat
        lon0_deg = self._lon_ref_deg + float(x0_km) / max(km_per_deg_lon, 1e-6)
        r0 = float(r_earth_km) + float(z0_km)
        lat0 = np.deg2rad(lat0_deg)
        lon0 = np.deg2rad(lon0_deg)

        elev = np.deg2rad(float(elevation_deg))
        az = np.deg2rad(float(azimuth_deg))
        vr0 = np.sin(elev)
        vh = np.cos(elev)
        vlat0 = vh * np.cos(az)
        vlon0 = vh * np.sin(az)
        vnorm = np.linalg.norm([vr0, vlat0, vlon0])
        vr0, vlat0, vlon0 = vr0 / vnorm, vlat0 / vnorm, vlon0 / vnorm
        yinit = np.array([r0, lat0, lon0, vr0, vlat0, vlon0], dtype=float)

        rmin = float(r_earth_km) + float(self.alts_km[0])
        rmax = float(r_earth_km) + float(self.alts_km[-1])
        lat_min = np.deg2rad(float(self.lats[0]))
        lat_max = np.deg2rad(float(self.lats[-1]))
        lon_min = np.deg2rad(float(self.lons[0]))
        lon_max = np.deg2rad(float(self.lons[-1]))

        def ev_rmin(_s, y):
            return y[0] - rmin - 1e-3

        def ev_rmax(_s, y):
            return rmax - y[0]

        def ev_latmin(_s, y):
            return y[1] - lat_min

        def ev_latmax(_s, y):
            return lat_max - y[1]

        def ev_lonmin(_s, y):
            return y[2] - lon_min

        def ev_lonmax(_s, y):
            return lon_max - y[2]

        for ev in (ev_rmin, ev_rmax, ev_latmin, ev_latmax, ev_lonmin, ev_lonmax):
            ev.terminal = True
            ev.direction = -1.0

        sol = solve_ivp(
            lambda s, y: self._rhs_sph(
                s,
                y,
                lambda r, lat, lon: self._eval_n_grad_sph(
                    r_km=r, lat_rad=lat, lon_rad=lon, r_earth_km=float(r_earth_km)
                ),
            ),
            (0.0, float(s_max_km)),
            yinit,
            rtol=float(rtol),
            atol=float(atol),
            max_step=float(max_step_km) if max_step_km is not None else np.inf,
            events=[ev_rmin, ev_rmax, ev_latmin, ev_latmax, ev_lonmin, ev_lonmax],
        )

        r = sol.y[0, :]
        lat = sol.y[1, :]
        lon = sol.y[2, :]
        z = r - float(r_earth_km)
        lat_deg = np.rad2deg(lat)
        lon_deg = np.rad2deg(lon)
        x = (lon_deg - self._lon_ref_deg) * km_per_deg_lon
        yy = (lat_deg - self._lat_ref_deg) * km_per_deg_lat
        ds = np.sqrt(
            np.diff(r) ** 2
            + (0.5 * (r[:-1] + r[1:]) * np.diff(lat)) ** 2
            + (
                0.5
                * (r[:-1] + r[1:])
                * np.cos(0.5 * (lat[:-1] + lat[1:]))
                * np.diff(lon)
            )
            ** 2
        )
        group_path_km = float(np.nansum(ds))
        alt_mid = 0.5 * (z[:-1] + z[1:])
        lat_mid = 0.5 * (lat_deg[:-1] + lat_deg[1:])
        lon_mid = 0.5 * (lon_deg[:-1] + lon_deg[1:])
        mup = np.asarray(self._eval_mup_sph(alt_mid, lat_mid, lon_mid), dtype=float)
        valid = np.isfinite(mup)
        group_delay_sec = float(np.nansum((mup[valid] / C_KM_S) * ds[valid]))
        status = "length"
        if sol.status == 1:
            status = "ground" if len(sol.t_events[0]) > 0 else "domain"
        elif sol.status == -1:
            status = "failure"
        return SimpleNamespace(
            x_km=x,
            y_km=yy,
            z_km=z,
            lat_deg=lat_deg,
            lon_deg=lon_deg,
            r_km=r,
            vr=sol.y[3, :],
            vlat=sol.y[4, :],
            vlon=sol.y[5, :],
            t=sol.t,
            status=status,
            reason=status,
            group_path_km=group_path_km,
            group_delay_sec=group_delay_sec,
            mode=mode,
            coordinate_system="spherical",
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            azimuth_deg=float(azimuth_deg),
        )

    def oblique_trace(
        self,
        freq_hz: float,
        elevation_deg: float,
        *,
        coordinate_system: str = "cartesian",
        solver: str = "gradient",
        nhops: int = 1,
        **kwargs,
    ) -> SimpleNamespace:
        """Unified 3-D oblique ray-trace entry point.

        Parameters
        ----------
        coordinate_system : ``"cartesian"`` or ``"spherical"``.
        solver : ``"gradient"`` (default) or ``"hamiltonian"`` (cartesian only).
        nhops : int, optional
            Number of ionospheric hops (default 1).  For nhops > 1 each
            ground hit is reflected specularly (vz → −vz for cartesian,
            vr → −vr for spherical) and the ODE restarts from the domain
            left edge with x/y shifted by the accumulated ground-hit
            offset (horizontal-homogeneity assumption).  All hop segments
            are concatenated in the returned namespace.
        """
        nhops = max(1, int(nhops))
        coord = str(coordinate_system).strip().lower()
        solv = str(solver).strip().lower()

        # ── select tracer ──────────────────────────────────────────────────
        if coord in {"cartesian", "cart", "xyz"}:
            _tracer = (
                self.trace_cartesian_hamiltonian
                if solv in {"hamiltonian", "ham"}
                else self.trace_cartesian_gradient
            )
            is_sph = False
        elif coord in {"spherical", "sph", "rll"}:
            if solv in {"hamiltonian", "ham"}:
                logger.warning(
                    "Hamiltonian spherical solver not implemented; using gradient."
                )
            _tracer = self.trace_spherical_gradient
            is_sph = True
        else:
            raise ValueError("coordinate_system must be 'cartesian' or 'spherical'")

        # ── single-hop fast path ───────────────────────────────────────────
        if nhops == 1:
            out = _tracer(freq_hz=freq_hz, elevation_deg=elevation_deg, **kwargs)
            out.nhops_completed = 1
            return out

        # ── multi-hop path ─────────────────────────────────────────────────
        # Extract first-hop origin (consumed here; subsequent hops restart
        # at domain origin with coordinate shift applied to output).
        x0 = float(kwargs.pop("x0_km", 0.0))
        y0 = float(kwargs.pop("y0_km", 0.0))
        z0 = float(kwargs.pop("z0_km", float(self.alts_km[0])))

        all_x: list[np.ndarray] = []
        all_y: list[np.ndarray] = []
        all_z: list[np.ndarray] = []
        total_gpath = 0.0
        total_gdelay = 0.0
        z_apex_best = -np.inf
        last: SimpleNamespace | None = None
        hops_done = 0
        elev = float(elevation_deg)
        az = float(kwargs.get("azimuth_deg", 0.0))

        # Accumulated physical offset for subsequent hops
        x_accum, y_accum = x0, y0

        for _hop in range(nhops):
            x_ode = 0.0 if _hop > 0 else x0
            y_ode = 0.0 if _hop > 0 else y0
            x_sft = x_accum if _hop > 0 else 0.0
            y_sft = y_accum if _hop > 0 else 0.0

            ray = _tracer(
                freq_hz=freq_hz,
                elevation_deg=elev,
                x0_km=x_ode,
                y0_km=y_ode,
                z0_km=z0,
                **kwargs,
            )
            x_arr = np.asarray(ray.x_km, dtype=float) + x_sft
            y_arr = np.asarray(ray.y_km, dtype=float) + y_sft
            z_arr = np.asarray(ray.z_km, dtype=float)
            all_x.append(x_arr)
            all_y.append(y_arr)
            all_z.append(z_arr)
            total_gpath += float(ray.group_path_km)
            total_gdelay += float(getattr(ray, "group_delay_sec", 0.0))
            if z_arr.size:
                z_apex_best = max(z_apex_best, float(np.nanmax(z_arr)))
            last = ray
            hops_done += 1

            if ray.status != "ground" or x_arr.size == 0:
                break  # did not reach ground — no further hops

            # ── specular ground reflection ─────────────────────────────────
            if is_sph:
                # state [r, lat, lon, vr, vlat, vlon]; vr²+vlat²+vlon²=1
                vr_last = float(ray.vr[-1])  # < 0 at descent
                vlat_last = float(ray.vlat[-1])
                vlon_last = float(ray.vlon[-1])
                elev = float(
                    np.degrees(
                        np.arctan2(abs(vr_last), np.sqrt(vlat_last**2 + vlon_last**2))
                    )
                )
                az = float(np.degrees(np.arctan2(vlon_last, vlat_last)))
            else:
                # state [x, y, z, vx, vy, vz]; vx²+vy²+vz²=1
                vx_last = float(ray.vx[-1])
                vy_last = float(ray.vy[-1])
                vz_last = float(ray.vz[-1])  # < 0 at descent
                elev = float(
                    np.degrees(
                        np.arctan2(abs(vz_last), np.sqrt(vx_last**2 + vy_last**2))
                    )
                )
                az = float(np.degrees(np.arctan2(vy_last, vx_last)))

            # Update azimuth in kwargs so the next tracer call uses it
            kwargs["azimuth_deg"] = az

            # Physical ground-hit position becomes the shift for the next hop
            x_accum = float(x_arr[-1])
            y_accum = float(y_arr[-1])
            z0 = float(self.alts_km[0])  # restart at ground level

        # ── concatenate all hop segments ───────────────────────────────────
        x_cat = np.concatenate(all_x) if all_x else np.array([], dtype=float)
        y_cat = np.concatenate(all_y) if all_y else np.array([], dtype=float)
        z_cat = np.concatenate(all_z) if all_z else np.array([], dtype=float)
        final_status = last.status if last is not None else "failure"

        out = SimpleNamespace(
            x_km=x_cat,
            y_km=y_cat,
            z_km=z_cat,
            status=final_status,
            reason=final_status,
            group_path_km=total_gpath,
            group_delay_sec=total_gdelay,
            z_apex_km=float(z_apex_best) if z_apex_best > -np.inf else np.nan,
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            azimuth_deg=float(kwargs.get("azimuth_deg", az)),
            mode=getattr(last, "mode", None),
            coordinate_system=coord,
            solver=getattr(last, "solver", "gradient"),
            nhops_completed=hops_done,
        )
        # Carry terminal velocity components from the final hop
        if last is not None:
            if is_sph:
                out.vr = last.vr
                out.vlat = last.vlat
                out.vlon = last.vlon
            else:
                out.vx = last.vx
                out.vy = last.vy
                out.vz = last.vz
        return out

Collision Frequency Support

RT3DProfile and RT3D mirror the same collision API as RT2D, operating on 3D fields of shape (nlat, nlon, nalt).

Workflow

from hfpytrace.model.rt3d import RT3D, RT3DProfile

prof = RT3DProfile.from_cfg(cfg, fetch_iri=True, fetch_msise=True)
rt = RT3D(profile=prof)
rt.fetch_collision()                    # stores ComputeCollision on prof.collision

# Extract a specific model's nu array for downstream use
nu_3d = RT3D._extract_collision_hz(prof.collision, "FT")
# nu_3d.shape == (nlat, nlon, nalt)

Supported collision_type Keys

Key Model
"FT" Friedrich-Tonker (ν_ft, a=1.0)
"FT_cc" Friedrich-Tonker (ν_av_cc, a=2.5)
"FT_mb" Friedrich-Tonker (ν_av_mb, a=1.5)
"SN_en" Schunk-Nagy electron-neutral total
"SN_ei" Schunk-Nagy electron-ion total
"SN" Schunk-Nagy full (en + ei)
"atm" Atmospheric ion-neutral approximation

Custom Plasma State

rt.fetch_collision(
    Te=Te_3d,    # shape (nlat, nlon, nalt), K
    Ti=Ti_3d,
    Op=Op_3d,    # O+ density in cm^-3
    O2p=O2p_3d,
)