Skip to content

hfpytrace.model

Package

Model-level pure-Python ray tracing helpers.

Key Classes

Class AppletonHartreeDispersion
Class SenWyllerDispersion
Class RT1DProfile
Class RT1D
Class RT2DProfile
Class RT2D
Class RT2DConfig Class RT3DProfile
Class RT3D

API

hfpytrace.model

hfpytrace.model — ionospheric ray-tracing model classes.

This sub-package contains the core ray-tracing and dispersion models:

RT1D 1-D vertical-incidence tracer using a simple ODE integrator. RT2D / RT2DProfile / RT2DConfig 2-D great-circle ray-tracing with a configurable ionospheric profile (IRI, SAMI3, GEMINI, etc.). RT3D / RT3DProfile 3-D oblique ray-tracing via PHaRLAP (raytrace_3d or raytrace_3d_sp). DispersionResult Container for refractive index, absorption, and related propagation metrics. AppletonHartreeDispersion Appleton-Hartree magneto-ionic dispersion relation. SenWyllerDispersion Sen-Wyller generalized dispersion relation (includes electron collision frequency via a non-Maxwellian velocity distribution).

RT1DProfile dataclass

Single-point altitude profile for ray/ionosphere workflows.

Notes
  • alt_km is required and must be strictly increasing.
  • Electron density is stored in both m^-3 and cm^-3 (when available).
  • MSIS and geomagnetic outputs are attached as namespaces.
Source code in hfpytrace/model/rt1d.py
@dataclass
class RT1DProfile:
    """
    Single-point altitude profile for ray/ionosphere workflows.

    Notes
    -----
    - `alt_km` is required and must be strictly increasing.
    - Electron density is stored in both m^-3 and cm^-3 (when available).
    - MSIS and geomagnetic outputs are attached as namespaces.
    """

    alt_km: np.ndarray
    lat: float
    lon: float
    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.alt_km = np.asarray(self.alt_km, dtype=float).ravel()
        self.lat = float(self.lat)
        self.lon = float(self.lon)
        if not isinstance(self.time, dt.datetime):
            self.time = dt.datetime.fromisoformat(str(self.time))
        self.validate()

    def validate(self) -> None:
        if self.alt_km.ndim != 1 or self.alt_km.size < 2:
            raise ValueError("alt_km must be a 1D array with at least 2 points")
        if not np.all(np.diff(self.alt_km) > 0):
            raise ValueError("alt_km must be strictly increasing")
        if not np.isfinite(self.lat) or not np.isfinite(self.lon):
            raise ValueError("lat/lon must be finite")

        if self.ne_m3 is not None:
            self.ne_m3 = np.asarray(self.ne_m3, dtype=float).ravel()
            if self.ne_m3.shape != self.alt_km.shape:
                raise ValueError("ne_m3 must match alt_km shape")
            if np.any(self.ne_m3 < 0):
                raise ValueError("ne_m3 must be non-negative")
            self.ne_cm3 = self.ne_m3 * 1e-6
        elif self.ne_cm3 is not None:
            self.ne_cm3 = np.asarray(self.ne_cm3, dtype=float).ravel()
            if self.ne_cm3.shape != self.alt_km.shape:
                raise ValueError("ne_cm3 must match alt_km shape")
            if np.any(self.ne_cm3 < 0):
                raise ValueError("ne_cm3 must be non-negative")
            self.ne_m3 = self.ne_cm3 * 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).ravel()
                if arr.shape != self.alt_km.shape:
                    raise ValueError(f"msise.{k} must match alt_km 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).ravel()
                if arr.shape != self.alt_km.shape:
                    raise ValueError(f"geomag.{k} must match alt_km shape")
                setattr(self.geomag, k, arr)

    @classmethod
    def from_cfg(
        cls,
        cfg,
        time: dt.datetime | None = None,
        lat: float | None = None,
        lon: float | None = None,
        alt_km: np.ndarray | None = None,
        fetch_iri: bool = True,
        fetch_msise: bool = True,
        fetch_geomag: bool = True,
        workers: int = 1,
    ) -> "RT1DProfile":
        logger.info("RT1DProfile.from_cfg: build profile from config")
        t = time if time is not None else dt.datetime.fromisoformat(str(cfg.event))
        if lat is None or lon is None:
            if hasattr(cfg, "origin"):
                lat = float(cfg.origin.lat)
                lon = float(cfg.origin.lon)
            elif hasattr(cfg, "route") and hasattr(cfg.route, "start"):
                lat = float(cfg.route.start.lat)
                lon = float(cfg.route.start.lon)
            else:
                raise ValueError("Unable to infer lat/lon from cfg. Provide lat/lon.")

        if alt_km is None:
            h0 = float(getattr(cfg, "start_height_km"))
            h1 = float(getattr(cfg, "end_height_km"))
            dh = float(getattr(cfg, "height_incriment_km", 1.0))
            alt_km = np.arange(h0, h1, dh, dtype=float)

        prof = cls(alt_km=alt_km, lat=float(lat), lon=float(lon), time=t)
        logger.info(
            "RT1DProfile created: lat={:.3f}, lon={:.3f}, alt_points={}",
            prof.lat,
            prof.lon,
            prof.alt_km.size,
        )
        if fetch_iri:
            prof.fetch_iri(cfg)
        if fetch_msise:
            prof.fetch_msise(workers=workers)
        if fetch_geomag:
            gm_cfg = getattr(cfg, "geomag_grid", SimpleNamespace(coord_input="GEO"))
            prof.fetch_geomag(
                coord_input=str(getattr(gm_cfg, "coord_input", "GEO")),
                coeff_dir=getattr(gm_cfg, "coeff_dir", None),
            )
        prof.validate()
        return prof

    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).ravel()
            self.ne_cm3 = self.ne_m3 * 1e-6
        else:
            self.ne_cm3 = np.asarray(ne_cm3, dtype=float).ravel()
            self.ne_m3 = self.ne_cm3 * 1e6
        self.validate()

    def fetch_iri(self, cfg) -> np.ndarray:
        logger.info(
            "Fetching IRI profile: lat={:.3f}, lon={:.3f}, alt_points={}",
            self.lat,
            self.lon,
            self.alt_km.size,
        )
        model = IRI2d(cfg, self.time)
        ne_cm3, _ = model.fetch_dataset(
            self.time,
            lats=np.array([self.lat], dtype=float),
            lons=np.array([self.lon], dtype=float),
            alts=self.alt_km,
            workers=1,
        )
        self.ne_cm3 = np.asarray(ne_cm3[:, 0], dtype=float)
        self.ne_m3 = self.ne_cm3 * 1e6
        self.source = "iri"
        self.validate()
        logger.info(
            "IRI profile fetched: ne range [{:.3e}, {:.3e}] m^-3",
            float(np.nanmin(self.ne_m3)),
            float(np.nanmax(self.ne_m3)),
        )
        return self.ne_m3

    def fetch_msise(
        self,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ) -> SimpleNamespace:
        logger.info(
            "Fetching NRLMSISE profile: lat={:.3f}, lon={:.3f}, alt_points={}, workers={}",
            self.lat,
            self.lon,
            self.alt_km.size,
            int(workers),
        )
        ms = NRLMSISE2D(
            date=self.time,
            lats=np.array([self.lat], dtype=float),
            lons=np.array([self.lon], dtype=float),
            heights_km=self.alt_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"][:, 0], dtype=float),
            O2=np.asarray(ms["O2"][:, 0], dtype=float),
            O=np.asarray(ms["O"][:, 0], dtype=float),
            H=np.asarray(ms["H"][:, 0], dtype=float),
            He=np.asarray(ms["He"][:, 0], dtype=float),
            Tn=np.asarray(ms["Tn"][:, 0], dtype=float),
            t_nn=np.asarray(ms["t_nn"][:, 0], dtype=float),
        )
        self.validate()
        logger.info("NRLMSISE profile fetched successfully.")
        return self.msise

    def fetch_geomag(
        self,
        coord_input: str = "GEO",
        coeff_dir: str | None = None,
    ) -> SimpleNamespace:
        logger.info(
            "Fetching geomag profile: lat={:.3f}, lon={:.3f}, alt_points={}, coord_input={}",
            self.lat,
            self.lon,
            self.alt_km.size,
            coord_input,
        )
        cdir = None
        if isinstance(coeff_dir, str) and coeff_dir.strip():
            cdir = coeff_dir
        gm = build_geomag_grid(
            lats=np.array([self.lat], dtype=float),
            lons=np.array([self.lon], dtype=float),
            alts_km=self.alt_km,
            time=self.time,
            coord_input=coord_input,
            coeff_dir=cdir,
        )
        self.geomag = SimpleNamespace(
            Bx=np.asarray(gm.Bx[0, 0, :], dtype=float),
            By=np.asarray(gm.By[0, 0, :], dtype=float),
            Bz=np.asarray(gm.Bz[0, 0, :], dtype=float),
            bmag_t=np.asarray(gm.bmag_t[0, 0, :], dtype=float),
            inc_deg=np.asarray(gm.inc_deg[0, 0, :], dtype=float),
            dec_deg=np.asarray(gm.dec_deg[0, 0, :], dtype=float),
            psi_deg=np.asarray(gm.psi_deg[0, 0, :], dtype=float),
        )
        self.validate()
        logger.info("Geomag profile fetched successfully.")
        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]. Defaults to MSIS neutral temperature Tn.
        edens : array-like, optional
            Electron density [cm^-3]. Defaults to ``self.ne_cm3``.
        O2p, Op : array-like, optional
            O2+ and O+ ion densities [cm^-3].
            Defaults to 10% / 90% of edens (typical F-region mix).

        Returns
        -------
        ComputeCollision
            The collision object is also stored on ``self.collision`` for
            subsequent retrieval by :meth:`RT1D.NVIS_tracer` via
            ``collision_type``.

        Notes
        -----
        Supported collision types for ``NVIS_tracer(collision_type=...)``:

        +-----------+-----------------------------------------------+
        | Key       | Source array                                  |
        +===========+===============================================+
        | ``FT``    | Friedrich-Tonker (nu_ft, a=1.0)               |
        | ``FT_cc`` | Friedrich-Tonker (nu_av_cc, a=2.5)            |
        | ``FT_mb`` | Friedrich-Tonker (nu_av_mb, a=1.5)            |
        | ``SN_en`` | Schunk-Nagy electron-neutral total             |
        | ``SN_ei`` | Schunk-Nagy electron-ion total                 |
        | ``SN``    | Schunk-Nagy full total (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)
        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

        # ComputeCollision expects (nh, nr) arrays; wrap 1D profile as (nh, 1).
        cc = ComputeCollision(
            Te=Te_use[:, None],
            Ti=Ti_use[:, None],
            Tn=Tn[:, None],
            edens=edens_use[:, None],
            O2p=O2p_use[:, None],
            Op=Op_use[:, None],
            N2=np.asarray(self.msise.N2, dtype=float)[:, None],
            O2=np.asarray(self.msise.O2, dtype=float)[:, None],
            O=np.asarray(self.msise.O, dtype=float)[:, None],
            H=np.asarray(self.msise.H, dtype=float)[:, None],
            He=np.asarray(self.msise.He, dtype=float)[:, None],
            date=self.time,
        )
        self.collision = cc
        logger.info(
            "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

    @staticmethod
    def den_to_plasma_freq_hz(ne_m3: np.ndarray | float) -> np.ndarray:
        ne = np.asarray(ne_m3, dtype=float)
        if np.any(ne < 0):
            raise ValueError("Electron density must be non-negative")
        omega_p = np.sqrt(ne * constants.e**2 / (constants.epsilon_0 * constants.m_e))
        return omega_p / (2.0 * np.pi)

    @staticmethod
    def plasma_freq_to_den(freq_hz: np.ndarray | float) -> np.ndarray:
        f = np.asarray(freq_hz, dtype=float)
        if np.any(f < 0):
            raise ValueError("Plasma frequency must be non-negative")
        return (
            ((2.0 * np.pi * f) ** 2)
            * constants.epsilon_0
            * constants.m_e
            / (constants.e**2)
        )

    @staticmethod
    def inclintation2vertical(
        inclination_deg: np.ndarray | float,
    ) -> np.ndarray:
        return 90.0 - np.abs(np.asarray(inclination_deg, dtype=float))

    @staticmethod
    def inclination_to_vertical_angle(
        inclination_deg: np.ndarray | float,
    ) -> np.ndarray:
        return RT1DProfile.inclintation2vertical(inclination_deg)

    @staticmethod
    def vertical_to_magnetic_angle(inclination_deg: np.ndarray | float) -> np.ndarray:
        return RT1DProfile.inclintation2vertical(inclination_deg)

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]. Defaults to MSIS neutral temperature Tn.

array-like, optional

Electron density [cm^-3]. Defaults to self.ne_cm3.

O2p, Op : array-like, optional O2+ and O+ ion densities [cm^-3]. Defaults to 10% / 90% of edens (typical F-region mix).

Returns

ComputeCollision The collision object is also stored on self.collision for subsequent retrieval by :meth:RT1D.NVIS_tracer via collision_type.

Notes

Supported collision types for NVIS_tracer(collision_type=...):

+-----------+-----------------------------------------------+ | Key | Source array | +===========+===============================================+ | FT | Friedrich-Tonker (nu_ft, a=1.0) | | FT_cc | Friedrich-Tonker (nu_av_cc, a=2.5) | | FT_mb | Friedrich-Tonker (nu_av_mb, a=1.5) | | SN_en | Schunk-Nagy electron-neutral total | | SN_ei | Schunk-Nagy electron-ion total | | SN | Schunk-Nagy full total (en + ei) | | atm | Atmospheric ion-neutral approximation | +-----------+-----------------------------------------------+

Source code in hfpytrace/model/rt1d.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]. Defaults to MSIS neutral temperature Tn.
    edens : array-like, optional
        Electron density [cm^-3]. Defaults to ``self.ne_cm3``.
    O2p, Op : array-like, optional
        O2+ and O+ ion densities [cm^-3].
        Defaults to 10% / 90% of edens (typical F-region mix).

    Returns
    -------
    ComputeCollision
        The collision object is also stored on ``self.collision`` for
        subsequent retrieval by :meth:`RT1D.NVIS_tracer` via
        ``collision_type``.

    Notes
    -----
    Supported collision types for ``NVIS_tracer(collision_type=...)``:

    +-----------+-----------------------------------------------+
    | Key       | Source array                                  |
    +===========+===============================================+
    | ``FT``    | Friedrich-Tonker (nu_ft, a=1.0)               |
    | ``FT_cc`` | Friedrich-Tonker (nu_av_cc, a=2.5)            |
    | ``FT_mb`` | Friedrich-Tonker (nu_av_mb, a=1.5)            |
    | ``SN_en`` | Schunk-Nagy electron-neutral total             |
    | ``SN_ei`` | Schunk-Nagy electron-ion total                 |
    | ``SN``    | Schunk-Nagy full total (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)
    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

    # ComputeCollision expects (nh, nr) arrays; wrap 1D profile as (nh, 1).
    cc = ComputeCollision(
        Te=Te_use[:, None],
        Ti=Ti_use[:, None],
        Tn=Tn[:, None],
        edens=edens_use[:, None],
        O2p=O2p_use[:, None],
        Op=Op_use[:, None],
        N2=np.asarray(self.msise.N2, dtype=float)[:, None],
        O2=np.asarray(self.msise.O2, dtype=float)[:, None],
        O=np.asarray(self.msise.O, dtype=float)[:, None],
        H=np.asarray(self.msise.H, dtype=float)[:, None],
        He=np.asarray(self.msise.He, dtype=float)[:, None],
        date=self.time,
    )
    self.collision = cc
    logger.info(
        "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

RT2DProfile dataclass

Container for a 2D ionospheric slice sampled on altitude and path axes.

Conventions: - vertical axis: alt_km (length nz) - route axis: x_km / lats / lons (length nx) - any 2D physical field uses shape (nz, nx)

Source code in hfpytrace/model/rt2d.py
@dataclass
class RT2DProfile:
    """
    Container for a 2D ionospheric slice sampled on altitude and path axes.

    Conventions:
    - vertical axis: ``alt_km`` (length ``nz``)
    - route axis: ``x_km`` / ``lats`` / ``lons`` (length ``nx``)
    - any 2D physical field uses shape ``(nz, nx)``
    """

    alt_km: np.ndarray
    lats: np.ndarray
    lons: np.ndarray
    time: dt.datetime
    x_km: np.ndarray | None = None
    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:
        """Normalize input arrays and run structural validation."""
        self.alt_km = np.asarray(self.alt_km, dtype=float).ravel()
        self.lats = np.asarray(self.lats, dtype=float).ravel()
        self.lons = np.asarray(self.lons, dtype=float).ravel()
        if not isinstance(self.time, dt.datetime):
            self.time = dt.datetime.fromisoformat(str(self.time))
        if self.x_km is None:
            self.x_km = np.arange(self.lats.size, dtype=float)
        else:
            self.x_km = np.asarray(self.x_km, dtype=float).ravel()
        self.validate()

    def validate(self) -> None:
        """Validate grid monotonicity and attached field shapes."""
        if self.alt_km.size < 2:
            raise ValueError("alt_km must contain at least 2 points")
        if self.lats.size < 2 or self.lons.size < 2:
            raise ValueError("lats and lons must contain at least 2 points")
        if self.lats.shape != self.lons.shape:
            raise ValueError("lats and lons must have the same shape")
        if self.x_km.shape != self.lats.shape:
            raise ValueError("x_km must match lats/lons shape")
        if not np.all(np.diff(self.alt_km) > 0):
            raise ValueError("alt_km must be strictly increasing")
        if not np.all(np.diff(self.x_km) > 0):
            raise ValueError("x_km must be strictly increasing")

        nz = self.alt_km.size
        nx = self.lats.size
        shape = (nz, nx)

        if self.ne_m3 is not None:
            ne = np.asarray(self.ne_m3, dtype=float)
            if ne.shape != shape:
                raise ValueError("ne_m3 must have shape (len(alt_km), len(lats))")
            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("ne_cm3 must have shape (len(alt_km), len(lats))")
            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)

    @classmethod
    def from_cfg(
        cls,
        cfg,
        time: dt.datetime | None = None,
        lats: np.ndarray | None = None,
        lons: np.ndarray | None = None,
        alt_km: np.ndarray | None = None,
        fetch_iri: bool = True,
        fetch_msise: bool = False,
        fetch_geomag: bool = False,
        workers: int = 1,
    ) -> "RT2DProfile":
        """Build an RT2DProfile from route/height settings in config."""
        logger.info("RT2DProfile.from_cfg: build route profile from config")
        t = time if time is not None else dt.datetime.fromisoformat(str(cfg.event))

        if lats is None or lons is None:
            n_range = int(getattr(cfg, "number_of_ground_step_km", 200))
            lats, lons, _, route_km = build_route_from_cfg(cfg, n_range)
            x_km = np.linspace(0.0, float(route_km), int(n_range))
        else:
            lats = np.asarray(lats, dtype=float).ravel()
            lons = np.asarray(lons, dtype=float).ravel()
            if lats.shape != lons.shape:
                raise ValueError("lats and lons must have same shape")
            x_km = np.arange(lats.size, dtype=float)

        if alt_km is None:
            alt_km = build_heights_from_cfg(cfg)
        else:
            alt_km = np.asarray(alt_km, dtype=float).ravel()

        prof = cls(alt_km=alt_km, lats=lats, lons=lons, x_km=x_km, time=t)
        if fetch_iri:
            prof.fetch_iri(cfg, workers=workers)
        if fetch_msise:
            prof.fetch_msise(workers=workers)
        if fetch_geomag:
            gm_cfg = getattr(cfg, "geomag_grid", SimpleNamespace(coord_input="GEO"))
            prof.fetch_geomag(
                coord_input=str(getattr(gm_cfg, "coord_input", "GEO")),
                coeff_dir=getattr(gm_cfg, "coeff_dir", None),
            )
        prof.validate()
        return prof

    def set_electron_density(
        self,
        ne_m3: np.ndarray | None = None,
        ne_cm3: np.ndarray | None = None,
        source: str = "iri",
    ) -> None:
        """Attach user-supplied electron density and keep unit pairs synced."""
        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:
        """
        Force electron density to zero below a specified altitude threshold.

        Parameters
        ----------
        min_alt_km:
            Altitude floor in km. Any row with ``alt_km < min_alt_km`` is zeroed.

        Returns
        -------
        int
            Number of altitude rows modified.
        """
        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.alt_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:
        """Populate electron density from IRI2d on the profile grid."""
        logger.info(
            "Fetching 2D IRI profile: path_points={}, alt_points={}",
            self.lats.size,
            self.alt_km.size,
        )
        model = IRI2d(cfg, self.time)
        ne_cm3, _ = model.fetch_dataset(
            self.time,
            lats=self.lats,
            lons=self.lons,
            alts=self.alt_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()
        logger.info("2D IRI profile fetched: shape={}", self.ne_m3.shape)
        return self.ne_m3

    def fetch_msise(
        self,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ) -> SimpleNamespace:
        """Populate neutral species and neutral temperature from NRLMSISE."""
        logger.info(
            "Fetching 2D NRLMSISE profile: path_points={}, alt_points={}, workers={}",
            self.lats.size,
            self.alt_km.size,
            int(workers),
        )
        ms = NRLMSISE2D(
            date=self.time,
            lats=self.lats,
            lons=self.lons,
            heights_km=self.alt_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()
        logger.info("2D NRLMSISE profile fetched.")
        return self.msise

    def fetch_geomag(
        self,
        coord_input: str = "GEO",
        coeff_dir: str | None = None,
    ) -> SimpleNamespace:
        """Populate geomagnetic vectors and angles along the 2D route grid."""
        logger.info(
            "Fetching 2D geomag profile on route: path_points={}, alt_points={}",
            self.lats.size,
            self.alt_km.size,
        )
        nx = self.lats.size
        nz = self.alt_km.size
        Bx = np.zeros((nz, nx), dtype=float)
        By = np.zeros((nz, nx), dtype=float)
        Bz = np.zeros((nz, nx), dtype=float)
        bmag_t = np.zeros((nz, nx), dtype=float)
        inc_deg = np.zeros((nz, nx), dtype=float)
        dec_deg = np.zeros((nz, nx), dtype=float)
        psi_deg = np.zeros((nz, nx), dtype=float)

        cdir = None
        if isinstance(coeff_dir, str) and coeff_dir.strip():
            cdir = coeff_dir

        for i in range(nx):
            gm = build_geomag_grid(
                lats=np.array([self.lats[i]], dtype=float),
                lons=np.array([self.lons[i]], dtype=float),
                alts_km=self.alt_km,
                time=self.time,
                coord_input=coord_input,
                coeff_dir=cdir,
            )
            Bx[:, i] = gm.Bx[0, 0, :]
            By[:, i] = gm.By[0, 0, :]
            Bz[:, i] = gm.Bz[0, 0, :]
            bmag_t[:, i] = gm.bmag_t[0, 0, :]
            inc_deg[:, i] = gm.inc_deg[0, 0, :]
            dec_deg[:, i] = gm.dec_deg[0, 0, :]
            psi_deg[:, i] = gm.psi_deg[0, 0, :]

        self.geomag = SimpleNamespace(
            Bx=Bx,
            By=By,
            Bz=Bz,
            bmag_t=bmag_t,
            inc_deg=inc_deg,
            dec_deg=dec_deg,
            psi_deg=psi_deg,
        )
        self.validate()
        logger.info("2D geomag profile fetched.")
        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 (nz, nx) or broadcastable.
            Defaults to MSIS neutral temperature Tn.
        edens : array-like, optional
            Electron density [cm^-3], shape (nz, nx). 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 :meth:`RT2D.build_refractive_index_interpolators`.

        Notes
        -----
        Supported ``collision_type`` keys for :meth:`RT2D.oblique_trace`:

        +-------------+--------------------------------------------------+
        | 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 (nz, nx)
        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(
            "2D 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

__post_init__()

Normalize input arrays and run structural validation.

Source code in hfpytrace/model/rt2d.py
def __post_init__(self) -> None:
    """Normalize input arrays and run structural validation."""
    self.alt_km = np.asarray(self.alt_km, dtype=float).ravel()
    self.lats = np.asarray(self.lats, dtype=float).ravel()
    self.lons = np.asarray(self.lons, dtype=float).ravel()
    if not isinstance(self.time, dt.datetime):
        self.time = dt.datetime.fromisoformat(str(self.time))
    if self.x_km is None:
        self.x_km = np.arange(self.lats.size, dtype=float)
    else:
        self.x_km = np.asarray(self.x_km, dtype=float).ravel()
    self.validate()

validate()

Validate grid monotonicity and attached field shapes.

Source code in hfpytrace/model/rt2d.py
def validate(self) -> None:
    """Validate grid monotonicity and attached field shapes."""
    if self.alt_km.size < 2:
        raise ValueError("alt_km must contain at least 2 points")
    if self.lats.size < 2 or self.lons.size < 2:
        raise ValueError("lats and lons must contain at least 2 points")
    if self.lats.shape != self.lons.shape:
        raise ValueError("lats and lons must have the same shape")
    if self.x_km.shape != self.lats.shape:
        raise ValueError("x_km must match lats/lons shape")
    if not np.all(np.diff(self.alt_km) > 0):
        raise ValueError("alt_km must be strictly increasing")
    if not np.all(np.diff(self.x_km) > 0):
        raise ValueError("x_km must be strictly increasing")

    nz = self.alt_km.size
    nx = self.lats.size
    shape = (nz, nx)

    if self.ne_m3 is not None:
        ne = np.asarray(self.ne_m3, dtype=float)
        if ne.shape != shape:
            raise ValueError("ne_m3 must have shape (len(alt_km), len(lats))")
        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("ne_cm3 must have shape (len(alt_km), len(lats))")
        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)

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

Build an RT2DProfile from route/height settings in config.

Source code in hfpytrace/model/rt2d.py
@classmethod
def from_cfg(
    cls,
    cfg,
    time: dt.datetime | None = None,
    lats: np.ndarray | None = None,
    lons: np.ndarray | None = None,
    alt_km: np.ndarray | None = None,
    fetch_iri: bool = True,
    fetch_msise: bool = False,
    fetch_geomag: bool = False,
    workers: int = 1,
) -> "RT2DProfile":
    """Build an RT2DProfile from route/height settings in config."""
    logger.info("RT2DProfile.from_cfg: build route profile from config")
    t = time if time is not None else dt.datetime.fromisoformat(str(cfg.event))

    if lats is None or lons is None:
        n_range = int(getattr(cfg, "number_of_ground_step_km", 200))
        lats, lons, _, route_km = build_route_from_cfg(cfg, n_range)
        x_km = np.linspace(0.0, float(route_km), int(n_range))
    else:
        lats = np.asarray(lats, dtype=float).ravel()
        lons = np.asarray(lons, dtype=float).ravel()
        if lats.shape != lons.shape:
            raise ValueError("lats and lons must have same shape")
        x_km = np.arange(lats.size, dtype=float)

    if alt_km is None:
        alt_km = build_heights_from_cfg(cfg)
    else:
        alt_km = np.asarray(alt_km, dtype=float).ravel()

    prof = cls(alt_km=alt_km, lats=lats, lons=lons, x_km=x_km, time=t)
    if fetch_iri:
        prof.fetch_iri(cfg, workers=workers)
    if fetch_msise:
        prof.fetch_msise(workers=workers)
    if fetch_geomag:
        gm_cfg = getattr(cfg, "geomag_grid", SimpleNamespace(coord_input="GEO"))
        prof.fetch_geomag(
            coord_input=str(getattr(gm_cfg, "coord_input", "GEO")),
            coeff_dir=getattr(gm_cfg, "coeff_dir", None),
        )
    prof.validate()
    return prof

set_electron_density(ne_m3=None, ne_cm3=None, source='iri')

Attach user-supplied electron density and keep unit pairs synced.

Source code in hfpytrace/model/rt2d.py
def set_electron_density(
    self,
    ne_m3: np.ndarray | None = None,
    ne_cm3: np.ndarray | None = None,
    source: str = "iri",
) -> None:
    """Attach user-supplied electron density and keep unit pairs synced."""
    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()

force_zero_density_below(min_alt_km)

Force electron density to zero below a specified altitude threshold.

Parameters
min_alt_km

Altitude floor in km. Any row with alt_km < min_alt_km is zeroed.

Returns

int Number of altitude rows modified.

Source code in hfpytrace/model/rt2d.py
def force_zero_density_below(self, min_alt_km: float) -> int:
    """
    Force electron density to zero below a specified altitude threshold.

    Parameters
    ----------
    min_alt_km:
        Altitude floor in km. Any row with ``alt_km < min_alt_km`` is zeroed.

    Returns
    -------
    int
        Number of altitude rows modified.
    """
    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.alt_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

fetch_iri(cfg, workers=1)

Populate electron density from IRI2d on the profile grid.

Source code in hfpytrace/model/rt2d.py
def fetch_iri(self, cfg, workers: int = 1) -> np.ndarray:
    """Populate electron density from IRI2d on the profile grid."""
    logger.info(
        "Fetching 2D IRI profile: path_points={}, alt_points={}",
        self.lats.size,
        self.alt_km.size,
    )
    model = IRI2d(cfg, self.time)
    ne_cm3, _ = model.fetch_dataset(
        self.time,
        lats=self.lats,
        lons=self.lons,
        alts=self.alt_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()
    logger.info("2D IRI profile fetched: shape={}", self.ne_m3.shape)
    return self.ne_m3

fetch_msise(workers=1, update_spaceweather=False, suppress_spaceweather_warning=True)

Populate neutral species and neutral temperature from NRLMSISE.

Source code in hfpytrace/model/rt2d.py
def fetch_msise(
    self,
    workers: int = 1,
    update_spaceweather: bool = False,
    suppress_spaceweather_warning: bool = True,
) -> SimpleNamespace:
    """Populate neutral species and neutral temperature from NRLMSISE."""
    logger.info(
        "Fetching 2D NRLMSISE profile: path_points={}, alt_points={}, workers={}",
        self.lats.size,
        self.alt_km.size,
        int(workers),
    )
    ms = NRLMSISE2D(
        date=self.time,
        lats=self.lats,
        lons=self.lons,
        heights_km=self.alt_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()
    logger.info("2D NRLMSISE profile fetched.")
    return self.msise

fetch_geomag(coord_input='GEO', coeff_dir=None)

Populate geomagnetic vectors and angles along the 2D route grid.

Source code in hfpytrace/model/rt2d.py
def fetch_geomag(
    self,
    coord_input: str = "GEO",
    coeff_dir: str | None = None,
) -> SimpleNamespace:
    """Populate geomagnetic vectors and angles along the 2D route grid."""
    logger.info(
        "Fetching 2D geomag profile on route: path_points={}, alt_points={}",
        self.lats.size,
        self.alt_km.size,
    )
    nx = self.lats.size
    nz = self.alt_km.size
    Bx = np.zeros((nz, nx), dtype=float)
    By = np.zeros((nz, nx), dtype=float)
    Bz = np.zeros((nz, nx), dtype=float)
    bmag_t = np.zeros((nz, nx), dtype=float)
    inc_deg = np.zeros((nz, nx), dtype=float)
    dec_deg = np.zeros((nz, nx), dtype=float)
    psi_deg = np.zeros((nz, nx), dtype=float)

    cdir = None
    if isinstance(coeff_dir, str) and coeff_dir.strip():
        cdir = coeff_dir

    for i in range(nx):
        gm = build_geomag_grid(
            lats=np.array([self.lats[i]], dtype=float),
            lons=np.array([self.lons[i]], dtype=float),
            alts_km=self.alt_km,
            time=self.time,
            coord_input=coord_input,
            coeff_dir=cdir,
        )
        Bx[:, i] = gm.Bx[0, 0, :]
        By[:, i] = gm.By[0, 0, :]
        Bz[:, i] = gm.Bz[0, 0, :]
        bmag_t[:, i] = gm.bmag_t[0, 0, :]
        inc_deg[:, i] = gm.inc_deg[0, 0, :]
        dec_deg[:, i] = gm.dec_deg[0, 0, :]
        psi_deg[:, i] = gm.psi_deg[0, 0, :]

    self.geomag = SimpleNamespace(
        Bx=Bx,
        By=By,
        Bz=Bz,
        bmag_t=bmag_t,
        inc_deg=inc_deg,
        dec_deg=dec_deg,
        psi_deg=psi_deg,
    )
    self.validate()
    logger.info("2D geomag profile fetched.")
    return self.geomag

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 (nz, nx) or broadcastable. Defaults to MSIS neutral temperature Tn.

array-like, optional

Electron density [cm^-3], shape (nz, nx). 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 :meth:RT2D.build_refractive_index_interpolators.

Notes

Supported collision_type keys for :meth:RT2D.oblique_trace:

+-------------+--------------------------------------------------+ | 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/rt2d.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 (nz, nx) or broadcastable.
        Defaults to MSIS neutral temperature Tn.
    edens : array-like, optional
        Electron density [cm^-3], shape (nz, nx). 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 :meth:`RT2D.build_refractive_index_interpolators`.

    Notes
    -----
    Supported ``collision_type`` keys for :meth:`RT2D.oblique_trace`:

    +-------------+--------------------------------------------------+
    | 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 (nz, nx)
    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(
        "2D 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

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

DispersionResult dataclass

Container for derived propagation metrics.

Attributes
np.ndarray

Complex refractive index (same shape as broadcasted input fields).

np.ndarray

Absorption coefficient in dB/km.

np.ndarray

Phase constant in rad/km.

np.ndarray

Phase constant in deg/km.

Source code in hfpytrace/model/dispersion.py
@dataclass
class DispersionResult:
    """
    Container for derived propagation metrics.

    Attributes
    ----------
    refractive_index : np.ndarray
        Complex refractive index (same shape as broadcasted input fields).
    absorption_db_per_km : np.ndarray
        Absorption coefficient in dB/km.
    phase_rad_per_km : np.ndarray
        Phase constant in rad/km.
    phase_deg_per_km : np.ndarray
        Phase constant in deg/km.
    """

    refractive_index: np.ndarray
    absorption_db_per_km: np.ndarray
    phase_rad_per_km: np.ndarray
    phase_deg_per_km: np.ndarray

AppletonHartreeDispersion

Bases: DispersionBase

Appleton-Hartree style magneto-ionic formulation.

Supported modes
  • "N"/"NO"/"ISO": isotropic-like branch
  • "O": ordinary
  • "X": extraordinary
  • "R": right-hand circular
  • "L": left-hand circular
Source code in hfpytrace/model/dispersion.py
class AppletonHartreeDispersion(DispersionBase):
    """
    Appleton-Hartree style magneto-ionic formulation.

    Supported modes
    ---------------
    - "N"/"NO"/"ISO": isotropic-like branch
    - "O": ordinary
    - "X": extraordinary
    - "R": right-hand circular
    - "L": left-hand circular
    """

    def refractive_index(self, mode: str = "O") -> np.ndarray:
        """
        Compute Appleton-Hartree refractive index for the selected mode.
        """
        mode_u = str(mode).upper()
        X, Z, _, YL, YT = self._params()
        jz = 1j * Z

        if mode_u in {"N", "NO", "ISO"}:
            return _safe_sqrt_complex(1.0 - (X / (1.0 - jz)))
        if mode_u == "O":
            return _safe_sqrt_complex(1.0 - (X / (1.0 - jz)))
        if mode_u == "X":
            num = 2.0 * X * (1.0 - X - jz)
            den = (2.0 * (1.0 - X - jz) * (1.0 - jz)) - (2.0 * YT**2)
            return _safe_sqrt_complex(1.0 - (num / den))
        if mode_u == "R":
            return _safe_sqrt_complex(1.0 - (X / ((1.0 - jz) - YL)))
        if mode_u == "L":
            return _safe_sqrt_complex(1.0 - (X / ((1.0 - jz) + YL)))
        raise ValueError("mode must be one of: N/NO/ISO, O, X, R, L")

refractive_index(mode='O')

Compute Appleton-Hartree refractive index for the selected mode.

Source code in hfpytrace/model/dispersion.py
def refractive_index(self, mode: str = "O") -> np.ndarray:
    """
    Compute Appleton-Hartree refractive index for the selected mode.
    """
    mode_u = str(mode).upper()
    X, Z, _, YL, YT = self._params()
    jz = 1j * Z

    if mode_u in {"N", "NO", "ISO"}:
        return _safe_sqrt_complex(1.0 - (X / (1.0 - jz)))
    if mode_u == "O":
        return _safe_sqrt_complex(1.0 - (X / (1.0 - jz)))
    if mode_u == "X":
        num = 2.0 * X * (1.0 - X - jz)
        den = (2.0 * (1.0 - X - jz) * (1.0 - jz)) - (2.0 * YT**2)
        return _safe_sqrt_complex(1.0 - (num / den))
    if mode_u == "R":
        return _safe_sqrt_complex(1.0 - (X / ((1.0 - jz) - YL)))
    if mode_u == "L":
        return _safe_sqrt_complex(1.0 - (X / ((1.0 - jz) + YL)))
    raise ValueError("mode must be one of: N/NO/ISO, O, X, R, L")

SenWyllerDispersion

Bases: DispersionBase

Sen-Wyller generalized formulation.

Notes

This implementation follows the structure used in the existing project absorption workflow and evaluates C(p,y) numerically with scipy.integrate.quad.

Source code in hfpytrace/model/dispersion.py
class SenWyllerDispersion(DispersionBase):
    """
    Sen-Wyller generalized formulation.

    Notes
    -----
    This implementation follows the structure used in the existing project
    absorption workflow and evaluates C(p,y) numerically with `scipy.integrate.quad`.
    """

    def refractive_index(self, mode: str = "O") -> np.ndarray:
        """
        Compute Sen-Wyller refractive index for the selected mode.

        Supported modes: "N"/"NO"/"ISO", "O", "X", "R", "L".
        """
        mode_u = str(mode).upper()
        X, _, Y, YL, _ = self._params()
        nu_sw = np.clip(self.collision_hz, 1e-12, None)
        w = self.omega
        ne, nu_sw, Y, YL = _as_broadcast(
            np.clip(self.ne_m3, 0.0, None),
            nu_sw,
            Y,
            YL,
        )

        wp2 = ne * constants.e**2 / (constants.epsilon_0 * constants.m_e)
        y = w / nu_sw
        yx = (w - YL * w) / nu_sw
        yo = (w + YL * w) / nu_sw

        C15_y = _V_C15(y)
        C25_y = _V_C25(y)
        C15_yx = _V_C15(yx)
        C15_yo = _V_C15(yo)
        C25_yx = _V_C25(yx)
        C25_yo = _V_C25(yo)

        # R/L branches from Sen-Wyller generalization.
        pref = wp2 / (2.0 * w * nu_sw)
        nL = 1.0 - pref * (yo * C15_yo + 1j * 2.5 * C25_yo)
        nR = 1.0 - pref * (yx * C15_yx + 1j * 2.5 * C25_yx)

        if mode_u == "L":
            return nL.astype(np.complex128)
        if mode_u == "R":
            return nR.astype(np.complex128)

        # O/X branches through generalized dielectric terms.
        ajb = (wp2 / (w * nu_sw)) * ((y * C15_y) + 1j * (2.5 * C25_y))
        c = (wp2 / (w * nu_sw)) * yx * C15_yx
        d = 2.5 * (wp2 / (w * nu_sw)) * C25_yx
        e = (wp2 / (w * nu_sw)) * yo * C15_yo
        f = 2.5 * (wp2 / (w * nu_sw)) * C25_yo

        eI = 1.0 - ajb
        eII = 0.5 * ((f - d) + 1j * (c - e))
        eIII = ajb - 0.5 * ((c + e) + 1j * (d + f))

        Aa = 2.0 * eI * (eI + eIII)
        Bb = (eIII * (eI + eII)) + eII**2
        Dd = 2.0 * eI
        Ee = 2.0 * eIII

        nO = _safe_sqrt_complex(Aa / (Dd + Ee))
        nX = _safe_sqrt_complex((Aa + Bb) / (Dd + Ee))

        if mode_u in {"N", "NO", "ISO", "O"}:
            return nO
        if mode_u == "X":
            return nX
        raise ValueError("mode must be one of: N/NO/ISO, O, X, R, L")

refractive_index(mode='O')

Compute Sen-Wyller refractive index for the selected mode.

Supported modes: "N"/"NO"/"ISO", "O", "X", "R", "L".

Source code in hfpytrace/model/dispersion.py
def refractive_index(self, mode: str = "O") -> np.ndarray:
    """
    Compute Sen-Wyller refractive index for the selected mode.

    Supported modes: "N"/"NO"/"ISO", "O", "X", "R", "L".
    """
    mode_u = str(mode).upper()
    X, _, Y, YL, _ = self._params()
    nu_sw = np.clip(self.collision_hz, 1e-12, None)
    w = self.omega
    ne, nu_sw, Y, YL = _as_broadcast(
        np.clip(self.ne_m3, 0.0, None),
        nu_sw,
        Y,
        YL,
    )

    wp2 = ne * constants.e**2 / (constants.epsilon_0 * constants.m_e)
    y = w / nu_sw
    yx = (w - YL * w) / nu_sw
    yo = (w + YL * w) / nu_sw

    C15_y = _V_C15(y)
    C25_y = _V_C25(y)
    C15_yx = _V_C15(yx)
    C15_yo = _V_C15(yo)
    C25_yx = _V_C25(yx)
    C25_yo = _V_C25(yo)

    # R/L branches from Sen-Wyller generalization.
    pref = wp2 / (2.0 * w * nu_sw)
    nL = 1.0 - pref * (yo * C15_yo + 1j * 2.5 * C25_yo)
    nR = 1.0 - pref * (yx * C15_yx + 1j * 2.5 * C25_yx)

    if mode_u == "L":
        return nL.astype(np.complex128)
    if mode_u == "R":
        return nR.astype(np.complex128)

    # O/X branches through generalized dielectric terms.
    ajb = (wp2 / (w * nu_sw)) * ((y * C15_y) + 1j * (2.5 * C25_y))
    c = (wp2 / (w * nu_sw)) * yx * C15_yx
    d = 2.5 * (wp2 / (w * nu_sw)) * C25_yx
    e = (wp2 / (w * nu_sw)) * yo * C15_yo
    f = 2.5 * (wp2 / (w * nu_sw)) * C25_yo

    eI = 1.0 - ajb
    eII = 0.5 * ((f - d) + 1j * (c - e))
    eIII = ajb - 0.5 * ((c + e) + 1j * (d + f))

    Aa = 2.0 * eI * (eI + eIII)
    Bb = (eIII * (eI + eII)) + eII**2
    Dd = 2.0 * eI
    Ee = 2.0 * eIII

    nO = _safe_sqrt_complex(Aa / (Dd + Ee))
    nX = _safe_sqrt_complex((Aa + Bb) / (Dd + Ee))

    if mode_u in {"N", "NO", "ISO", "O"}:
        return nO
    if mode_u == "X":
        return nX
    raise ValueError("mode must be one of: N/NO/ISO, O, X, R, L")

RT1D

1D model entry-point that owns a single :class:RT1DProfile.

This initializer is intentionally flexible so callers can construct the profile from:

  1. a pre-built RT1DProfile object, or
  2. a TRACE cfg object (config1D-style namespace), or
  3. explicit scalar/array user inputs.
Parameters
RT1DProfile, optional

Existing profile instance. When provided, this takes precedence and is validated directly.

object, optional

Config namespace used by :meth:RT1DProfile.from_cfg. Can also be used only for defaults (event/lat/lon/heights) when explicit values are partially provided.

datetime | str, optional

Profile timestamp. If omitted and cfg has event, cfg event is used. Otherwise current UTC time is used.

lat, lon : float, optional Profile location. If omitted, inferred from cfg.origin or cfg.route.start.

array-like, optional

Altitude grid [km]. If omitted and cfg is provided, built from start_height_km/end_height_km/height_incriment_km.

ne_m3, ne_cm3 : array-like, optional User-provided electron density. Provide exactly one if overriding model fetch.

str, optional

Density source label when user density is supplied.

fetch_iri, fetch_msise, fetch_geomag : bool, optional If True, populate those profile components during initialization.

int, optional

Worker hint passed to MSIS/cfg-based constructor where supported.

coord_input, coeff_dir : str, optional Geomagnetic options passed to fetch_geomag when requested and not provided by cfg.

Notes
  • This class currently provides initialization/validation orchestration.
  • Frequency conversions remain exposed as static compatibility methods.
Source code in hfpytrace/model/rt1d.py
 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
class RT1D:
    """
    1D model entry-point that owns a single :class:`RT1DProfile`.

    This initializer is intentionally flexible so callers can construct the
    profile from:

    1. a pre-built ``RT1DProfile`` object, or
    2. a TRACE cfg object (``config1D``-style namespace), or
    3. explicit scalar/array user inputs.

    Parameters
    ----------
    profile : RT1DProfile, optional
        Existing profile instance. When provided, this takes precedence and is
        validated directly.
    cfg : object, optional
        Config namespace used by :meth:`RT1DProfile.from_cfg`. Can also be used
        only for defaults (event/lat/lon/heights) when explicit values are
        partially provided.
    time : datetime | str, optional
        Profile timestamp. If omitted and ``cfg`` has ``event``, cfg event is
        used. Otherwise current UTC time is used.
    lat, lon : float, optional
        Profile location. If omitted, inferred from ``cfg.origin`` or
        ``cfg.route.start``.
    alt_km : array-like, optional
        Altitude grid [km]. If omitted and ``cfg`` is provided, built from
        ``start_height_km/end_height_km/height_incriment_km``.
    ne_m3, ne_cm3 : array-like, optional
        User-provided electron density. Provide exactly one if overriding model
        fetch.
    source : str, optional
        Density source label when user density is supplied.
    fetch_iri, fetch_msise, fetch_geomag : bool, optional
        If True, populate those profile components during initialization.
    workers : int, optional
        Worker hint passed to MSIS/cfg-based constructor where supported.
    coord_input, coeff_dir : str, optional
        Geomagnetic options passed to ``fetch_geomag`` when requested and not
        provided by cfg.

    Notes
    -----
    - This class currently provides initialization/validation orchestration.
    - Frequency conversions remain exposed as static compatibility methods.
    """

    def __init__(
        self,
        profile: RT1DProfile | None = None,
        cfg=None,
        time: dt.datetime | str | None = None,
        lat: float | None = None,
        lon: float | None = None,
        alt_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,
        coord_input: str = "GEO",
        coeff_dir: str | None = None,
    ):
        logger.info("Initializing RT1D model")
        self.cfg = cfg
        self.workers = int(workers)
        if self.workers < 1:
            raise ValueError("workers must be >= 1")

        # Path 1: caller gives a full profile instance.
        if profile is not None:
            if not isinstance(profile, RT1DProfile):
                raise TypeError("profile must be an RT1DProfile instance")
            if any(v is not None for v in (cfg, lat, lon, alt_km, ne_m3, ne_cm3)):
                raise ValueError(
                    "When `profile` is provided, do not also pass cfg/lat/lon/alt/density inputs."
                )
            self.profile = profile
            self.profile.validate()
            logger.info("RT1D initialized from existing RT1DProfile")
            return

        # Path 2: build directly from cfg when available and no explicit overrides.
        has_explicit_density = (ne_m3 is not None) or (ne_cm3 is not None)
        if (
            cfg is not None
            and lat is None
            and lon is None
            and alt_km is None
            and not has_explicit_density
        ):
            t_cfg = time if time is not None else None
            self.profile = RT1DProfile.from_cfg(
                cfg=cfg,
                time=t_cfg,
                fetch_iri=bool(fetch_iri),
                fetch_msise=bool(fetch_msise),
                fetch_geomag=bool(fetch_geomag),
                workers=self.workers,
            )
            logger.info("RT1D initialized from config-driven profile")
            return

        # Path 3: explicit user assembly, with cfg optionally supplying defaults.
        t = self._resolve_time(time=time, cfg=cfg)
        lat_f, lon_f = self._resolve_location(lat=lat, lon=lon, cfg=cfg)
        alt_arr = self._resolve_altitudes(alt_km=alt_km, cfg=cfg)

        self.profile = RT1DProfile(
            alt_km=alt_arr,
            lat=lat_f,
            lon=lon_f,
            time=t,
        )

        if has_explicit_density:
            self.profile.set_electron_density(
                ne_m3=ne_m3,
                ne_cm3=ne_cm3,
                source=source,
            )
        elif fetch_iri:
            if cfg is None:
                raise ValueError("fetch_iri=True requires cfg for IRI parameters")
            self.profile.fetch_iri(cfg)

        if fetch_msise:
            self.profile.fetch_msise(workers=self.workers)

        if fetch_geomag:
            cdir = coeff_dir
            if cfg is not None and hasattr(cfg, "geomag_grid"):
                coord_input = str(getattr(cfg.geomag_grid, "coord_input", coord_input))
                cdir = getattr(cfg.geomag_grid, "coeff_dir", cdir)
            self.profile.fetch_geomag(coord_input=coord_input, coeff_dir=cdir)

        self.profile.validate()
        logger.info(
            "RT1D ready: lat={:.3f}, lon={:.3f}, alt_points={}, source={}",
            self.profile.lat,
            self.profile.lon,
            self.profile.alt_km.size,
            self.profile.source,
        )

    # ------------------------------------------------------------------
    # Collision type keys understood by NVIS_tracer(collision_type=...)
    # ------------------------------------------------------------------
    _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 1D collision-frequency array [Hz] from a ComputeCollision
        object using the user-specified type key.

        Parameters
        ----------
        cc : ComputeCollision
            Object returned by ``RT1DProfile.compute_collision()``.
        collision_type : str
            One of ``"FT"``, ``"FT_cc"``, ``"FT_mb"``, ``"SN_en"``,
            ``"SN_ei"``, ``"SN"``, ``"atm"`` (case-insensitive).

        Returns
        -------
        np.ndarray, shape (nh,)
        """
        ct = str(collision_type).strip().upper()
        _map = {
            "FT": lambda c: np.asarray(c.collision.nu_ft[:, 0], dtype=float),
            "FT_CC": lambda c: np.asarray(c.collision.nu_av_cc[:, 0], dtype=float),
            "FT_MB": lambda c: np.asarray(c.collision.nu_av_mb[:, 0], dtype=float),
            "SN_EN": lambda c: np.asarray(
                c.collision.nu_sn.en.total[:, 0], dtype=float
            ),
            "SN_EI": lambda c: np.asarray(
                c.collision.nu_sn.ei.total[:, 0], dtype=float
            ),
            "SN": lambda c: np.asarray(c.collision.nu_sn.total[:, 0], dtype=float),
            "ATM": lambda c: np.asarray(
                c.atmospheric_ion_neutral_collision_frequency()[:, 0], dtype=float
            ),
        }
        if ct not in _map:
            valid = sorted(_map.keys())
            raise ValueError(
                f"Unknown collision_type '{collision_type}'. Valid options: {valid}"
            )
        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:`RT1DProfile.compute_collision`.
        Requires that ``fetch_msise()`` has been called. Plasma defaults
        (Te=Ti=Tn, Op=0.9·Ne, O2p=0.1·Ne) are applied when arguments
        are omitted.

        After calling this, pass ``collision_type`` to
        :meth:`NVIS_tracer` to select which model to use, e.g.::

            rt.fetch_collision()
            result = rt.NVIS_tracer(freq_mhz=freqs, collision_type="SN")

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

    @staticmethod
    def _resolve_time(time: dt.datetime | str | None, cfg=None) -> dt.datetime:
        """Resolve profile time from explicit input, cfg event, or UTC now."""
        if time is not None:
            return (
                time
                if isinstance(time, dt.datetime)
                else dt.datetime.fromisoformat(str(time))
            )
        if cfg is not None and hasattr(cfg, "event"):
            return dt.datetime.fromisoformat(str(cfg.event))
        return dt.datetime.utcnow()

    @staticmethod
    def _resolve_location(
        lat: float | None, lon: float | None, cfg=None
    ) -> tuple[float, float]:
        """Resolve lat/lon from explicit values or cfg defaults."""
        if lat is not None and lon is not None:
            return float(lat), float(lon)
        if (lat is None) ^ (lon is None):
            raise ValueError("Provide both lat and lon, or neither")
        if cfg is not None:
            if hasattr(cfg, "origin"):
                return float(cfg.origin.lat), float(cfg.origin.lon)
            if hasattr(cfg, "route") and hasattr(cfg.route, "start"):
                return float(cfg.route.start.lat), float(cfg.route.start.lon)
        raise ValueError(
            "Unable to resolve lat/lon. Provide lat/lon or cfg with origin/route.start."
        )

    @staticmethod
    def _resolve_altitudes(alt_km: np.ndarray | None, cfg=None) -> np.ndarray:
        """Resolve altitude grid from explicit input or cfg height fields."""
        if alt_km is not None:
            arr = np.asarray(alt_km, dtype=float).ravel()
            if arr.size < 2:
                raise ValueError("alt_km must contain at least 2 points")
            return arr
        if cfg is not None:
            h0 = float(getattr(cfg, "start_height_km"))
            h1 = float(getattr(cfg, "end_height_km"))
            dh = float(getattr(cfg, "height_incriment_km", 1.0))
            return np.arange(h0, h1, dh, dtype=float)
        raise ValueError("Unable to resolve altitude grid. Provide alt_km or cfg.")

    def _refractive_index_profile(
        self,
        frequency_hz: float,
        mode: str = "O",
        formulation: str = "appleton",
        collision_hz: np.ndarray | float | None = None,
        b_t: np.ndarray | float | None = None,
        theta_deg: np.ndarray | float | None = None,
    ) -> np.ndarray:
        """
        Build a 1D refractive-index profile n(z) on ``self.profile.alt_km``.

        Parameters
        ----------
        frequency_hz : float
            Wave frequency in Hz.
        mode : str, optional
            Mode selector for the selected formulation.
        formulation : {"appleton", "senwyller"}, optional
            Dispersion relation backend.
        collision_hz, b_t, theta_deg : array-like | scalar, optional
            Optional overrides. If omitted, best-available values are pulled
            from ``self.profile``:
            - collision: 0 (collisionless)
            - b_t: geomag ``bmag_t`` if available else 0
            - theta_deg: geomag ``psi_deg`` if available else 0
        """
        if self.profile.ne_m3 is None:
            raise ValueError("Profile must include electron density (ne_m3).")

        alt = self.profile.alt_km
        ne = self.profile.ne_m3
        nu = (
            np.zeros_like(alt, dtype=float)
            if collision_hz is None
            else np.asarray(collision_hz, dtype=float)
        )
        if b_t is None:
            b = (
                np.asarray(self.profile.geomag.bmag_t, dtype=float)
                if self.profile.geomag is not None
                and hasattr(self.profile.geomag, "bmag_t")
                else np.zeros_like(alt, dtype=float)
            )
        else:
            b = np.asarray(b_t, dtype=float)

        if theta_deg is None:
            psi = (
                np.asarray(self.profile.geomag.psi_deg, dtype=float)
                if self.profile.geomag is not None
                and hasattr(self.profile.geomag, "psi_deg")
                else np.zeros_like(alt, dtype=float)
            )
        else:
            psi = np.asarray(theta_deg, dtype=float)

        form = str(formulation).strip().lower()
        if form == "appleton":
            model = AppletonHartreeDispersion(
                frequency_hz=frequency_hz,
                ne_m3=ne,
                collision_hz=nu,
                b_t=b,
                theta_deg=psi,
            )
        elif form in {"senwyller", "sen-wyller"}:
            model = SenWyllerDispersion(
                frequency_hz=frequency_hz,
                ne_m3=ne,
                collision_hz=nu,
                b_t=b,
                theta_deg=psi,
            )
        else:
            raise ValueError("formulation must be 'appleton' or 'senwyller'")

        n = np.real(model.refractive_index(mode=mode))
        n = np.asarray(n, dtype=float).ravel()
        # guard tiny negatives from numerical noise
        n = np.where(np.isfinite(n), np.clip(n, 0.0, None), np.nan)
        if n.shape != alt.shape:
            raise ValueError("Refractive index profile shape mismatch.")
        return n

    def _dispersion_result_profile(
        self,
        frequency_hz: float,
        mode: str = "O",
        formulation: str = "appleton",
        collision_hz: np.ndarray | float | None = None,
        b_t: np.ndarray | float | None = None,
        theta_deg: np.ndarray | float | None = None,
    ) -> "DispersionResult":
        """Build a full DispersionResult profile on ``self.profile.alt_km``.

        Same model-construction logic as ``_refractive_index_profile`` but
        calls ``model.evaluate()`` so that absorption and phase profiles are
        also returned alongside the complex refractive index.
        """
        if self.profile.ne_m3 is None:
            raise ValueError("Profile must include electron density (ne_m3).")

        alt = self.profile.alt_km
        ne = self.profile.ne_m3
        nu = (
            np.zeros_like(alt, dtype=float)
            if collision_hz is None
            else np.asarray(collision_hz, dtype=float)
        )
        if b_t is None:
            b = (
                np.asarray(self.profile.geomag.bmag_t, dtype=float)
                if self.profile.geomag is not None
                and hasattr(self.profile.geomag, "bmag_t")
                else np.zeros_like(alt, dtype=float)
            )
        else:
            b = np.asarray(b_t, dtype=float)
        if theta_deg is None:
            psi = (
                np.asarray(self.profile.geomag.psi_deg, dtype=float)
                if self.profile.geomag is not None
                and hasattr(self.profile.geomag, "psi_deg")
                else np.zeros_like(alt, dtype=float)
            )
        else:
            psi = np.asarray(theta_deg, dtype=float)

        form = str(formulation).strip().lower()
        if form == "appleton":
            model = AppletonHartreeDispersion(
                frequency_hz=frequency_hz,
                ne_m3=ne,
                collision_hz=nu,
                b_t=b,
                theta_deg=psi,
            )
        elif form in {"senwyller", "sen-wyller"}:
            model = SenWyllerDispersion(
                frequency_hz=frequency_hz,
                ne_m3=ne,
                collision_hz=nu,
                b_t=b,
                theta_deg=psi,
            )
        else:
            raise ValueError("formulation must be 'appleton' or 'senwyller'")
        return model.evaluate(mode=mode)

    @staticmethod
    def _smooth_nonuniform_grid(
        start: float, end: float, n_points: int, sharpness: float
    ) -> np.ndarray:
        """
        Build a smooth nonuniform coordinate in [start, end] with denser
        sampling near ``end``.
        """
        if int(n_points) < 3:
            raise ValueError("n_points must be >= 3")
        u = np.linspace(0.0, 1.0, int(n_points))
        flipped_u = 1.0 - u
        denom = np.exp(float(sharpness)) - 1.0
        if np.isclose(denom, 0.0):
            return np.linspace(float(start), float(end), int(n_points))
        factor = (np.exp(float(sharpness) * flipped_u) - 1.0) / denom
        return 1.0 - (float(start) + (float(end) - float(start)) * factor)

    def NVIS_tracer(
        self,
        freq_mhz: np.ndarray | float,
        mode: str = "O",
        formulation: str = "appleton",
        collision_hz: np.ndarray | float | None = None,
        collision_type: str | None = None,
        b_t: np.ndarray | float | None = None,
        theta_deg: np.ndarray | float | None = None,
        n_floor: float = 1e-8,
        use_nonuniform_grid: bool = True,
        nonuniform_points: int = 240,
        nonuniform_sharpness: float = 10.0,
        compute_absorption_phase: bool = False,
        round_trip: bool = False,
    ) -> SimpleNamespace:
        """
        Vertical-forward-operator style NVIS tracer for a 1D profile.

        Parameters
        ----------
        freq_mhz : array-like or float
            Sounding frequencies in MHz.
        mode : str, optional
            Dispersion mode selector. Supported values are inherited directly
            from the selected dispersion formulation in ``dispersion.py``:
            - Appleton-Hartree: ``N/NO/ISO``, ``O``, ``X``, ``R``, ``L``
            - Sen-Wyller: ``N/NO/ISO``, ``O``, ``X``, ``R``, ``L``
        formulation : {"appleton", "senwyller"}, optional
            Dispersion backend.
        collision_hz : array-like or scalar, optional
            Collision frequency [Hz] as a direct 1D array. Mutually exclusive
            with ``collision_type``.
        collision_type : str, optional
            Named collision model. Requires ``rt.fetch_collision()`` to have
            been called first. Mutually exclusive with ``collision_hz``.
            Valid values: ``"FT"``, ``"FT_cc"``, ``"FT_mb"``, ``"SN_en"``,
            ``"SN_ei"``, ``"SN"``, ``"atm"`` (case-insensitive).
        b_t, theta_deg : array-like or scalar, optional
            Overrides for magnetic field magnitude [T] and wave-normal angle [deg].
        n_floor : float, optional
            Minimum refractive index used to identify valid propagation layers.
        use_nonuniform_grid : bool, optional
            If True, remap each frequency profile onto a stretched vertical
            grid with denser sampling near the turning altitude.
        nonuniform_points : int, optional
            Number of regridded altitude points used when
            ``use_nonuniform_grid=True``.
        nonuniform_sharpness : float, optional
            Stretching strength for nonuniform grid. Larger values concentrate
            more points near the turning altitude.
        compute_absorption_phase : bool, optional
            If True, call ``dispersion.evaluate()`` for each frequency and
            integrate absorption and phase along the propagation path.
            Adds ``absorption_db``, ``phase_rad``, ``absorption_profile``,
            and ``phase_profile`` to the returned namespace.
        round_trip : bool, optional
            If True (and ``compute_absorption_phase=True``), multiply the
            integrated absorption and phase by 2 for a two-way (round-trip)
            path.  Has no effect when ``compute_absorption_phase=False``.

        Returns
        -------
        SimpleNamespace
            - ``freq_mhz``          : frequency array [MHz]
            - ``vh_km``             : virtual-height estimate [km]
            - ``turning_height_km`` : turning heights [km]
            - ``n_profile``         : refractive-index profiles [nfreq, nz]
            - ``reason``            : per-frequency status strings
            - ``absorption_db``     : height-integrated absorption [dB, nfreq]
              (only when ``compute_absorption_phase=True``)
            - ``phase_rad``         : height-integrated phase [rad, nfreq]
              (only when ``compute_absorption_phase=True``)
            - ``absorption_profile``: absorption coefficient [dB/km] on the
              altitude grid [nfreq, nz]
              (only when ``compute_absorption_phase=True``)
            - ``phase_profile``     : phase constant [rad/km] on the altitude
              grid [nfreq, nz]
              (only when ``compute_absorption_phase=True``)

        Notes
        -----
        This method intentionally mirrors a vertical forward operator:
        it integrates an approximate group index ``mu' ~= 1 / n`` from the
        bottom altitude up to the turning point for each frequency.

        **Collision workflow** — two ways to supply collision frequency:

        1. *Direct array*: pass ``collision_hz`` as a 1D array [Hz].
        2. *Named model*: call ``rt.fetch_collision()`` first, then pass
           ``collision_type`` with one of the keys below.  ``collision_hz``
           must be ``None`` when ``collision_type`` is used.

        +-------------+--------------------------------------------------+
        | Key         | Model                                            |
        +=============+==================================================+
        | ``"FT"``    | Friedrich-Tonker (ν_ft, scaling a=1.0)           |
        | ``"FT_cc"`` | Friedrich-Tonker (ν_av_cc, scaling a=2.5)        |
        | ``"FT_mb"`` | Friedrich-Tonker (ν_av_mb, scaling 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            |
        +-------------+--------------------------------------------------+
        """
        # ── Resolve collision frequency ──────────────────────────────────
        if collision_type is not None and collision_hz is not None:
            raise ValueError(
                "Provide at most one of 'collision_hz' or 'collision_type', not both."
            )
        if collision_type is not None:
            if self.profile.collision is None:
                raise ValueError(
                    f"collision_type='{collision_type}' requires pre-computed collision "
                    "data. Call rt.fetch_collision() before NVIS_tracer()."
                )
            collision_hz = self._extract_collision_hz(
                self.profile.collision, collision_type
            )
            logger.info(
                "NVIS_tracer: using collision_type='{}', nu=[{:.3e},{:.3e}] Hz",
                collision_type,
                float(np.nanmin(collision_hz)),
                float(np.nanmax(collision_hz)),
            )

        z = np.asarray(self.profile.alt_km, dtype=float)
        f_mhz = np.atleast_1d(np.asarray(freq_mhz, dtype=float))
        if np.any(f_mhz <= 0.0):
            raise ValueError("All frequencies must be > 0 MHz.")
        mode = str(mode).upper()
        logger.info(
            "NVIS tracer start: mode={}, formulation={}, freq_points={}, "
            "nonuniform_grid={}, collision_type={}",
            mode,
            formulation,
            f_mhz.size,
            bool(use_nonuniform_grid),
            collision_type if collision_type is not None else "none",
        )

        n_all = np.full((f_mhz.size, z.size), np.nan, dtype=float)
        vh = np.full(f_mhz.size, np.nan, dtype=float)
        zt = np.full(f_mhz.size, np.nan, dtype=float)
        reason = np.full(f_mhz.size, "no_propagation", dtype=object)
        if compute_absorption_phase:
            abs_db = np.full(f_mhz.size, np.nan, dtype=float)
            phase_rad_out = np.full(f_mhz.size, np.nan, dtype=float)
            abs_profile_all = np.full((f_mhz.size, z.size), np.nan, dtype=float)
            ph_profile_all = np.full((f_mhz.size, z.size), np.nan, dtype=float)
            _trip = 2.0 if round_trip else 1.0

        z0 = float(np.min(z))
        for i, fm in enumerate(f_mhz):
            # Propagation mask and virtual-height integration use the
            # COLLISIONLESS refractive index (Z = 0).  Any non-zero collision
            # frequency gives Re(n) > 0 even when X > 1 (evanescent wave),
            # which would include sub-cutoff regions and produce absorption
            # hundreds of dB/km.  The collisionless n drops to zero exactly at
            # the plasma cutoff (X = 1), yielding the correct turning point.
            n = self._refractive_index_profile(
                frequency_hz=float(fm) * 1e6,
                mode=mode,
                formulation=formulation,
                collision_hz=0.0,
                b_t=b_t,
                theta_deg=theta_deg,
            )
            n_all[i, :] = n
            if compute_absorption_phase:
                # Full collisional dispersion for absorption/phase; integration
                # bounds are taken from the collisionless mask so the integral
                # never enters the evanescent region.
                dr = self._dispersion_result_profile(
                    frequency_hz=float(fm) * 1e6,
                    mode=mode,
                    formulation=formulation,
                    collision_hz=collision_hz,
                    b_t=b_t,
                    theta_deg=theta_deg,
                )
                abs_profile_all[i, :] = dr.absorption_db_per_km
                ph_profile_all[i, :] = dr.phase_rad_per_km

            mask = np.isfinite(n) & (n > float(n_floor))
            if not np.any(mask):
                reason[i] = "no_propagation"
                continue

            # Use only the first contiguous propagation segment from the bottom.
            # This avoids integrating through disconnected valid layers above a
            # cutoff, which can create non-physical huge virtual heights.
            i_start = int(np.argmax(mask))
            if i_start >= (z.size - 1):
                reason[i] = "no_propagation"
                continue

            i_stop = i_start
            while i_stop < z.size and mask[i_stop]:
                i_stop += 1
            i_top = i_stop - 1
            if (i_top - i_start + 1) < 2:
                reason[i] = "no_propagation"
                continue

            z_raw = z[i_start : i_top + 1]
            z_up = z_raw.copy()
            n_up = n[i_start : i_top + 1]
            if use_nonuniform_grid and z_up.size >= 3:
                m = self._smooth_nonuniform_grid(
                    0.0,
                    1.0,
                    int(nonuniform_points),
                    float(nonuniform_sharpness),
                )
                z_new = z_up[0] + m * (z_up[-1] - z_up[0])
                n_new = np.interp(z_new, z_up, n_up)
                z_up = z_new
                n_up = n_new

            mu_p = 1.0 / np.clip(n_up, float(n_floor), None)
            dz = np.diff(z_up)
            mu_mid = 0.5 * (mu_p[:-1] + mu_p[1:])
            iono_h = np.sum(mu_mid * dz) if dz.size > 0 else 0.0

            zt[i] = float(z_up[-1])
            vh[i] = float(z0 + iono_h)
            reason[i] = "turning" if i_stop < z.size else "top_of_profile"

            if compute_absorption_phase:
                # Integrate absorption on the original fine altitude grid
                # (z_raw, 0.1 km step).  The nonuniform grid concentrates
                # points near the turning height and undersamples the D-layer
                # where most absorption occurs, so we avoid regridding here.
                abs_up = dr.absorption_db_per_km[i_start : i_top + 1]
                ph_up = dr.phase_rad_per_km[i_start : i_top + 1]
                abs_db[i] = _trip * np.trapezoid(abs_up, z_raw)
                phase_rad_out[i] = _trip * np.trapezoid(ph_up, z_raw)

        ns = SimpleNamespace(
            freq_mhz=f_mhz,
            vh_km=vh,
            turning_height_km=zt,
            n_profile=n_all,
            reason=reason,
            alt_km=z,
        )
        if compute_absorption_phase:
            ns.absorption_db = abs_db
            ns.phase_rad = phase_rad_out
            ns.absorption_profile = abs_profile_all
            ns.phase_profile = ph_profile_all
        return ns

    # Compatibility static helpers.
    den_to_plasma_freq_hz = staticmethod(RT1DProfile.den_to_plasma_freq_hz)
    plasma_freq_to_den = staticmethod(RT1DProfile.plasma_freq_to_den)
    vertical_to_magnetic_angle = staticmethod(RT1DProfile.vertical_to_magnetic_angle)
    inclination_to_vertical_angle = staticmethod(
        RT1DProfile.inclination_to_vertical_angle
    )
    inclintation2vertical = staticmethod(RT1DProfile.inclintation2vertical)

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

Compute and attach collision frequencies to the profile.

Convenience wrapper around :meth:RT1DProfile.compute_collision. Requires that fetch_msise() has been called. Plasma defaults (Te=Ti=Tn, Op=0.9·Ne, O2p=0.1·Ne) are applied when arguments are omitted.

After calling this, pass collision_type to :meth:NVIS_tracer to select which model to use, e.g.::

rt.fetch_collision()
result = rt.NVIS_tracer(freq_mhz=freqs, collision_type="SN")
Returns

ComputeCollision

Source code in hfpytrace/model/rt1d.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:`RT1DProfile.compute_collision`.
    Requires that ``fetch_msise()`` has been called. Plasma defaults
    (Te=Ti=Tn, Op=0.9·Ne, O2p=0.1·Ne) are applied when arguments
    are omitted.

    After calling this, pass ``collision_type`` to
    :meth:`NVIS_tracer` to select which model to use, e.g.::

        rt.fetch_collision()
        result = rt.NVIS_tracer(freq_mhz=freqs, collision_type="SN")

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

NVIS_tracer(freq_mhz, mode='O', formulation='appleton', collision_hz=None, collision_type=None, b_t=None, theta_deg=None, n_floor=1e-08, use_nonuniform_grid=True, nonuniform_points=240, nonuniform_sharpness=10.0, compute_absorption_phase=False, round_trip=False)

Vertical-forward-operator style NVIS tracer for a 1D profile.

Parameters
array-like or float

Sounding frequencies in MHz.

str, optional

Dispersion mode selector. Supported values are inherited directly from the selected dispersion formulation in dispersion.py: - Appleton-Hartree: N/NO/ISO, O, X, R, L - Sen-Wyller: N/NO/ISO, O, X, R, L

{"appleton", "senwyller"}, optional

Dispersion backend.

array-like or scalar, optional

Collision frequency [Hz] as a direct 1D array. Mutually exclusive with collision_type.

str, optional

Named collision model. Requires rt.fetch_collision() to have been called first. Mutually exclusive with collision_hz. Valid values: "FT", "FT_cc", "FT_mb", "SN_en", "SN_ei", "SN", "atm" (case-insensitive).

b_t, theta_deg : array-like or scalar, optional Overrides for magnetic field magnitude [T] and wave-normal angle [deg].

float, optional

Minimum refractive index used to identify valid propagation layers.

bool, optional

If True, remap each frequency profile onto a stretched vertical grid with denser sampling near the turning altitude.

int, optional

Number of regridded altitude points used when use_nonuniform_grid=True.

float, optional

Stretching strength for nonuniform grid. Larger values concentrate more points near the turning altitude.

bool, optional

If True, call dispersion.evaluate() for each frequency and integrate absorption and phase along the propagation path. Adds absorption_db, phase_rad, absorption_profile, and phase_profile to the returned namespace.

bool, optional

If True (and compute_absorption_phase=True), multiply the integrated absorption and phase by 2 for a two-way (round-trip) path. Has no effect when compute_absorption_phase=False.

Returns

SimpleNamespace - freq_mhz : frequency array [MHz] - vh_km : virtual-height estimate [km] - turning_height_km : turning heights [km] - n_profile : refractive-index profiles [nfreq, nz] - reason : per-frequency status strings - absorption_db : height-integrated absorption [dB, nfreq] (only when compute_absorption_phase=True) - phase_rad : height-integrated phase [rad, nfreq] (only when compute_absorption_phase=True) - absorption_profile: absorption coefficient [dB/km] on the altitude grid [nfreq, nz] (only when compute_absorption_phase=True) - phase_profile : phase constant [rad/km] on the altitude grid [nfreq, nz] (only when compute_absorption_phase=True)

Notes

This method intentionally mirrors a vertical forward operator: it integrates an approximate group index mu' ~= 1 / n from the bottom altitude up to the turning point for each frequency.

Collision workflow — two ways to supply collision frequency:

  1. Direct array: pass collision_hz as a 1D array [Hz].
  2. Named model: call rt.fetch_collision() first, then pass collision_type with one of the keys below. collision_hz must be None when collision_type is used.

+-------------+--------------------------------------------------+ | Key | Model | +=============+==================================================+ | "FT" | Friedrich-Tonker (ν_ft, scaling a=1.0) | | "FT_cc" | Friedrich-Tonker (ν_av_cc, scaling a=2.5) | | "FT_mb" | Friedrich-Tonker (ν_av_mb, scaling 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/rt1d.py
def NVIS_tracer(
    self,
    freq_mhz: np.ndarray | float,
    mode: str = "O",
    formulation: str = "appleton",
    collision_hz: np.ndarray | float | None = None,
    collision_type: str | None = None,
    b_t: np.ndarray | float | None = None,
    theta_deg: np.ndarray | float | None = None,
    n_floor: float = 1e-8,
    use_nonuniform_grid: bool = True,
    nonuniform_points: int = 240,
    nonuniform_sharpness: float = 10.0,
    compute_absorption_phase: bool = False,
    round_trip: bool = False,
) -> SimpleNamespace:
    """
    Vertical-forward-operator style NVIS tracer for a 1D profile.

    Parameters
    ----------
    freq_mhz : array-like or float
        Sounding frequencies in MHz.
    mode : str, optional
        Dispersion mode selector. Supported values are inherited directly
        from the selected dispersion formulation in ``dispersion.py``:
        - Appleton-Hartree: ``N/NO/ISO``, ``O``, ``X``, ``R``, ``L``
        - Sen-Wyller: ``N/NO/ISO``, ``O``, ``X``, ``R``, ``L``
    formulation : {"appleton", "senwyller"}, optional
        Dispersion backend.
    collision_hz : array-like or scalar, optional
        Collision frequency [Hz] as a direct 1D array. Mutually exclusive
        with ``collision_type``.
    collision_type : str, optional
        Named collision model. Requires ``rt.fetch_collision()`` to have
        been called first. Mutually exclusive with ``collision_hz``.
        Valid values: ``"FT"``, ``"FT_cc"``, ``"FT_mb"``, ``"SN_en"``,
        ``"SN_ei"``, ``"SN"``, ``"atm"`` (case-insensitive).
    b_t, theta_deg : array-like or scalar, optional
        Overrides for magnetic field magnitude [T] and wave-normal angle [deg].
    n_floor : float, optional
        Minimum refractive index used to identify valid propagation layers.
    use_nonuniform_grid : bool, optional
        If True, remap each frequency profile onto a stretched vertical
        grid with denser sampling near the turning altitude.
    nonuniform_points : int, optional
        Number of regridded altitude points used when
        ``use_nonuniform_grid=True``.
    nonuniform_sharpness : float, optional
        Stretching strength for nonuniform grid. Larger values concentrate
        more points near the turning altitude.
    compute_absorption_phase : bool, optional
        If True, call ``dispersion.evaluate()`` for each frequency and
        integrate absorption and phase along the propagation path.
        Adds ``absorption_db``, ``phase_rad``, ``absorption_profile``,
        and ``phase_profile`` to the returned namespace.
    round_trip : bool, optional
        If True (and ``compute_absorption_phase=True``), multiply the
        integrated absorption and phase by 2 for a two-way (round-trip)
        path.  Has no effect when ``compute_absorption_phase=False``.

    Returns
    -------
    SimpleNamespace
        - ``freq_mhz``          : frequency array [MHz]
        - ``vh_km``             : virtual-height estimate [km]
        - ``turning_height_km`` : turning heights [km]
        - ``n_profile``         : refractive-index profiles [nfreq, nz]
        - ``reason``            : per-frequency status strings
        - ``absorption_db``     : height-integrated absorption [dB, nfreq]
          (only when ``compute_absorption_phase=True``)
        - ``phase_rad``         : height-integrated phase [rad, nfreq]
          (only when ``compute_absorption_phase=True``)
        - ``absorption_profile``: absorption coefficient [dB/km] on the
          altitude grid [nfreq, nz]
          (only when ``compute_absorption_phase=True``)
        - ``phase_profile``     : phase constant [rad/km] on the altitude
          grid [nfreq, nz]
          (only when ``compute_absorption_phase=True``)

    Notes
    -----
    This method intentionally mirrors a vertical forward operator:
    it integrates an approximate group index ``mu' ~= 1 / n`` from the
    bottom altitude up to the turning point for each frequency.

    **Collision workflow** — two ways to supply collision frequency:

    1. *Direct array*: pass ``collision_hz`` as a 1D array [Hz].
    2. *Named model*: call ``rt.fetch_collision()`` first, then pass
       ``collision_type`` with one of the keys below.  ``collision_hz``
       must be ``None`` when ``collision_type`` is used.

    +-------------+--------------------------------------------------+
    | Key         | Model                                            |
    +=============+==================================================+
    | ``"FT"``    | Friedrich-Tonker (ν_ft, scaling a=1.0)           |
    | ``"FT_cc"`` | Friedrich-Tonker (ν_av_cc, scaling a=2.5)        |
    | ``"FT_mb"`` | Friedrich-Tonker (ν_av_mb, scaling 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            |
    +-------------+--------------------------------------------------+
    """
    # ── Resolve collision frequency ──────────────────────────────────
    if collision_type is not None and collision_hz is not None:
        raise ValueError(
            "Provide at most one of 'collision_hz' or 'collision_type', not both."
        )
    if collision_type is not None:
        if self.profile.collision is None:
            raise ValueError(
                f"collision_type='{collision_type}' requires pre-computed collision "
                "data. Call rt.fetch_collision() before NVIS_tracer()."
            )
        collision_hz = self._extract_collision_hz(
            self.profile.collision, collision_type
        )
        logger.info(
            "NVIS_tracer: using collision_type='{}', nu=[{:.3e},{:.3e}] Hz",
            collision_type,
            float(np.nanmin(collision_hz)),
            float(np.nanmax(collision_hz)),
        )

    z = np.asarray(self.profile.alt_km, dtype=float)
    f_mhz = np.atleast_1d(np.asarray(freq_mhz, dtype=float))
    if np.any(f_mhz <= 0.0):
        raise ValueError("All frequencies must be > 0 MHz.")
    mode = str(mode).upper()
    logger.info(
        "NVIS tracer start: mode={}, formulation={}, freq_points={}, "
        "nonuniform_grid={}, collision_type={}",
        mode,
        formulation,
        f_mhz.size,
        bool(use_nonuniform_grid),
        collision_type if collision_type is not None else "none",
    )

    n_all = np.full((f_mhz.size, z.size), np.nan, dtype=float)
    vh = np.full(f_mhz.size, np.nan, dtype=float)
    zt = np.full(f_mhz.size, np.nan, dtype=float)
    reason = np.full(f_mhz.size, "no_propagation", dtype=object)
    if compute_absorption_phase:
        abs_db = np.full(f_mhz.size, np.nan, dtype=float)
        phase_rad_out = np.full(f_mhz.size, np.nan, dtype=float)
        abs_profile_all = np.full((f_mhz.size, z.size), np.nan, dtype=float)
        ph_profile_all = np.full((f_mhz.size, z.size), np.nan, dtype=float)
        _trip = 2.0 if round_trip else 1.0

    z0 = float(np.min(z))
    for i, fm in enumerate(f_mhz):
        # Propagation mask and virtual-height integration use the
        # COLLISIONLESS refractive index (Z = 0).  Any non-zero collision
        # frequency gives Re(n) > 0 even when X > 1 (evanescent wave),
        # which would include sub-cutoff regions and produce absorption
        # hundreds of dB/km.  The collisionless n drops to zero exactly at
        # the plasma cutoff (X = 1), yielding the correct turning point.
        n = self._refractive_index_profile(
            frequency_hz=float(fm) * 1e6,
            mode=mode,
            formulation=formulation,
            collision_hz=0.0,
            b_t=b_t,
            theta_deg=theta_deg,
        )
        n_all[i, :] = n
        if compute_absorption_phase:
            # Full collisional dispersion for absorption/phase; integration
            # bounds are taken from the collisionless mask so the integral
            # never enters the evanescent region.
            dr = self._dispersion_result_profile(
                frequency_hz=float(fm) * 1e6,
                mode=mode,
                formulation=formulation,
                collision_hz=collision_hz,
                b_t=b_t,
                theta_deg=theta_deg,
            )
            abs_profile_all[i, :] = dr.absorption_db_per_km
            ph_profile_all[i, :] = dr.phase_rad_per_km

        mask = np.isfinite(n) & (n > float(n_floor))
        if not np.any(mask):
            reason[i] = "no_propagation"
            continue

        # Use only the first contiguous propagation segment from the bottom.
        # This avoids integrating through disconnected valid layers above a
        # cutoff, which can create non-physical huge virtual heights.
        i_start = int(np.argmax(mask))
        if i_start >= (z.size - 1):
            reason[i] = "no_propagation"
            continue

        i_stop = i_start
        while i_stop < z.size and mask[i_stop]:
            i_stop += 1
        i_top = i_stop - 1
        if (i_top - i_start + 1) < 2:
            reason[i] = "no_propagation"
            continue

        z_raw = z[i_start : i_top + 1]
        z_up = z_raw.copy()
        n_up = n[i_start : i_top + 1]
        if use_nonuniform_grid and z_up.size >= 3:
            m = self._smooth_nonuniform_grid(
                0.0,
                1.0,
                int(nonuniform_points),
                float(nonuniform_sharpness),
            )
            z_new = z_up[0] + m * (z_up[-1] - z_up[0])
            n_new = np.interp(z_new, z_up, n_up)
            z_up = z_new
            n_up = n_new

        mu_p = 1.0 / np.clip(n_up, float(n_floor), None)
        dz = np.diff(z_up)
        mu_mid = 0.5 * (mu_p[:-1] + mu_p[1:])
        iono_h = np.sum(mu_mid * dz) if dz.size > 0 else 0.0

        zt[i] = float(z_up[-1])
        vh[i] = float(z0 + iono_h)
        reason[i] = "turning" if i_stop < z.size else "top_of_profile"

        if compute_absorption_phase:
            # Integrate absorption on the original fine altitude grid
            # (z_raw, 0.1 km step).  The nonuniform grid concentrates
            # points near the turning height and undersamples the D-layer
            # where most absorption occurs, so we avoid regridding here.
            abs_up = dr.absorption_db_per_km[i_start : i_top + 1]
            ph_up = dr.phase_rad_per_km[i_start : i_top + 1]
            abs_db[i] = _trip * np.trapezoid(abs_up, z_raw)
            phase_rad_out[i] = _trip * np.trapezoid(ph_up, z_raw)

    ns = SimpleNamespace(
        freq_mhz=f_mhz,
        vh_km=vh,
        turning_height_km=zt,
        n_profile=n_all,
        reason=reason,
        alt_km=z,
    )
    if compute_absorption_phase:
        ns.absorption_db = abs_db
        ns.phase_rad = phase_rad_out
        ns.absorption_profile = abs_profile_all
        ns.phase_profile = ph_profile_all
    return ns

RT2DConfig dataclass

Integration controls for :class:RT2D.

Source code in hfpytrace/model/rt2d.py
@dataclass
class RT2DConfig:
    """Integration controls for :class:`RT2D`."""

    x0_km: float = 0.0
    z0_km: float = 0.0
    ds_km: float = 1.0
    max_steps: int = 8000
    x_min_km: float | None = None
    x_max_km: float | None = None
    z_min_km: float = 0.0
    z_max_km: float | None = None
    n2_floor: float = 1e-5
    keep_every: int = 1

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

RT2D

Main 2D tracing interface for profile-based and legacy workflows.

Accepted initialization patterns: 1) direct grids: RT2D(x_km, z_km, ne_m3) 2) profile object: RT2D(profile=RT2DProfile(...)) 3) config-driven: RT2D(cfg=..., fetch_iri=True, ...)

Source code in hfpytrace/model/rt2d.py
 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
class RT2D:
    """
    Main 2D tracing interface for profile-based and legacy workflows.

    Accepted initialization patterns:
    1) direct grids: ``RT2D(x_km, z_km, ne_m3)``
    2) profile object: ``RT2D(profile=RT2DProfile(...))``
    3) config-driven: ``RT2D(cfg=..., fetch_iri=True, ...)``
    """

    def __init__(
        self,
        x_km: np.ndarray | None = None,
        z_km: np.ndarray | None = None,
        ne_m3: np.ndarray | None = None,
        *,
        profile: RT2DProfile | None = None,
        cfg=None,
        time: dt.datetime | str | None = None,
        lats: np.ndarray | None = None,
        lons: np.ndarray | None = None,
        alt_km: 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,
    ):
        """Create an RT2D solver instance and prepare interpolation kernels."""
        self.profile: RT2DProfile | None = None

        if profile is not None:
            if not isinstance(profile, RT2DProfile):
                raise TypeError("profile must be an RT2DProfile")
            profile.validate()
            self.profile = profile
            if self.profile.ne_m3 is None:
                raise ValueError("RT2DProfile must include ne_m3 to initialize RT2D")
            self.x_km = np.asarray(self.profile.x_km, dtype=float)
            self.z_km = np.asarray(self.profile.alt_km, dtype=float)
            self.ne_m3 = np.asarray(self.profile.ne_m3, dtype=float)
        elif x_km is not None and z_km is not None and ne_m3 is not None:
            # Legacy path
            self.x_km = np.asarray(x_km, dtype=float).ravel()
            self.z_km = np.asarray(z_km, dtype=float).ravel()
            self.ne_m3 = np.asarray(ne_m3, dtype=float)
        else:
            # Config/explicit profile assembly path
            if cfg is None:
                raise ValueError(
                    "Provide profile, or legacy arrays (x_km/z_km/ne_m3), or cfg-based inputs."
                )
            t = time if time is not None else dt.datetime.fromisoformat(str(cfg.event))
            self.profile = RT2DProfile.from_cfg(
                cfg=cfg,
                time=t,
                lats=lats,
                lons=lons,
                alt_km=alt_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,
                )
            if self.profile.ne_m3 is None:
                raise ValueError(
                    "No electron density available. Set ne_m3/ne_cm3 or fetch_iri=True."
                )
            self.x_km = np.asarray(self.profile.x_km, dtype=float)
            self.z_km = np.asarray(self.profile.alt_km, dtype=float)
            self.ne_m3 = np.asarray(self.profile.ne_m3, dtype=float)

        if self.ne_m3.shape != (self.z_km.size, self.x_km.size):
            raise ValueError("ne_m3 shape must be (len(z_km), len(x_km))")
        if not np.all(np.diff(self.x_km) > 0) or not np.all(np.diff(self.z_km) > 0):
            raise ValueError("x_km and z_km must be strictly increasing")

        self._ne_interp = RegularGridInterpolator(
            (self.z_km, self.x_km),
            self.ne_m3,
            method="linear",
            bounds_error=False,
            fill_value=np.nan,
        )
        self._dx = float(np.mean(np.diff(self.x_km)))
        self._dz = float(np.mean(np.diff(self.z_km)))
        self._n_interp = None
        self._dn_dx_interp = None
        self._dn_dz_interp = None
        self._mup_interp = None
        logger.info(
            "RT2D initialized: nx={}, nz={}, ne_shape={}",
            self.x_km.size,
            self.z_km.size,
            self.ne_m3.shape,
        )

    _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 profile fields (nz, nx)
        and can be passed directly to the dispersion models.

        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:`RT2DProfile.compute_collision`.
        Requires ``fetch_msise()`` to have been called on the profile first.

        After calling this, pass ``collision_type`` to
        :meth:`oblique_trace` to select which model to use, e.g.::

            rt = RT2D(profile=prof)
            rt.fetch_collision()
            ray = rt.oblique_trace(freq_hz=10.5e6, elevation_deg=25,
                                   collision_type="SN")

        Returns
        -------
        ComputeCollision
        """
        if self.profile is None:
            raise ValueError("RT2D has no attached profile. Cannot compute collision.")
        return self.profile.compute_collision(
            Te=Te,
            Ti=Ti,
            edens=edens,
            O2p=O2p,
            Op=Op,
        )

    def _inside(self, x: float, z: float, cfg: RT2DConfig) -> bool:
        """Check whether a point lies inside active tracing bounds."""
        x_min = self.x_km[0] if cfg.x_min_km is None else cfg.x_min_km
        x_max = self.x_km[-1] if cfg.x_max_km is None else cfg.x_max_km
        z_max = self.z_km[-1] if cfg.z_max_km is None else cfg.z_max_km
        return (x_min <= x <= x_max) and (cfg.z_min_km <= z <= z_max)

    def _sample_ne(self, x: float, z: float) -> float:
        """Sample electron density at a single Cartesian point."""
        return float(self._ne_interp(np.array([[z, x]], dtype=float))[0])

    def _n_and_grad_fd(
        self, freq_hz: float, x: float, z: float
    ) -> tuple[float, float, float]:
        """Finite-difference estimate of refractive index and spatial gradients."""
        ne = self._sample_ne(x, z)
        fp = RT1DProfile.den_to_plasma_freq_hz(np.maximum(ne, 0.0))
        n2 = max(1.0 - (fp / float(freq_hz)) ** 2, 1e-12)
        n = float(np.sqrt(n2))

        hx = max(self._dx, 1e-3)
        hz = max(self._dz, 1e-3)
        ne_xp = self._sample_ne(x + hx, z)
        ne_xm = self._sample_ne(x - hx, z)
        ne_zp = self._sample_ne(x, z + hz)
        ne_zm = self._sample_ne(x, z - hz)

        n2_xp = max(
            1.0
            - (RT1DProfile.den_to_plasma_freq_hz(np.maximum(ne_xp, 0.0)) / freq_hz)
            ** 2,
            1e-12,
        )
        n2_xm = max(
            1.0
            - (RT1DProfile.den_to_plasma_freq_hz(np.maximum(ne_xm, 0.0)) / freq_hz)
            ** 2,
            1e-12,
        )
        n2_zp = max(
            1.0
            - (RT1DProfile.den_to_plasma_freq_hz(np.maximum(ne_zp, 0.0)) / freq_hz)
            ** 2,
            1e-12,
        )
        n2_zm = max(
            1.0
            - (RT1DProfile.den_to_plasma_freq_hz(np.maximum(ne_zm, 0.0)) / freq_hz)
            ** 2,
            1e-12,
        )

        if n <= 0:
            return n, 0.0, 0.0
        dn_dx = 0.25 * (n2_xp - n2_xm) / (hx * n)
        dn_dz = 0.25 * (n2_zp - n2_zm) / (hz * n)
        return n, float(dn_dx), float(dn_dz)

    @staticmethod
    def _resolve_dispersion_model_name(formulation: str) -> str:
        """
        Map external model labels to internal canonical names.

        Canonical names:
        - ``appleton-hartree``
        - ``sen-wyller``
        """
        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_refractive_index_interpolators(
        self,
        freq_hz: float,
        b_abs_t: np.ndarray | float | None = None,
        b_psi_deg: np.ndarray | float | None = None,
        mode: str = "O",
        formulation: str = "appleton",
        collision_hz: np.ndarray | float | None = None,
        collision_type: str | None = None,
    ) -> SimpleNamespace:
        """
        Build refractive-index and gradient interpolators on the RT2D grid.

        The returned namespace includes:
        - ``n``: phase refractive index
        - ``mup``: group refractive index proxy (1/n)
        - ``dn_dx``, ``dn_dz``: Cartesian gradients of ``n``

        Parameters
        ----------
        collision_hz : array-like or float, optional
            Collision frequency [Hz], shape (nz, nx) or scalar. Mutually
            exclusive with ``collision_type``.
        collision_type : str, optional
            Named collision model key. Requires ``fetch_collision()`` to have
            been called first. Mutually exclusive with ``collision_hz``.
            Valid values: ``"FT"``, ``"FT_cc"``, ``"FT_mb"``, ``"SN_en"``,
            ``"SN_ei"``, ``"SN"``, ``"atm"`` (case-insensitive).
        """
        if collision_type is not None and collision_hz is not None:
            raise ValueError(
                "Provide at most one of 'collision_hz' or 'collision_type', not both."
            )
        if collision_type is not None:
            if self.profile is None or self.profile.collision is None:
                raise ValueError(
                    f"collision_type='{collision_type}' requires pre-computed collision. "
                    "Call rt.fetch_collision() first."
                )
            collision_hz = self._extract_collision_hz(
                self.profile.collision, collision_type
            )
            logger.info(
                "RT2D interpolators: using collision_type='{}', nu=[{:.3e},{:.3e}] Hz",
                collision_type,
                float(np.nanmin(collision_hz)),
                float(np.nanmax(collision_hz)),
            )

        model_name = self._resolve_dispersion_model_name(formulation)
        logger.info(
            "Building RT2D refractive index interpolators: freq={} Hz, mode={}, model={}, collision={}",
            float(freq_hz),
            mode,
            model_name,
            (
                collision_type
                if collision_type is not None
                else ("custom" if collision_hz is not None else "none")
            ),
        )
        if b_abs_t is None:
            b_abs_t_arr = np.zeros_like(self.ne_m3)
        else:
            b_abs_t_arr = np.asarray(b_abs_t, dtype=float)
            if b_abs_t_arr.ndim == 0:
                b_abs_t_arr = np.full_like(self.ne_m3, float(b_abs_t_arr))
        if b_psi_deg is None:
            b_psi_arr = np.zeros_like(self.ne_m3)
        else:
            b_psi_arr = np.asarray(b_psi_deg, dtype=float)
            if b_psi_arr.ndim == 0:
                b_psi_arr = np.full_like(self.ne_m3, float(b_psi_arr))

        nu_arr = (
            np.zeros_like(self.ne_m3)
            if collision_hz is None
            else (
                np.full_like(self.ne_m3, float(collision_hz))
                if np.asarray(collision_hz).ndim == 0
                else np.asarray(collision_hz, dtype=float)
            )
        )

        if model_name == "appleton-hartree":
            model = AppletonHartreeDispersion(
                frequency_hz=float(freq_hz),
                ne_m3=self.ne_m3,
                collision_hz=nu_arr,
                b_t=b_abs_t_arr,
                theta_deg=b_psi_arr,
            )
        elif model_name == "sen-wyller":
            model = SenWyllerDispersion(
                frequency_hz=float(freq_hz),
                ne_m3=self.ne_m3,
                collision_hz=nu_arr,
                b_t=b_abs_t_arr,
                theta_deg=b_psi_arr,
            )

        n_complex = model.refractive_index(mode=mode)
        n = np.real(n_complex)
        n = np.where(np.isfinite(n), np.clip(n, 0.0, None), np.nan)
        mup = 1.0 / np.clip(n, 1e-8, None)
        dn_dz, dn_dx = np.gradient(n, self.z_km, self.x_km)

        self._n_interp = RegularGridInterpolator(
            (self.z_km, self.x_km),
            n,
            method="linear",
            bounds_error=False,
            fill_value=np.nan,
        )
        self._dn_dx_interp = RegularGridInterpolator(
            (self.z_km, self.x_km),
            dn_dx,
            method="linear",
            bounds_error=False,
            fill_value=np.nan,
        )
        self._dn_dz_interp = RegularGridInterpolator(
            (self.z_km, self.x_km),
            dn_dz,
            method="linear",
            bounds_error=False,
            fill_value=np.nan,
        )
        self._mup_interp = RegularGridInterpolator(
            (self.z_km, self.x_km),
            mup,
            method="linear",
            bounds_error=False,
            fill_value=np.nan,
        )
        logger.debug("RT2D refractive index interpolators ready")
        return SimpleNamespace(n=n, mup=mup, dn_dx=dn_dx, dn_dz=dn_dz)

    def _eval_n_grad(
        self, x: np.ndarray, z: np.ndarray
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Evaluate phase index and gradients at Cartesian sample points."""
        if self._n_interp is None:
            raise RuntimeError("Call build_refractive_index_interpolators() first")
        x_arr = np.atleast_1d(np.asarray(x, dtype=float))
        z_arr = np.atleast_1d(np.asarray(z, dtype=float))
        x_arr, z_arr = np.broadcast_arrays(x_arr, z_arr)
        pts = np.column_stack([z_arr.ravel(), x_arr.ravel()])
        n = self._n_interp(pts).reshape(x_arr.shape)
        dnx = self._dn_dx_interp(pts).reshape(x_arr.shape)
        dnz = self._dn_dz_interp(pts).reshape(x_arr.shape)
        return n, dnx, dnz

    def _eval_mup(self, x: np.ndarray, z: np.ndarray) -> np.ndarray:
        """Evaluate group-index proxy at Cartesian sample points."""
        if self._mup_interp is None:
            raise RuntimeError("Call build_refractive_index_interpolators() first")
        x_arr = np.atleast_1d(np.asarray(x, dtype=float))
        z_arr = np.atleast_1d(np.asarray(z, dtype=float))
        x_arr, z_arr = np.broadcast_arrays(x_arr, z_arr)
        pts = np.column_stack([z_arr.ravel(), x_arr.ravel()])
        return self._mup_interp(pts).reshape(x_arr.shape)

    def _eval_n_grad_rphi(
        self,
        phi: np.ndarray,
        r: np.ndarray,
        r_earth_km: float,
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Evaluate n, dn/dr, dn/dphi by mapping spherical points to x-z grid."""
        phi_arr = np.atleast_1d(np.asarray(phi, dtype=float))
        r_arr = np.atleast_1d(np.asarray(r, dtype=float))
        phi_arr, r_arr = np.broadcast_arrays(phi_arr, r_arr)
        x = phi_arr * float(r_earth_km)
        z = r_arr - float(r_earth_km)
        n, dn_dx, dn_dz = self._eval_n_grad(x=x, z=z)
        dn_dr = dn_dz
        dn_dphi = dn_dx * float(r_earth_km)
        return n, dn_dr, dn_dphi

    @staticmethod
    def _ray_rhs(_s: float, y: np.ndarray, n_grad_fn) -> np.ndarray:
        """RHS for Cartesian ray ODE integrated over path length."""
        x, z, vx, vz = y
        n, dnx, dnz = n_grad_fn(np.array([x]), np.array([z]))
        n = float(n[0])
        dnx = float(dnx[0])
        dnz = float(dnz[0])
        if not np.isfinite(n) or n <= 0:
            return np.zeros(4)
        dot = dnx * vx + dnz * vz
        dvx = (dnx - dot * vx) / n
        dvz = (dnz - dot * vz) / n
        return np.array([vx, vz, dvx, dvz], dtype=float)

    @staticmethod
    def _ray_rhs_spherical(_s: float, y: np.ndarray, n_grad_rphi_fn) -> np.ndarray:
        """RHS for spherical (r, phi) ray ODE integrated over path length."""
        r, phi, v_r, v_phi = y
        n, dn_dr, dn_dphi = n_grad_rphi_fn(np.array([phi]), np.array([r]))
        n = float(n[0])
        dn_dr = float(dn_dr[0])
        dn_dphi = float(dn_dphi[0])
        if not np.isfinite(n) or n <= 0.0 or r <= 0.0:
            return np.zeros(4, dtype=float)
        grad_dot_v = dn_dr * v_r + (dn_dphi / r) * v_phi
        drds = v_r
        dphids = v_phi / r
        dv_r = (dn_dr - grad_dot_v * v_r) / n + (v_phi * v_phi) / r
        dv_phi = ((dn_dphi / r) - grad_dot_v * v_phi) / n - (v_r * v_phi) / r
        return np.array([drds, dphids, dv_r, dv_phi], dtype=float)

    def trace_cartesian_gradient(
        self,
        freq_hz: float,
        elevation_deg: float,
        x0_km: float = 0.0,
        z0_km: float = 0.0,
        s_max_km: float = 5000.0,
        mode: str = "O",
        b_abs_t: np.ndarray | float | None = None,
        b_psi_deg: np.ndarray | float | None = None,
        formulation: str = "appleton",
        collision_hz: np.ndarray | float | None = None,
        collision_type: str | None = None,
        rtol: float = 1e-7,
        atol: float = 1e-9,
        max_step_km: float | None = None,
    ) -> SimpleNamespace:
        """
        Integrate one oblique ray in Cartesian coordinates using gradient ODEs.

        Returns path coordinates, ray direction history, and derived path metrics.

        Parameters
        ----------
        collision_hz : array-like or float, optional
            Collision frequency [Hz], shape (nz, nx) or scalar. Mutually
            exclusive with ``collision_type``.
        collision_type : str, optional
            Named collision model. Requires ``fetch_collision()`` first.
            Valid values: ``"FT"``, ``"FT_cc"``, ``"FT_mb"``, ``"SN_en"``,
            ``"SN_ei"``, ``"SN"``, ``"atm"`` (case-insensitive).
        """
        logger.info(
            "RT2D gradient trace start: freq={} Hz, elev={} deg, mode={}, collision={}",
            float(freq_hz),
            float(elevation_deg),
            mode,
            (
                collision_type
                if collision_type is not None
                else ("custom" if collision_hz is not None else "none")
            ),
        )
        self.build_refractive_index_interpolators(
            freq_hz=freq_hz,
            b_abs_t=b_abs_t,
            b_psi_deg=b_psi_deg,
            mode=mode,
            formulation=formulation,
            collision_hz=collision_hz,
            collision_type=collision_type,
        )

        elev = np.deg2rad(float(elevation_deg))
        y0 = np.array(
            [float(x0_km), float(z0_km), np.cos(elev), np.sin(elev)], dtype=float
        )
        y0[2:] /= max(np.linalg.norm(y0[2:]), 1e-12)

        z_ground = float(self.z_km[0])
        z_top = float(self.z_km[-1])
        x_left = float(self.x_km[0])
        x_right = float(self.x_km[-1])

        def ev_ground(_s, y):
            return y[1] - z_ground - 1e-3

        def ev_top(_s, y):
            return z_top - y[1]

        def ev_left(_s, y):
            return y[0] - x_left

        def ev_right(_s, y):
            return x_right - y[0]

        for ev in (ev_ground, ev_top, ev_left, ev_right):
            ev.terminal = True
            ev.direction = -1.0

        sol = solve_ivp(
            lambda s, y: self._ray_rhs(s, y, self._eval_n_grad),
            (0.0, float(s_max_km)),
            y0,
            method="RK45",
            rtol=float(rtol),
            atol=float(atol),
            max_step=float(max_step_km) if max_step_km is not None else np.inf,
            events=[ev_ground, ev_top, ev_left, ev_right],
        )
        x = sol.y[0, :]
        z = sol.y[1, :]
        dx = np.diff(x)
        dz = np.diff(z)
        ds = np.hypot(dx, dz)
        group_path_km = float(np.nansum(ds))
        x_mid = 0.5 * (x[:-1] + x[1:])
        z_mid = 0.5 * (z[:-1] + z[1:])
        mup_mid = np.asarray(self._eval_mup(x_mid, z_mid), dtype=float)
        valid = np.isfinite(mup_mid)
        group_delay_sec = float(np.nansum((mup_mid[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"
        out = SimpleNamespace(
            x_km=x,
            z_km=z,
            vx=sol.y[2, :],
            vz=sol.y[3, :],
            t=sol.t,
            status=status,
            reason=status,
            group_path_km=group_path_km,
            group_delay_sec=group_delay_sec,
            ground_range_km=float(x[-1]) if status == "ground" else np.nan,
            x_apex_km=float(x[np.nanargmax(z)]) if z.size else np.nan,
            z_apex_km=float(np.nanmax(z)) if z.size else np.nan,
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            mode=mode,
        )
        logger.info("RT2D gradient trace complete: status={}", out.status)
        return out

    def trace_spherical_gradient(
        self,
        freq_hz: float,
        elevation_deg: float,
        x0_km: float = 0.0,
        z0_km: float = 0.0,
        s_max_km: float = 5000.0,
        mode: str = "O",
        b_abs_t: np.ndarray | float | None = None,
        b_psi_deg: np.ndarray | float | None = None,
        formulation: str = "appleton",
        collision_hz: np.ndarray | float | None = None,
        collision_type: str | None = None,
        r_earth_km: float = 6371.0,
        rtol: float = 1e-7,
        atol: float = 1e-9,
        max_step_km: float | None = None,
    ) -> SimpleNamespace:
        """
        Integrate one oblique ray in spherical geometry over the same n-field.

        The n-field is sampled from the internal x-z grid; geometry terms are
        handled in (r, phi) coordinates for better long-range behavior.

        Parameters
        ----------
        collision_hz : array-like or float, optional
            Collision frequency [Hz]. Mutually exclusive with ``collision_type``.
        collision_type : str, optional
            Named collision model key. Requires ``fetch_collision()`` first.
        """
        logger.info(
            "RT2D spherical gradient trace start: freq={} Hz, elev={} deg, mode={}, collision={}",
            float(freq_hz),
            float(elevation_deg),
            mode,
            (
                collision_type
                if collision_type is not None
                else ("custom" if collision_hz is not None else "none")
            ),
        )
        self.build_refractive_index_interpolators(
            freq_hz=freq_hz,
            b_abs_t=b_abs_t,
            b_psi_deg=b_psi_deg,
            mode=mode,
            formulation=formulation,
            collision_hz=collision_hz,
            collision_type=collision_type,
        )

        elev = np.deg2rad(float(elevation_deg))
        r0 = float(r_earth_km) + float(z0_km)
        phi0 = float(x0_km) / float(r_earth_km)
        y0 = np.array([r0, phi0, np.sin(elev), np.cos(elev)], dtype=float)
        y0[2:] /= max(np.linalg.norm(y0[2:]), 1e-12)

        r_ground = float(r_earth_km) + float(self.z_km[0])
        r_top = float(r_earth_km) + float(self.z_km[-1])
        phi_left = float(self.x_km[0]) / float(r_earth_km)
        phi_right = float(self.x_km[-1]) / float(r_earth_km)

        def ev_ground(_s, y):
            return y[0] - r_ground - 1e-3

        def ev_top(_s, y):
            return r_top - y[0]

        def ev_left(_s, y):
            return y[1] - phi_left

        def ev_right(_s, y):
            return phi_right - y[1]

        for ev in (ev_ground, ev_top, ev_left, ev_right):
            ev.terminal = True
            ev.direction = -1.0

        sol = solve_ivp(
            lambda s, y: self._ray_rhs_spherical(
                s,
                y,
                lambda phi, r: self._eval_n_grad_rphi(
                    phi=phi,
                    r=r,
                    r_earth_km=float(r_earth_km),
                ),
            ),
            (0.0, float(s_max_km)),
            y0,
            method="RK45",
            rtol=float(rtol),
            atol=float(atol),
            max_step=float(max_step_km) if max_step_km is not None else np.inf,
            events=[ev_ground, ev_top, ev_left, ev_right],
        )

        r = sol.y[0, :]
        phi = sol.y[1, :]
        x = float(r_earth_km) * phi
        z = r - float(r_earth_km)

        dr = np.diff(r)
        dphi = np.diff(phi)
        r_mid = 0.5 * (r[:-1] + r[1:])
        ds = np.sqrt(dr * dr + (r_mid * dphi) * (r_mid * dphi))
        group_path_km = float(np.nansum(ds))
        x_mid = 0.5 * (x[:-1] + x[1:])
        z_mid = 0.5 * (z[:-1] + z[1:])
        mup_mid = np.asarray(self._eval_mup(x_mid, z_mid), dtype=float)
        valid = np.isfinite(mup_mid)
        group_delay_sec = float(np.nansum((mup_mid[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"

        out = SimpleNamespace(
            x_km=x,
            z_km=z,
            r_km=r,
            phi_rad=phi,
            v_r=sol.y[2, :],
            v_phi=sol.y[3, :],
            t=sol.t,
            status=status,
            reason=status,
            group_path_km=group_path_km,
            group_delay_sec=group_delay_sec,
            ground_range_km=float(x[-1]) if status == "ground" else np.nan,
            x_apex_km=float(x[np.nanargmax(z)]) if z.size else np.nan,
            z_apex_km=float(np.nanmax(z)) if z.size else np.nan,
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            mode=mode,
            coordinate_system="spherical",
        )
        logger.info("RT2D spherical gradient trace complete: status={}", out.status)
        return out

    def oblique_trace(
        self,
        freq_hz: float,
        elevation_deg: float,
        *,
        coordinate_system: str = "cartesian",
        nhops: int = 1,
        **kwargs,
    ) -> SimpleNamespace:
        """
        Unified gradient tracer entry point for oblique propagation.

        Parameters
        ----------
        coordinate_system:
            ``"cartesian"`` or ``"spherical"`` (aliases accepted).
        nhops : int, optional
            Number of ionospheric hops to attempt (default 1).  For
            nhops > 1 each time a hop reaches the ground the ray
            direction is reflected (vz → −vz) and a new ODE restarts
            from that ground-hit point.  All segments are concatenated
            in the returned namespace.
        """
        nhops = max(1, int(nhops))
        coord = str(coordinate_system).strip().lower()
        if coord in {"cartesian", "cart", "xy"}:
            _tracer = self.trace_cartesian_gradient
        elif coord in {"spherical", "sph", "rphi"}:
            _tracer = self.trace_spherical_gradient
        else:
            raise ValueError("coordinate_system must be 'cartesian' or 'spherical'")

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

        # ── multi-hop path ─────────────────────────────────────────────────
        z_ground = float(self.z_km[0])
        r_earth_km = float(kwargs.get("r_earth_km", 6371.0))
        x_start = float(kwargs.pop("x0_km", 0.0))
        z_start = float(kwargs.pop("z0_km", z_ground))
        is_sph = coord in {"spherical", "sph", "rphi"}

        all_x: 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)
        # x_accum: running total of physical x displacement across all hops.
        # For hops 2+ we reset the ODE to x=0 inside the domain (horizontal
        # homogeneity) so the full n-field grid is available.  The output
        # x coordinates are then shifted back to physical positions.
        x_accum = x_start

        for _hop in range(nhops):
            # hops 2+ restart at the domain left edge; x output is shifted
            x_ode_start = 0.0 if _hop > 0 else x_start
            x_shift = x_accum if _hop > 0 else 0.0

            ray = _tracer(
                freq_hz=freq_hz,
                elevation_deg=elev,
                x0_km=x_ode_start,
                z0_km=z_start,
                **kwargs,
            )
            x_arr = np.asarray(ray.x_km, dtype=float) + x_shift
            z_arr = np.asarray(ray.z_km, dtype=float)
            all_x.append(x_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  # ray did not reach ground — no further hops

            # ── reflect at ground: compute new elevation from terminal velocity
            if is_sph:
                # Spherical state: [r, phi, v_r, v_phi].
                # Initial condition sets v_r=sin(elev), v_phi=cos(elev) so
                # v_r² + v_phi² = 1 (Euclidean normalisation, not spherical
                # metric).  Therefore elevation = arctan2(v_r, v_phi) — no
                # factor of r needed.
                v_r_last = float(ray.v_r[-1])  # < 0 at ground impact
                v_phi_last = float(ray.v_phi[-1])
                elev = float(np.degrees(np.arctan2(abs(v_r_last), abs(v_phi_last))))
            else:
                # cartesian state: [x, z, vx, vz]  (vz < 0 at descent)
                vx_last = float(ray.vx[-1])
                vz_last = float(ray.vz[-1])
                elev = float(np.degrees(np.arctan2(abs(vz_last), abs(vx_last))))

            x_accum = float(x_arr[-1])  # physical accumulated x at ground hit
            z_start = z_ground

        x_cat = np.concatenate(all_x) if all_x 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"
        _empty = np.array([], dtype=float)

        out = SimpleNamespace(
            x_km=x_cat,
            z_km=z_cat,
            status=final_status,
            reason=final_status,
            group_path_km=total_gpath,
            group_delay_sec=total_gdelay,
            ground_range_km=float(x_cat[-1]) if final_status == "ground" else np.nan,
            z_apex_km=float(z_apex_best) if z_apex_best > -np.inf else np.nan,
            x_apex_km=(
                float(x_cat[int(np.nanargmax(z_cat))]) if z_cat.size else np.nan
            ),
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            mode=getattr(last, "mode", None),
            coordinate_system=coord,
            nhops_completed=hops_done,
        )
        # carry terminal velocity attributes from the final hop
        if last is not None:
            if is_sph:
                out.v_r = last.v_r
                out.v_phi = last.v_phi
            else:
                out.vx = last.vx
                out.vz = last.vz
        return out

    def trace(
        self,
        freq_hz: float,
        elevation_deg: float,
        cfg: RT2DConfig | None = None,
    ) -> SimpleNamespace:
        """
        Legacy finite-difference tracer retained for backward compatibility.
        """
        logger.info(
            "RT2D FD trace start: freq={} Hz, elev={} deg",
            float(freq_hz),
            float(elevation_deg),
        )
        cfg = cfg or RT2DConfig()
        r = np.array([float(cfg.x0_km), float(cfg.z0_km)], dtype=float)
        el = np.deg2rad(float(elevation_deg))
        t = np.array([np.cos(el), np.sin(el)], dtype=float)

        xs: list[float] = []
        zs: list[float] = []
        ns: list[float] = []
        reason = "max_steps"

        for i in range(int(cfg.max_steps)):
            if not self._inside(r[0], r[1], cfg):
                reason = "out_of_bounds"
                break

            n, gx, gz = self._n_and_grad_fd(float(freq_hz), r[0], r[1])
            if not np.isfinite(n):
                reason = "nan_field"
                break
            if n * n < float(cfg.n2_floor):
                reason = "evanescent"
                break

            if i % max(1, int(cfg.keep_every)) == 0:
                xs.append(float(r[0]))
                zs.append(float(r[1]))
                ns.append(float(n))

            g = np.array([gx, gz], dtype=float)
            a = (g - np.dot(g, t) * t) / max(n, 1e-9)
            t = t + a * float(cfg.ds_km)
            t_norm = np.linalg.norm(t)
            if t_norm <= 0:
                reason = "invalid_direction"
                break
            t /= t_norm
            r = r + t * float(cfg.ds_km)

        out = SimpleNamespace(
            x_km=np.asarray(xs, dtype=float),
            z_km=np.asarray(zs, dtype=float),
            n=np.asarray(ns, dtype=float),
            freq_hz=float(freq_hz),
            elevation_deg=float(elevation_deg),
            reason=reason,
            status=reason,
        )
        logger.info("RT2D FD trace complete: status={}", out.status)
        return out

    def trace_fan(
        self,
        freqs_hz: np.ndarray,
        elevations_deg: np.ndarray,
        cfg: RT2DConfig | None = None,
    ) -> list[SimpleNamespace]:
        """Run a finite-difference fan sweep over frequencies and elevations."""
        out: list[SimpleNamespace] = []
        for f in np.asarray(freqs_hz, dtype=float):
            for el in np.asarray(elevations_deg, dtype=float):
                out.append(
                    self.trace(freq_hz=float(f), elevation_deg=float(el), cfg=cfg)
                )
        return out

__init__(x_km=None, z_km=None, ne_m3=None, *, profile=None, cfg=None, time=None, lats=None, lons=None, alt_km=None, ne_cm3=None, source='iri', fetch_iri=False, fetch_msise=False, fetch_geomag=False, workers=1)

Create an RT2D solver instance and prepare interpolation kernels.

Source code in hfpytrace/model/rt2d.py
def __init__(
    self,
    x_km: np.ndarray | None = None,
    z_km: np.ndarray | None = None,
    ne_m3: np.ndarray | None = None,
    *,
    profile: RT2DProfile | None = None,
    cfg=None,
    time: dt.datetime | str | None = None,
    lats: np.ndarray | None = None,
    lons: np.ndarray | None = None,
    alt_km: 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,
):
    """Create an RT2D solver instance and prepare interpolation kernels."""
    self.profile: RT2DProfile | None = None

    if profile is not None:
        if not isinstance(profile, RT2DProfile):
            raise TypeError("profile must be an RT2DProfile")
        profile.validate()
        self.profile = profile
        if self.profile.ne_m3 is None:
            raise ValueError("RT2DProfile must include ne_m3 to initialize RT2D")
        self.x_km = np.asarray(self.profile.x_km, dtype=float)
        self.z_km = np.asarray(self.profile.alt_km, dtype=float)
        self.ne_m3 = np.asarray(self.profile.ne_m3, dtype=float)
    elif x_km is not None and z_km is not None and ne_m3 is not None:
        # Legacy path
        self.x_km = np.asarray(x_km, dtype=float).ravel()
        self.z_km = np.asarray(z_km, dtype=float).ravel()
        self.ne_m3 = np.asarray(ne_m3, dtype=float)
    else:
        # Config/explicit profile assembly path
        if cfg is None:
            raise ValueError(
                "Provide profile, or legacy arrays (x_km/z_km/ne_m3), or cfg-based inputs."
            )
        t = time if time is not None else dt.datetime.fromisoformat(str(cfg.event))
        self.profile = RT2DProfile.from_cfg(
            cfg=cfg,
            time=t,
            lats=lats,
            lons=lons,
            alt_km=alt_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,
            )
        if self.profile.ne_m3 is None:
            raise ValueError(
                "No electron density available. Set ne_m3/ne_cm3 or fetch_iri=True."
            )
        self.x_km = np.asarray(self.profile.x_km, dtype=float)
        self.z_km = np.asarray(self.profile.alt_km, dtype=float)
        self.ne_m3 = np.asarray(self.profile.ne_m3, dtype=float)

    if self.ne_m3.shape != (self.z_km.size, self.x_km.size):
        raise ValueError("ne_m3 shape must be (len(z_km), len(x_km))")
    if not np.all(np.diff(self.x_km) > 0) or not np.all(np.diff(self.z_km) > 0):
        raise ValueError("x_km and z_km must be strictly increasing")

    self._ne_interp = RegularGridInterpolator(
        (self.z_km, self.x_km),
        self.ne_m3,
        method="linear",
        bounds_error=False,
        fill_value=np.nan,
    )
    self._dx = float(np.mean(np.diff(self.x_km)))
    self._dz = float(np.mean(np.diff(self.z_km)))
    self._n_interp = None
    self._dn_dx_interp = None
    self._dn_dz_interp = None
    self._mup_interp = None
    logger.info(
        "RT2D initialized: nx={}, nz={}, ne_shape={}",
        self.x_km.size,
        self.z_km.size,
        self.ne_m3.shape,
    )

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

Compute and attach collision frequencies to the profile.

Convenience wrapper around :meth:RT2DProfile.compute_collision. Requires fetch_msise() to have been called on the profile first.

After calling this, pass collision_type to :meth:oblique_trace to select which model to use, e.g.::

rt = RT2D(profile=prof)
rt.fetch_collision()
ray = rt.oblique_trace(freq_hz=10.5e6, elevation_deg=25,
                       collision_type="SN")
Returns

ComputeCollision

Source code in hfpytrace/model/rt2d.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:`RT2DProfile.compute_collision`.
    Requires ``fetch_msise()`` to have been called on the profile first.

    After calling this, pass ``collision_type`` to
    :meth:`oblique_trace` to select which model to use, e.g.::

        rt = RT2D(profile=prof)
        rt.fetch_collision()
        ray = rt.oblique_trace(freq_hz=10.5e6, elevation_deg=25,
                               collision_type="SN")

    Returns
    -------
    ComputeCollision
    """
    if self.profile is None:
        raise ValueError("RT2D has no attached profile. Cannot compute collision.")
    return self.profile.compute_collision(
        Te=Te,
        Ti=Ti,
        edens=edens,
        O2p=O2p,
        Op=Op,
    )

build_refractive_index_interpolators(freq_hz, b_abs_t=None, b_psi_deg=None, mode='O', formulation='appleton', collision_hz=None, collision_type=None)

Build refractive-index and gradient interpolators on the RT2D grid.

The returned namespace includes: - n: phase refractive index - mup: group refractive index proxy (1/n) - dn_dx, dn_dz: Cartesian gradients of n

Parameters
array-like or float, optional

Collision frequency [Hz], shape (nz, nx) or scalar. Mutually exclusive with collision_type.

str, optional

Named collision model key. Requires fetch_collision() to have been called first. Mutually exclusive with collision_hz. Valid values: "FT", "FT_cc", "FT_mb", "SN_en", "SN_ei", "SN", "atm" (case-insensitive).

Source code in hfpytrace/model/rt2d.py
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,
    mode: str = "O",
    formulation: str = "appleton",
    collision_hz: np.ndarray | float | None = None,
    collision_type: str | None = None,
) -> SimpleNamespace:
    """
    Build refractive-index and gradient interpolators on the RT2D grid.

    The returned namespace includes:
    - ``n``: phase refractive index
    - ``mup``: group refractive index proxy (1/n)
    - ``dn_dx``, ``dn_dz``: Cartesian gradients of ``n``

    Parameters
    ----------
    collision_hz : array-like or float, optional
        Collision frequency [Hz], shape (nz, nx) or scalar. Mutually
        exclusive with ``collision_type``.
    collision_type : str, optional
        Named collision model key. Requires ``fetch_collision()`` to have
        been called first. Mutually exclusive with ``collision_hz``.
        Valid values: ``"FT"``, ``"FT_cc"``, ``"FT_mb"``, ``"SN_en"``,
        ``"SN_ei"``, ``"SN"``, ``"atm"`` (case-insensitive).
    """
    if collision_type is not None and collision_hz is not None:
        raise ValueError(
            "Provide at most one of 'collision_hz' or 'collision_type', not both."
        )
    if collision_type is not None:
        if self.profile is None or self.profile.collision is None:
            raise ValueError(
                f"collision_type='{collision_type}' requires pre-computed collision. "
                "Call rt.fetch_collision() first."
            )
        collision_hz = self._extract_collision_hz(
            self.profile.collision, collision_type
        )
        logger.info(
            "RT2D interpolators: using collision_type='{}', nu=[{:.3e},{:.3e}] Hz",
            collision_type,
            float(np.nanmin(collision_hz)),
            float(np.nanmax(collision_hz)),
        )

    model_name = self._resolve_dispersion_model_name(formulation)
    logger.info(
        "Building RT2D refractive index interpolators: freq={} Hz, mode={}, model={}, collision={}",
        float(freq_hz),
        mode,
        model_name,
        (
            collision_type
            if collision_type is not None
            else ("custom" if collision_hz is not None else "none")
        ),
    )
    if b_abs_t is None:
        b_abs_t_arr = np.zeros_like(self.ne_m3)
    else:
        b_abs_t_arr = np.asarray(b_abs_t, dtype=float)
        if b_abs_t_arr.ndim == 0:
            b_abs_t_arr = np.full_like(self.ne_m3, float(b_abs_t_arr))
    if b_psi_deg is None:
        b_psi_arr = np.zeros_like(self.ne_m3)
    else:
        b_psi_arr = np.asarray(b_psi_deg, dtype=float)
        if b_psi_arr.ndim == 0:
            b_psi_arr = np.full_like(self.ne_m3, float(b_psi_arr))

    nu_arr = (
        np.zeros_like(self.ne_m3)
        if collision_hz is None
        else (
            np.full_like(self.ne_m3, float(collision_hz))
            if np.asarray(collision_hz).ndim == 0
            else np.asarray(collision_hz, dtype=float)
        )
    )

    if model_name == "appleton-hartree":
        model = AppletonHartreeDispersion(
            frequency_hz=float(freq_hz),
            ne_m3=self.ne_m3,
            collision_hz=nu_arr,
            b_t=b_abs_t_arr,
            theta_deg=b_psi_arr,
        )
    elif model_name == "sen-wyller":
        model = SenWyllerDispersion(
            frequency_hz=float(freq_hz),
            ne_m3=self.ne_m3,
            collision_hz=nu_arr,
            b_t=b_abs_t_arr,
            theta_deg=b_psi_arr,
        )

    n_complex = model.refractive_index(mode=mode)
    n = np.real(n_complex)
    n = np.where(np.isfinite(n), np.clip(n, 0.0, None), np.nan)
    mup = 1.0 / np.clip(n, 1e-8, None)
    dn_dz, dn_dx = np.gradient(n, self.z_km, self.x_km)

    self._n_interp = RegularGridInterpolator(
        (self.z_km, self.x_km),
        n,
        method="linear",
        bounds_error=False,
        fill_value=np.nan,
    )
    self._dn_dx_interp = RegularGridInterpolator(
        (self.z_km, self.x_km),
        dn_dx,
        method="linear",
        bounds_error=False,
        fill_value=np.nan,
    )
    self._dn_dz_interp = RegularGridInterpolator(
        (self.z_km, self.x_km),
        dn_dz,
        method="linear",
        bounds_error=False,
        fill_value=np.nan,
    )
    self._mup_interp = RegularGridInterpolator(
        (self.z_km, self.x_km),
        mup,
        method="linear",
        bounds_error=False,
        fill_value=np.nan,
    )
    logger.debug("RT2D refractive index interpolators ready")
    return SimpleNamespace(n=n, mup=mup, dn_dx=dn_dx, dn_dz=dn_dz)

trace_cartesian_gradient(freq_hz, elevation_deg, x0_km=0.0, z0_km=0.0, s_max_km=5000.0, mode='O', b_abs_t=None, b_psi_deg=None, formulation='appleton', collision_hz=None, collision_type=None, rtol=1e-07, atol=1e-09, max_step_km=None)

Integrate one oblique ray in Cartesian coordinates using gradient ODEs.

Returns path coordinates, ray direction history, and derived path metrics.

Parameters
array-like or float, optional

Collision frequency [Hz], shape (nz, nx) or scalar. Mutually exclusive with collision_type.

str, optional

Named collision model. Requires fetch_collision() first. Valid values: "FT", "FT_cc", "FT_mb", "SN_en", "SN_ei", "SN", "atm" (case-insensitive).

Source code in hfpytrace/model/rt2d.py
def trace_cartesian_gradient(
    self,
    freq_hz: float,
    elevation_deg: float,
    x0_km: float = 0.0,
    z0_km: float = 0.0,
    s_max_km: float = 5000.0,
    mode: str = "O",
    b_abs_t: np.ndarray | float | None = None,
    b_psi_deg: np.ndarray | float | None = None,
    formulation: str = "appleton",
    collision_hz: np.ndarray | float | None = None,
    collision_type: str | None = None,
    rtol: float = 1e-7,
    atol: float = 1e-9,
    max_step_km: float | None = None,
) -> SimpleNamespace:
    """
    Integrate one oblique ray in Cartesian coordinates using gradient ODEs.

    Returns path coordinates, ray direction history, and derived path metrics.

    Parameters
    ----------
    collision_hz : array-like or float, optional
        Collision frequency [Hz], shape (nz, nx) or scalar. Mutually
        exclusive with ``collision_type``.
    collision_type : str, optional
        Named collision model. Requires ``fetch_collision()`` first.
        Valid values: ``"FT"``, ``"FT_cc"``, ``"FT_mb"``, ``"SN_en"``,
        ``"SN_ei"``, ``"SN"``, ``"atm"`` (case-insensitive).
    """
    logger.info(
        "RT2D gradient trace start: freq={} Hz, elev={} deg, mode={}, collision={}",
        float(freq_hz),
        float(elevation_deg),
        mode,
        (
            collision_type
            if collision_type is not None
            else ("custom" if collision_hz is not None else "none")
        ),
    )
    self.build_refractive_index_interpolators(
        freq_hz=freq_hz,
        b_abs_t=b_abs_t,
        b_psi_deg=b_psi_deg,
        mode=mode,
        formulation=formulation,
        collision_hz=collision_hz,
        collision_type=collision_type,
    )

    elev = np.deg2rad(float(elevation_deg))
    y0 = np.array(
        [float(x0_km), float(z0_km), np.cos(elev), np.sin(elev)], dtype=float
    )
    y0[2:] /= max(np.linalg.norm(y0[2:]), 1e-12)

    z_ground = float(self.z_km[0])
    z_top = float(self.z_km[-1])
    x_left = float(self.x_km[0])
    x_right = float(self.x_km[-1])

    def ev_ground(_s, y):
        return y[1] - z_ground - 1e-3

    def ev_top(_s, y):
        return z_top - y[1]

    def ev_left(_s, y):
        return y[0] - x_left

    def ev_right(_s, y):
        return x_right - y[0]

    for ev in (ev_ground, ev_top, ev_left, ev_right):
        ev.terminal = True
        ev.direction = -1.0

    sol = solve_ivp(
        lambda s, y: self._ray_rhs(s, y, self._eval_n_grad),
        (0.0, float(s_max_km)),
        y0,
        method="RK45",
        rtol=float(rtol),
        atol=float(atol),
        max_step=float(max_step_km) if max_step_km is not None else np.inf,
        events=[ev_ground, ev_top, ev_left, ev_right],
    )
    x = sol.y[0, :]
    z = sol.y[1, :]
    dx = np.diff(x)
    dz = np.diff(z)
    ds = np.hypot(dx, dz)
    group_path_km = float(np.nansum(ds))
    x_mid = 0.5 * (x[:-1] + x[1:])
    z_mid = 0.5 * (z[:-1] + z[1:])
    mup_mid = np.asarray(self._eval_mup(x_mid, z_mid), dtype=float)
    valid = np.isfinite(mup_mid)
    group_delay_sec = float(np.nansum((mup_mid[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"
    out = SimpleNamespace(
        x_km=x,
        z_km=z,
        vx=sol.y[2, :],
        vz=sol.y[3, :],
        t=sol.t,
        status=status,
        reason=status,
        group_path_km=group_path_km,
        group_delay_sec=group_delay_sec,
        ground_range_km=float(x[-1]) if status == "ground" else np.nan,
        x_apex_km=float(x[np.nanargmax(z)]) if z.size else np.nan,
        z_apex_km=float(np.nanmax(z)) if z.size else np.nan,
        freq_hz=float(freq_hz),
        elevation_deg=float(elevation_deg),
        mode=mode,
    )
    logger.info("RT2D gradient trace complete: status={}", out.status)
    return out

trace_spherical_gradient(freq_hz, elevation_deg, x0_km=0.0, z0_km=0.0, s_max_km=5000.0, mode='O', b_abs_t=None, b_psi_deg=None, formulation='appleton', collision_hz=None, collision_type=None, r_earth_km=6371.0, rtol=1e-07, atol=1e-09, max_step_km=None)

Integrate one oblique ray in spherical geometry over the same n-field.

The n-field is sampled from the internal x-z grid; geometry terms are handled in (r, phi) coordinates for better long-range behavior.

Parameters
array-like or float, optional

Collision frequency [Hz]. Mutually exclusive with collision_type.

str, optional

Named collision model key. Requires fetch_collision() first.

Source code in hfpytrace/model/rt2d.py
def trace_spherical_gradient(
    self,
    freq_hz: float,
    elevation_deg: float,
    x0_km: float = 0.0,
    z0_km: float = 0.0,
    s_max_km: float = 5000.0,
    mode: str = "O",
    b_abs_t: np.ndarray | float | None = None,
    b_psi_deg: np.ndarray | float | None = None,
    formulation: str = "appleton",
    collision_hz: np.ndarray | float | None = None,
    collision_type: str | None = None,
    r_earth_km: float = 6371.0,
    rtol: float = 1e-7,
    atol: float = 1e-9,
    max_step_km: float | None = None,
) -> SimpleNamespace:
    """
    Integrate one oblique ray in spherical geometry over the same n-field.

    The n-field is sampled from the internal x-z grid; geometry terms are
    handled in (r, phi) coordinates for better long-range behavior.

    Parameters
    ----------
    collision_hz : array-like or float, optional
        Collision frequency [Hz]. Mutually exclusive with ``collision_type``.
    collision_type : str, optional
        Named collision model key. Requires ``fetch_collision()`` first.
    """
    logger.info(
        "RT2D spherical gradient trace start: freq={} Hz, elev={} deg, mode={}, collision={}",
        float(freq_hz),
        float(elevation_deg),
        mode,
        (
            collision_type
            if collision_type is not None
            else ("custom" if collision_hz is not None else "none")
        ),
    )
    self.build_refractive_index_interpolators(
        freq_hz=freq_hz,
        b_abs_t=b_abs_t,
        b_psi_deg=b_psi_deg,
        mode=mode,
        formulation=formulation,
        collision_hz=collision_hz,
        collision_type=collision_type,
    )

    elev = np.deg2rad(float(elevation_deg))
    r0 = float(r_earth_km) + float(z0_km)
    phi0 = float(x0_km) / float(r_earth_km)
    y0 = np.array([r0, phi0, np.sin(elev), np.cos(elev)], dtype=float)
    y0[2:] /= max(np.linalg.norm(y0[2:]), 1e-12)

    r_ground = float(r_earth_km) + float(self.z_km[0])
    r_top = float(r_earth_km) + float(self.z_km[-1])
    phi_left = float(self.x_km[0]) / float(r_earth_km)
    phi_right = float(self.x_km[-1]) / float(r_earth_km)

    def ev_ground(_s, y):
        return y[0] - r_ground - 1e-3

    def ev_top(_s, y):
        return r_top - y[0]

    def ev_left(_s, y):
        return y[1] - phi_left

    def ev_right(_s, y):
        return phi_right - y[1]

    for ev in (ev_ground, ev_top, ev_left, ev_right):
        ev.terminal = True
        ev.direction = -1.0

    sol = solve_ivp(
        lambda s, y: self._ray_rhs_spherical(
            s,
            y,
            lambda phi, r: self._eval_n_grad_rphi(
                phi=phi,
                r=r,
                r_earth_km=float(r_earth_km),
            ),
        ),
        (0.0, float(s_max_km)),
        y0,
        method="RK45",
        rtol=float(rtol),
        atol=float(atol),
        max_step=float(max_step_km) if max_step_km is not None else np.inf,
        events=[ev_ground, ev_top, ev_left, ev_right],
    )

    r = sol.y[0, :]
    phi = sol.y[1, :]
    x = float(r_earth_km) * phi
    z = r - float(r_earth_km)

    dr = np.diff(r)
    dphi = np.diff(phi)
    r_mid = 0.5 * (r[:-1] + r[1:])
    ds = np.sqrt(dr * dr + (r_mid * dphi) * (r_mid * dphi))
    group_path_km = float(np.nansum(ds))
    x_mid = 0.5 * (x[:-1] + x[1:])
    z_mid = 0.5 * (z[:-1] + z[1:])
    mup_mid = np.asarray(self._eval_mup(x_mid, z_mid), dtype=float)
    valid = np.isfinite(mup_mid)
    group_delay_sec = float(np.nansum((mup_mid[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"

    out = SimpleNamespace(
        x_km=x,
        z_km=z,
        r_km=r,
        phi_rad=phi,
        v_r=sol.y[2, :],
        v_phi=sol.y[3, :],
        t=sol.t,
        status=status,
        reason=status,
        group_path_km=group_path_km,
        group_delay_sec=group_delay_sec,
        ground_range_km=float(x[-1]) if status == "ground" else np.nan,
        x_apex_km=float(x[np.nanargmax(z)]) if z.size else np.nan,
        z_apex_km=float(np.nanmax(z)) if z.size else np.nan,
        freq_hz=float(freq_hz),
        elevation_deg=float(elevation_deg),
        mode=mode,
        coordinate_system="spherical",
    )
    logger.info("RT2D spherical gradient trace complete: status={}", out.status)
    return out

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

Unified gradient tracer entry point for oblique propagation.

Parameters
coordinate_system

"cartesian" or "spherical" (aliases accepted).

int, optional

Number of ionospheric hops to attempt (default 1). For nhops > 1 each time a hop reaches the ground the ray direction is reflected (vz → −vz) and a new ODE restarts from that ground-hit point. All segments are concatenated in the returned namespace.

Source code in hfpytrace/model/rt2d.py
def oblique_trace(
    self,
    freq_hz: float,
    elevation_deg: float,
    *,
    coordinate_system: str = "cartesian",
    nhops: int = 1,
    **kwargs,
) -> SimpleNamespace:
    """
    Unified gradient tracer entry point for oblique propagation.

    Parameters
    ----------
    coordinate_system:
        ``"cartesian"`` or ``"spherical"`` (aliases accepted).
    nhops : int, optional
        Number of ionospheric hops to attempt (default 1).  For
        nhops > 1 each time a hop reaches the ground the ray
        direction is reflected (vz → −vz) and a new ODE restarts
        from that ground-hit point.  All segments are concatenated
        in the returned namespace.
    """
    nhops = max(1, int(nhops))
    coord = str(coordinate_system).strip().lower()
    if coord in {"cartesian", "cart", "xy"}:
        _tracer = self.trace_cartesian_gradient
    elif coord in {"spherical", "sph", "rphi"}:
        _tracer = self.trace_spherical_gradient
    else:
        raise ValueError("coordinate_system must be 'cartesian' or 'spherical'")

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

    # ── multi-hop path ─────────────────────────────────────────────────
    z_ground = float(self.z_km[0])
    r_earth_km = float(kwargs.get("r_earth_km", 6371.0))
    x_start = float(kwargs.pop("x0_km", 0.0))
    z_start = float(kwargs.pop("z0_km", z_ground))
    is_sph = coord in {"spherical", "sph", "rphi"}

    all_x: 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)
    # x_accum: running total of physical x displacement across all hops.
    # For hops 2+ we reset the ODE to x=0 inside the domain (horizontal
    # homogeneity) so the full n-field grid is available.  The output
    # x coordinates are then shifted back to physical positions.
    x_accum = x_start

    for _hop in range(nhops):
        # hops 2+ restart at the domain left edge; x output is shifted
        x_ode_start = 0.0 if _hop > 0 else x_start
        x_shift = x_accum if _hop > 0 else 0.0

        ray = _tracer(
            freq_hz=freq_hz,
            elevation_deg=elev,
            x0_km=x_ode_start,
            z0_km=z_start,
            **kwargs,
        )
        x_arr = np.asarray(ray.x_km, dtype=float) + x_shift
        z_arr = np.asarray(ray.z_km, dtype=float)
        all_x.append(x_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  # ray did not reach ground — no further hops

        # ── reflect at ground: compute new elevation from terminal velocity
        if is_sph:
            # Spherical state: [r, phi, v_r, v_phi].
            # Initial condition sets v_r=sin(elev), v_phi=cos(elev) so
            # v_r² + v_phi² = 1 (Euclidean normalisation, not spherical
            # metric).  Therefore elevation = arctan2(v_r, v_phi) — no
            # factor of r needed.
            v_r_last = float(ray.v_r[-1])  # < 0 at ground impact
            v_phi_last = float(ray.v_phi[-1])
            elev = float(np.degrees(np.arctan2(abs(v_r_last), abs(v_phi_last))))
        else:
            # cartesian state: [x, z, vx, vz]  (vz < 0 at descent)
            vx_last = float(ray.vx[-1])
            vz_last = float(ray.vz[-1])
            elev = float(np.degrees(np.arctan2(abs(vz_last), abs(vx_last))))

        x_accum = float(x_arr[-1])  # physical accumulated x at ground hit
        z_start = z_ground

    x_cat = np.concatenate(all_x) if all_x 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"
    _empty = np.array([], dtype=float)

    out = SimpleNamespace(
        x_km=x_cat,
        z_km=z_cat,
        status=final_status,
        reason=final_status,
        group_path_km=total_gpath,
        group_delay_sec=total_gdelay,
        ground_range_km=float(x_cat[-1]) if final_status == "ground" else np.nan,
        z_apex_km=float(z_apex_best) if z_apex_best > -np.inf else np.nan,
        x_apex_km=(
            float(x_cat[int(np.nanargmax(z_cat))]) if z_cat.size else np.nan
        ),
        freq_hz=float(freq_hz),
        elevation_deg=float(elevation_deg),
        mode=getattr(last, "mode", None),
        coordinate_system=coord,
        nhops_completed=hops_done,
    )
    # carry terminal velocity attributes from the final hop
    if last is not None:
        if is_sph:
            out.v_r = last.v_r
            out.v_phi = last.v_phi
        else:
            out.vx = last.vx
            out.vz = last.vz
    return out

trace(freq_hz, elevation_deg, cfg=None)

Legacy finite-difference tracer retained for backward compatibility.

Source code in hfpytrace/model/rt2d.py
def trace(
    self,
    freq_hz: float,
    elevation_deg: float,
    cfg: RT2DConfig | None = None,
) -> SimpleNamespace:
    """
    Legacy finite-difference tracer retained for backward compatibility.
    """
    logger.info(
        "RT2D FD trace start: freq={} Hz, elev={} deg",
        float(freq_hz),
        float(elevation_deg),
    )
    cfg = cfg or RT2DConfig()
    r = np.array([float(cfg.x0_km), float(cfg.z0_km)], dtype=float)
    el = np.deg2rad(float(elevation_deg))
    t = np.array([np.cos(el), np.sin(el)], dtype=float)

    xs: list[float] = []
    zs: list[float] = []
    ns: list[float] = []
    reason = "max_steps"

    for i in range(int(cfg.max_steps)):
        if not self._inside(r[0], r[1], cfg):
            reason = "out_of_bounds"
            break

        n, gx, gz = self._n_and_grad_fd(float(freq_hz), r[0], r[1])
        if not np.isfinite(n):
            reason = "nan_field"
            break
        if n * n < float(cfg.n2_floor):
            reason = "evanescent"
            break

        if i % max(1, int(cfg.keep_every)) == 0:
            xs.append(float(r[0]))
            zs.append(float(r[1]))
            ns.append(float(n))

        g = np.array([gx, gz], dtype=float)
        a = (g - np.dot(g, t) * t) / max(n, 1e-9)
        t = t + a * float(cfg.ds_km)
        t_norm = np.linalg.norm(t)
        if t_norm <= 0:
            reason = "invalid_direction"
            break
        t /= t_norm
        r = r + t * float(cfg.ds_km)

    out = SimpleNamespace(
        x_km=np.asarray(xs, dtype=float),
        z_km=np.asarray(zs, dtype=float),
        n=np.asarray(ns, dtype=float),
        freq_hz=float(freq_hz),
        elevation_deg=float(elevation_deg),
        reason=reason,
        status=reason,
    )
    logger.info("RT2D FD trace complete: status={}", out.status)
    return out

trace_fan(freqs_hz, elevations_deg, cfg=None)

Run a finite-difference fan sweep over frequencies and elevations.

Source code in hfpytrace/model/rt2d.py
def trace_fan(
    self,
    freqs_hz: np.ndarray,
    elevations_deg: np.ndarray,
    cfg: RT2DConfig | None = None,
) -> list[SimpleNamespace]:
    """Run a finite-difference fan sweep over frequencies and elevations."""
    out: list[SimpleNamespace] = []
    for f in np.asarray(freqs_hz, dtype=float):
        for el in np.asarray(elevations_deg, dtype=float):
            out.append(
                self.trace(freq_hz=float(f), elevation_deg=float(el), cfg=cfg)
            )
    return out

Source Code

hfpytrace/model/__init__.py
"""hfpytrace.model — ionospheric ray-tracing model classes.

This sub-package contains the core ray-tracing and dispersion models:

RT1D
    1-D vertical-incidence tracer using a simple ODE integrator.
RT2D / RT2DProfile / RT2DConfig
    2-D great-circle ray-tracing with a configurable ionospheric profile
    (IRI, SAMI3, GEMINI, etc.).
RT3D / RT3DProfile
    3-D oblique ray-tracing via PHaRLAP (``raytrace_3d`` or
    ``raytrace_3d_sp``).
DispersionResult
    Container for refractive index, absorption, and related propagation metrics.
AppletonHartreeDispersion
    Appleton-Hartree magneto-ionic dispersion relation.
SenWyllerDispersion
    Sen-Wyller generalized dispersion relation (includes electron collision
    frequency via a non-Maxwellian velocity distribution).
"""

from loguru import logger

from .dispersion import AppletonHartreeDispersion, DispersionResult, SenWyllerDispersion
from .rt1d import RT1D, RT1DProfile
from .rt2d import RT2D, RT2DConfig, RT2DProfile
from .rt3d import RT3D, RT3DProfile

__all__ = [
    "RT1D",
    "RT1DProfile",
    "RT2D",
    "RT2DProfile",
    "RT2DConfig",
    "RT3D",
    "RT3DProfile",
    "DispersionResult",
    "AppletonHartreeDispersion",
    "SenWyllerDispersion",
]

logger.debug("hfpytrace.model namespace imported")