Skip to content

hfpytrace.collision

Package

Collision-frequency models and NRLMSISE-backed neutral background support.

Key Classes

Class NRLMSISE2D
Class NRLMSISE3D
Class ComputeCollision

Key Methods

Method NRLMSISE2D.fetch_dataset()
Method NRLMSISE3D.fetch_dataset()
Method ComputeCollision.from_nrlmsise()
Method ComputeCollision.from_nrlmsise_3d()
Method ComputeCollision.calculate_FT_collision_frequency()

API

hfpytrace.collision

Electron collision-frequency models.

Provides NRLMSISE-00-based neutral background models (2D and 3D) and multiple formulations for computing electron collision frequencies:

  • Friedrich-Tonker (FT) — pressure-based approximation.
  • Schunk-Nagy (SN) electron-neutral — species-resolved (N₂, O₂, O, H, He).
  • Schunk-Nagy (SN) electron-ion — Coulomb logarithm formulation (O₂⁺, O⁺).

The results are stored as a nested :class:Collision dataclass, which can be passed directly to HF ray-tracing engine grid construction.

Requires

nrlmsise00 : for neutral atmosphere profiles (pip install 'nrlmsise00[dataset]').

Classes

Collision_en Per-species electron-neutral collision frequency container. Collision_ei Per-species electron-ion collision frequency container. Collision_SN Combined Schunk-Nagy collision container (SN-en + SN-ei + total). Collision Top-level collision dataclass (FT variants + SN). NRLMSISE2D NRLMSISE-00 neutral background on a 2D (height × route) grid. NRLMSISE3D NRLMSISE-00 neutral background on a 3D (lat × lon × height) grid. ComputeCollision Derives all collision profiles from plasma/neutral state arrays.

Collision_en dataclass

Per-species electron-neutral collision frequency arrays.

Each field has the same shape as the input plasma/neutral grids. Units are Hz (s⁻¹) throughout.

Attributes

N2, O2, O, H, He : np.ndarray or None Species-resolved collision frequency contributions.

np.ndarray or None

Sum of all species contributions.

Source code in hfpytrace/collision.py
@dataclass
class Collision_en:
    """Per-species electron-neutral collision frequency arrays.

    Each field has the same shape as the input plasma/neutral grids.
    Units are Hz (s⁻¹) throughout.

    Attributes
    ----------
    N2, O2, O, H, He : np.ndarray or None
        Species-resolved collision frequency contributions.
    total : np.ndarray or None
        Sum of all species contributions.
    """

    N2: np.ndarray | None = None
    O2: np.ndarray | None = None
    O: np.ndarray | None = None
    H: np.ndarray | None = None
    He: np.ndarray | None = None
    total: np.ndarray | None = None

Collision_ei dataclass

Per-species electron-ion collision frequency arrays.

Attributes

O2p, Op : np.ndarray or None Species-resolved collision frequency contributions.

np.ndarray or None

Sum of O₂⁺ and O⁺ contributions.

Source code in hfpytrace/collision.py
@dataclass
class Collision_ei:
    """Per-species electron-ion collision frequency arrays.

    Attributes
    ----------
    O2p, Op : np.ndarray or None
        Species-resolved collision frequency contributions.
    total : np.ndarray or None
        Sum of O₂⁺ and O⁺ contributions.
    """

    O2p: np.ndarray | None = None
    Op: np.ndarray | None = None
    total: np.ndarray | None = None

Collision_SN dataclass

Schunk-Nagy collision container combining electron-neutral and electron-ion terms.

Attributes
Collision_en or None

Electron-neutral contributions per species.

Collision_ei or None

Electron-ion contributions per species.

np.ndarray or None

Sum of all Schunk-Nagy contributions (en.total + ei.total).

Source code in hfpytrace/collision.py
@dataclass
class Collision_SN:
    """Schunk-Nagy collision container combining electron-neutral and electron-ion terms.

    Attributes
    ----------
    en : Collision_en or None
        Electron-neutral contributions per species.
    ei : Collision_ei or None
        Electron-ion contributions per species.
    total : np.ndarray or None
        Sum of all Schunk-Nagy contributions (en.total + ei.total).
    """

    en: Collision_en | None = None
    ei: Collision_ei | None = None
    total: np.ndarray | None = None

Collision dataclass

Top-level collision-frequency container.

Attributes
np.ndarray or None

Friedrich-Tonker electron-neutral collision frequency (frac=1.0).

np.ndarray or None

Friedrich-Tonker with classical Coulomb correction (frac=2.5).

np.ndarray or None

Friedrich-Tonker with Maxwell-Boltzmann correction (frac=1.5).

Collision_SN or None

Full Schunk-Nagy (electron-neutral + electron-ion) collision container.

Source code in hfpytrace/collision.py
@dataclass
class Collision:
    """Top-level collision-frequency container.

    Attributes
    ----------
    nu_ft : np.ndarray or None
        Friedrich-Tonker electron-neutral collision frequency (frac=1.0).
    nu_av_cc : np.ndarray or None
        Friedrich-Tonker with classical Coulomb correction (frac=2.5).
    nu_av_mb : np.ndarray or None
        Friedrich-Tonker with Maxwell-Boltzmann correction (frac=1.5).
    nu_sn : Collision_SN or None
        Full Schunk-Nagy (electron-neutral + electron-ion) collision container.
    """

    nu_ft: np.ndarray | None = None
    nu_av_cc: np.ndarray | None = None
    nu_av_mb: np.ndarray | None = None
    nu_sn: Collision_SN | None = None

NRLMSISE2D

Bases: object

Build NRLMSISE-00 neutral background on a 2D (height x path-range) grid.

Inputs: - date: datetime for model evaluation - lats, lons: 1D path coordinates, length Nr - heights_km: 1D heights, length Nh

Outputs are stored in self.msise as arrays of shape (Nh, Nr), with densities in m^-3 (SI, as returned by nrlmsise00) and temperatures in K.

Source code in hfpytrace/collision.py
class NRLMSISE2D(object):
    """
    Build NRLMSISE-00 neutral background on a 2D (height x path-range) grid.

    Inputs:
    - date: datetime for model evaluation
    - lats, lons: 1D path coordinates, length Nr
    - heights_km: 1D heights, length Nh

    Outputs are stored in `self.msise` as arrays of shape (Nh, Nr), with
    densities in m^-3 (SI, as returned by nrlmsise00) and temperatures in K.
    """

    def __init__(
        self,
        date: dt.datetime,
        lats,
        lons,
        heights_km,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ):
        self.date = date
        self.lats = np.asarray(lats, dtype=float)
        self.lons = np.asarray(lons, dtype=float)
        self.heights_km = np.asarray(heights_km, dtype=float)
        self.workers = max(1, int(workers))
        self.update_spaceweather = update_spaceweather
        self.suppress_spaceweather_warning = suppress_spaceweather_warning
        if self.lats.shape != self.lons.shape:
            raise ValueError("lats and lons must have the same shape")
        if self.lats.ndim != 1:
            raise ValueError("lats and lons must be 1D arrays")
        if self.heights_km.ndim != 1:
            raise ValueError("heights_km must be a 1D array")
        self.msise = self.fetch_dataset()

    def fetch_dataset(self) -> dict[str, np.ndarray]:
        try:
            from nrlmsise00.dataset import msise_4d
        except ImportError as exc:
            raise ImportError(
                "nrlmsise00 dataset interface is unavailable. "
                "Install extras: pip install 'nrlmsise00[dataset]'"
            ) from exc

        if self.update_spaceweather:
            try:
                from spaceweather import sw

                sw.update_data()
                logger.info("Updated spaceweather local data files.")
            except Exception as exc:
                logger.warning(f"spaceweather update failed: {exc}")

        nh = self.heights_km.size
        nr = self.lats.size
        out = dict(
            N2=np.zeros((nh, nr), dtype=float),
            O2=np.zeros((nh, nr), dtype=float),
            O=np.zeros((nh, nr), dtype=float),
            H=np.zeros((nh, nr), dtype=float),
            He=np.zeros((nh, nr), dtype=float),
            Tn=np.zeros((nh, nr), dtype=float),
            t_nn=np.zeros((nh, nr), dtype=float),
        )

        logger.info(
            f"Running NRLMSISE-00 for {self.date} on grid Nh={nh}, Nr={nr} "
            f"with workers={self.workers}"
        )
        if self.workers == 1:
            for j, (lat, lon) in enumerate(zip(self.lats, self.lons)):
                with warnings.catch_warnings():
                    if self.suppress_spaceweather_warning:
                        warnings.filterwarnings(
                            "ignore",
                            message="Local data files are older than 30days.*",
                            category=UserWarning,
                        )
                    ds = msise_4d(
                        self.date, self.heights_km, np.array([lat]), np.array([lon])
                    )
                out["N2"][:, j] = ds.variables["N2"].values[0, :, 0, 0]
                out["O2"][:, j] = ds.variables["O2"].values[0, :, 0, 0]
                out["O"][:, j] = ds.variables["O"].values[0, :, 0, 0]
                out["H"][:, j] = ds.variables["H"].values[0, :, 0, 0]
                out["He"][:, j] = ds.variables["He"].values[0, :, 0, 0]
                out["Tn"][:, j] = ds.variables["Talt"].values[0, :, 0, 0]
        else:
            idx_chunks = np.array_split(np.arange(nr, dtype=int), self.workers)
            idx_chunks = [c for c in idx_chunks if c.size > 0]
            logger.info(
                f"Running NRLMSISE2D with process workers={self.workers} "
                f"on {len(idx_chunks)} route chunks"
            )
            with ProcessPoolExecutor(max_workers=self.workers) as ex:
                results = list(
                    ex.map(
                        _msise2d_chunk,
                        [
                            (
                                self.date,
                                self.heights_km,
                                self.lats[idx],
                                self.lons[idx],
                                idx,
                                self.suppress_spaceweather_warning,
                            )
                            for idx in idx_chunks
                        ],
                    )
                )
            for idx, chunk in results:
                out["N2"][:, idx] = chunk["N2"]
                out["O2"][:, idx] = chunk["O2"]
                out["O"][:, idx] = chunk["O"]
                out["H"][:, idx] = chunk["H"]
                out["He"][:, idx] = chunk["He"]
                out["Tn"][:, idx] = chunk["Tn"]

        out["t_nn"] = out["N2"] + out["O2"] + out["O"] + out["H"] + out["He"]
        return out

    def as_collision_kwargs(self) -> dict[str, np.ndarray]:
        """
        Convenience mapping for ComputeCollision neutral inputs.
        """
        return dict(
            Tn=self.msise["Tn"],
            N2=self.msise["N2"],
            O2=self.msise["O2"],
            O=self.msise["O"],
            H=self.msise["H"],
            He=self.msise["He"],
        )

as_collision_kwargs()

Convenience mapping for ComputeCollision neutral inputs.

Source code in hfpytrace/collision.py
def as_collision_kwargs(self) -> dict[str, np.ndarray]:
    """
    Convenience mapping for ComputeCollision neutral inputs.
    """
    return dict(
        Tn=self.msise["Tn"],
        N2=self.msise["N2"],
        O2=self.msise["O2"],
        O=self.msise["O"],
        H=self.msise["H"],
        He=self.msise["He"],
    )

NRLMSISE3D

Bases: object

Build NRLMSISE-00 neutral background on a 3D (lat x lon x height) grid.

This path is vectorized through one msise_4d call and is substantially faster than point-by-point evaluation for large 3D grids.

Source code in hfpytrace/collision.py
class NRLMSISE3D(object):
    """
    Build NRLMSISE-00 neutral background on a 3D (lat x lon x height) grid.

    This path is vectorized through one `msise_4d` call and is substantially
    faster than point-by-point evaluation for large 3D grids.
    """

    def __init__(
        self,
        date: dt.datetime,
        lats,
        lons,
        heights_km,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ):
        self.date = date
        self.lats = np.asarray(lats, dtype=float)
        self.lons = np.asarray(lons, dtype=float)
        self.heights_km = np.asarray(heights_km, dtype=float)
        self.workers = max(1, int(workers))
        self.update_spaceweather = update_spaceweather
        self.suppress_spaceweather_warning = suppress_spaceweather_warning
        if self.lats.ndim != 1 or self.lons.ndim != 1:
            raise ValueError("lats and lons must be 1D arrays for NRLMSISE3D")
        if self.heights_km.ndim != 1:
            raise ValueError("heights_km must be a 1D array for NRLMSISE3D")
        self.msise = self.fetch_dataset()

    def fetch_dataset(self) -> dict[str, np.ndarray]:
        try:
            from nrlmsise00.dataset import msise_4d
        except ImportError as exc:
            raise ImportError(
                "nrlmsise00 dataset interface is unavailable. "
                "Install extras: pip install 'nrlmsise00[dataset]'"
            ) from exc

        if self.update_spaceweather:
            try:
                from spaceweather import sw

                sw.update_data()
                logger.info("Updated spaceweather local data files.")
            except Exception as exc:
                logger.warning(f"spaceweather update failed: {exc}")

        if self.workers == 1:
            with warnings.catch_warnings():
                if self.suppress_spaceweather_warning:
                    warnings.filterwarnings(
                        "ignore",
                        message="Local data files are older than 30days.*",
                        category=UserWarning,
                    )
                ds = msise_4d(self.date, self.heights_km, self.lats, self.lons)

            def _llh(var_name: str) -> np.ndarray:
                arr = ds.variables[var_name].values[0, :, :, :]  # alt, lat, lon
                return np.transpose(arr, (1, 2, 0))  # lat, lon, alt

            out = dict(
                N2=_llh("N2"),
                O2=_llh("O2"),
                O=_llh("O"),
                H=_llh("H"),
                He=_llh("He"),
                Tn=_llh("Talt"),
            )
            out["t_nn"] = out["N2"] + out["O2"] + out["O"] + out["H"] + out["He"]
            return out

        lat_chunks = np.array_split(self.lats, self.workers)
        lat_chunks = [c for c in lat_chunks if c.size > 0]
        logger.info(
            f"Running NRLMSISE3D with process workers={self.workers} "
            f"on {len(lat_chunks)} latitude chunks"
        )
        with ProcessPoolExecutor(max_workers=self.workers) as ex:
            results = list(
                ex.map(
                    _msise3d_chunk,
                    [
                        (
                            self.date,
                            self.heights_km,
                            c,
                            self.lons,
                            self.suppress_spaceweather_warning,
                        )
                        for c in lat_chunks
                    ],
                )
            )

        results.sort(key=lambda x: x[0][0])
        keys = ["N2", "O2", "O", "H", "He", "Tn", "t_nn"]
        out = {k: np.concatenate([r[1][k] for r in results], axis=0) for k in keys}
        return out

    def as_collision_kwargs(self) -> dict[str, np.ndarray]:
        return dict(
            Tn=self.msise["Tn"],
            N2=self.msise["N2"],
            O2=self.msise["O2"],
            O=self.msise["O"],
            H=self.msise["H"],
            He=self.msise["He"],
        )

ComputeCollision

Bases: object

Estimate collision profiles from provided plasma/neutral state arrays.

Expected units: - Temperatures (Te, Ti, Tn): K - Neutral densities (N2, O2, O, H, He): m^-3 (SI; as returned by NRLMSISE-00) - Plasma densities (edens, O2p, Op): cm^-3 (as returned by IRI and RT model profiles)

The SN electron-neutral formulas apply a 1e-6 factor internally to handle the m^-3 neutral inputs. The FT formula uses neutral pressure (m^-3 × k_B × T) in SI throughout. The SN electron-ion formula converts plasma densities to m^-3 internally for both the Debye length and the collision rate.

Source code in hfpytrace/collision.py
class ComputeCollision(object):
    """
    Estimate collision profiles from provided plasma/neutral state arrays.

    Expected units:
    - Temperatures (Te, Ti, Tn): K
    - Neutral densities (N2, O2, O, H, He): m^-3  (SI; as returned by NRLMSISE-00)
    - Plasma densities (edens, O2p, Op): cm^-3  (as returned by IRI and RT model profiles)

    The SN electron-neutral formulas apply a 1e-6 factor internally to handle the
    m^-3 neutral inputs. The FT formula uses neutral pressure (m^-3 × k_B × T) in
    SI throughout. The SN electron-ion formula converts plasma densities to m^-3
    internally for both the Debye length and the collision rate.
    """

    def __init__(
        self,
        Te,
        Ti,
        Tn,
        edens,
        O2p,
        Op,
        N2,
        O2,
        O,
        H,
        He,
        date: dt.datetime | None = None,
    ):
        self.Te = np.asarray(Te, dtype=float)
        self.Ti = np.asarray(Ti, dtype=float)
        self.Tn = np.asarray(Tn, dtype=float)

        self.edens = np.asarray(edens, dtype=float)
        self.O2p = np.asarray(O2p, dtype=float)
        self.Op = np.asarray(Op, dtype=float)

        self.N2 = np.asarray(N2, dtype=float)
        self.O2 = np.asarray(O2, dtype=float)
        self.O = np.asarray(O, dtype=float)
        self.H = np.asarray(H, dtype=float)
        self.He = np.asarray(He, dtype=float)

        self.t_nn = self.N2 + self.O2 + self.O + self.H + self.He
        self.date = date
        if date:
            logger.info(f"Compute collision profiles for {date}")

        self.collision = Collision()
        self.collision.nu_sn = Collision_SN(
            en=Collision_en(),
            ei=Collision_ei(),
            total=np.zeros_like(self.Te),
        )

        self.collision.nu_ft = self.calculate_FT_collision_frequency()
        self.collision.nu_av_cc = self.calculate_FT_collision_frequency(2.5)
        self.collision.nu_av_mb = self.calculate_FT_collision_frequency(1.5)
        self.calculate_SN_en_collision_frequency()
        self.calculate_SN_ei_collision_frequency()
        return

    @classmethod
    def from_nrlmsise(
        cls,
        *,
        date: dt.datetime,
        lats,
        lons,
        heights_km,
        Te,
        Ti,
        edens,
        O2p,
        Op,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ):
        """
        Build collision model using neutral fields from NRLMSISE2D and plasma
        fields from the caller (e.g., IRI).
        """
        bg = NRLMSISE2D(
            date=date,
            lats=lats,
            lons=lons,
            heights_km=heights_km,
            workers=workers,
            update_spaceweather=update_spaceweather,
            suppress_spaceweather_warning=suppress_spaceweather_warning,
        )
        return cls(
            Te=Te,
            Ti=Ti,
            Tn=bg.msise["Tn"],
            edens=edens,
            O2p=O2p,
            Op=Op,
            N2=bg.msise["N2"],
            O2=bg.msise["O2"],
            O=bg.msise["O"],
            H=bg.msise["H"],
            He=bg.msise["He"],
            date=date,
        )

    @classmethod
    def from_nrlmsise_3d(
        cls,
        *,
        date: dt.datetime,
        lats,
        lons,
        heights_km,
        Te,
        Ti,
        edens,
        O2p,
        Op,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ):
        """
        Build collision model using neutral fields from NRLMSISE3D and plasma
        fields on a 3D (lat x lon x height) grid.
        """
        bg = NRLMSISE3D(
            date=date,
            lats=lats,
            lons=lons,
            heights_km=heights_km,
            workers=workers,
            update_spaceweather=update_spaceweather,
            suppress_spaceweather_warning=suppress_spaceweather_warning,
        )
        return cls(
            Te=Te,
            Ti=Ti,
            Tn=bg.msise["Tn"],
            edens=edens,
            O2p=O2p,
            Op=Op,
            N2=bg.msise["N2"],
            O2=bg.msise["O2"],
            O=bg.msise["O"],
            H=bg.msise["H"],
            He=bg.msise["He"],
            date=date,
        )

    def calculate_FT_collision_frequency(self, frac: float = 1.0):
        """
        Friedrich-Tonker electron-neutral collision frequency.

        t_nn is in cm^-3 (SI) need to convert; pressure p = n [m^-3] * k_B [J/K] * T [K] in Pa.
        """
        logger.info(
            f"Compute Friedrich-Tonker electron-neutral collision frequency with a={frac}"
        )
        t_nn = 1e6 * self.t_nn
        Te = np.clip(self.Te, 1.0, None)
        p = t_nn * self.Tn * pconst["boltz"]
        nu = (2.637e6 / np.sqrt(Te) + 4.945e5) * p
        return frac * nu

    def atmospheric_ion_neutral_collision_frequency(self):
        """
        Atmospheric ion-neutral collision frequency from total neutral density.

        Formula constant 3.8e-11 expects density in cm^-3; t_nn is in cm^-3,
        so multiply by 1e-6 to convert (if you think you set it in m^-3):
        ν = 3.8e-11 * n[cm^-3] = 3.8e-17 * n[m^-3].
        """
        return 3.8e-11 * self.t_nn

    def calculate_SN_ei_collision_frequency(self, gamma: float = 0.5572, zi: int = 2):
        """
        Schunk-Nagy electron-ion collision frequency profile.
        """
        logger.warning("Compute Schunk-Nagy electron-ion collision frequency")

        e = pconst["q_e"]
        k = pconst["boltz"]
        me = pconst["m_e"]
        eps0 = pconst["eps0"]
        k_e = 1 / (4 * np.pi * eps0)

        Te = np.clip(self.Te, 1.0, None)
        Ti = np.clip(self.Ti, 1.0, None)
        Ne = np.clip(self.edens, 1e-12, None)

        # Plasma densities (edens, O2p, Op) are in cm^-3; convert to m^-3
        # for the SI Coulomb-logarithm and collision rate formula.
        Ne_m3 = Ne * 1e6

        for key, Ni in {"O2p": self.O2p, "Op": self.Op}.items():
            Ni = np.clip(Ni, 1e-12, None)
            Ni_m3 = Ni * 1e6

            ki2 = 4 * np.pi * Ni_m3 * e**2 * zi**2 * k_e / (k * Ti)
            ke2 = 4 * np.pi * Ne_m3 * e**2 * k_e / (k * Te)

            ki2 = np.clip(ki2, 1e-30, None)
            ke2 = np.clip(ke2, 1e-30, None)

            ke = np.sqrt(ke2)
            lam = np.log(4 * k * Te / (gamma**2 * zi * e**2 * k_e * ke)) - (
                ((ke2 + ki2) / ki2) * np.log(np.sqrt((ke2 + ki2) / ke2))
            )
            lam = np.clip(lam, 1e-6, None)

            nu_ei = (
                4
                * np.sqrt(2 * np.pi)
                * Ni_m3  # SI formula requires m^-3 here
                * (zi * e**2 * k_e) ** 2
                * lam
                / (3 * np.sqrt(me) * (k * Te) ** 1.5)
            )
            setattr(self.collision.nu_sn.ei, key, nu_ei)

        self.collision.nu_sn.ei.total = (
            self.collision.nu_sn.ei.O2p + self.collision.nu_sn.ei.Op
        )
        self.collision.nu_sn.total += self.collision.nu_sn.ei.total

    def calculate_SN_en_collision_frequency(self):
        """
        Schunk-Nagy electron-neutral collision frequency profile.
        """
        logger.warning("Compute Schunk-Nagy electron-neutral collision frequency")

        Te = np.clip(self.Te, 1.0, None)
        sqrt_Te = np.sqrt(Te)

        self.collision.nu_sn.en.N2 = 1e-6 * 2.33e-11 * self.N2 * (1 - 1.12e-4 * Te) * Te
        self.collision.nu_sn.en.O2 = (
            1e-6 * 1.82e-10 * self.O2 * (1 + 3.6e-2 * sqrt_Te) * sqrt_Te
        )
        self.collision.nu_sn.en.O = (
            1e-6 * 8.9e-11 * self.O * (1 + 5.7e-4 * Te) * sqrt_Te
        )
        self.collision.nu_sn.en.He = 1e-6 * 4.6e-10 * self.He * sqrt_Te
        self.collision.nu_sn.en.H = (
            1e-6 * 4.5e-9 * self.H * (1 - 1.35e-4 * Te) * sqrt_Te
        )

        self.collision.nu_sn.en.total = (
            self.collision.nu_sn.en.N2
            + self.collision.nu_sn.en.O2
            + self.collision.nu_sn.en.O
            + self.collision.nu_sn.en.He
            + self.collision.nu_sn.en.H
        )
        self.collision.nu_sn.total += self.collision.nu_sn.en.total

    @staticmethod
    def atmospheric_collision_frequency(ni, nn, T):
        """
        Atmospheric collision profile from ion(electron)/neutral density and temperature.
        """
        na_profile = lambda T, nn: (1.8 * 1e-8 * nn * np.sqrt(T / 300))
        ni_profile = lambda T, ni: (6.1 * 1e-3 * ni * (300 / T) * np.sqrt(300 / T))
        return ni_profile(T, ni) + na_profile(T, nn)

from_nrlmsise(*, date, lats, lons, heights_km, Te, Ti, edens, O2p, Op, workers=1, update_spaceweather=False, suppress_spaceweather_warning=True) classmethod

Build collision model using neutral fields from NRLMSISE2D and plasma fields from the caller (e.g., IRI).

Source code in hfpytrace/collision.py
@classmethod
def from_nrlmsise(
    cls,
    *,
    date: dt.datetime,
    lats,
    lons,
    heights_km,
    Te,
    Ti,
    edens,
    O2p,
    Op,
    workers: int = 1,
    update_spaceweather: bool = False,
    suppress_spaceweather_warning: bool = True,
):
    """
    Build collision model using neutral fields from NRLMSISE2D and plasma
    fields from the caller (e.g., IRI).
    """
    bg = NRLMSISE2D(
        date=date,
        lats=lats,
        lons=lons,
        heights_km=heights_km,
        workers=workers,
        update_spaceweather=update_spaceweather,
        suppress_spaceweather_warning=suppress_spaceweather_warning,
    )
    return cls(
        Te=Te,
        Ti=Ti,
        Tn=bg.msise["Tn"],
        edens=edens,
        O2p=O2p,
        Op=Op,
        N2=bg.msise["N2"],
        O2=bg.msise["O2"],
        O=bg.msise["O"],
        H=bg.msise["H"],
        He=bg.msise["He"],
        date=date,
    )

from_nrlmsise_3d(*, date, lats, lons, heights_km, Te, Ti, edens, O2p, Op, workers=1, update_spaceweather=False, suppress_spaceweather_warning=True) classmethod

Build collision model using neutral fields from NRLMSISE3D and plasma fields on a 3D (lat x lon x height) grid.

Source code in hfpytrace/collision.py
@classmethod
def from_nrlmsise_3d(
    cls,
    *,
    date: dt.datetime,
    lats,
    lons,
    heights_km,
    Te,
    Ti,
    edens,
    O2p,
    Op,
    workers: int = 1,
    update_spaceweather: bool = False,
    suppress_spaceweather_warning: bool = True,
):
    """
    Build collision model using neutral fields from NRLMSISE3D and plasma
    fields on a 3D (lat x lon x height) grid.
    """
    bg = NRLMSISE3D(
        date=date,
        lats=lats,
        lons=lons,
        heights_km=heights_km,
        workers=workers,
        update_spaceweather=update_spaceweather,
        suppress_spaceweather_warning=suppress_spaceweather_warning,
    )
    return cls(
        Te=Te,
        Ti=Ti,
        Tn=bg.msise["Tn"],
        edens=edens,
        O2p=O2p,
        Op=Op,
        N2=bg.msise["N2"],
        O2=bg.msise["O2"],
        O=bg.msise["O"],
        H=bg.msise["H"],
        He=bg.msise["He"],
        date=date,
    )

calculate_FT_collision_frequency(frac=1.0)

Friedrich-Tonker electron-neutral collision frequency.

t_nn is in cm^-3 (SI) need to convert; pressure p = n [m^-3] * k_B [J/K] * T [K] in Pa.

Source code in hfpytrace/collision.py
def calculate_FT_collision_frequency(self, frac: float = 1.0):
    """
    Friedrich-Tonker electron-neutral collision frequency.

    t_nn is in cm^-3 (SI) need to convert; pressure p = n [m^-3] * k_B [J/K] * T [K] in Pa.
    """
    logger.info(
        f"Compute Friedrich-Tonker electron-neutral collision frequency with a={frac}"
    )
    t_nn = 1e6 * self.t_nn
    Te = np.clip(self.Te, 1.0, None)
    p = t_nn * self.Tn * pconst["boltz"]
    nu = (2.637e6 / np.sqrt(Te) + 4.945e5) * p
    return frac * nu

atmospheric_ion_neutral_collision_frequency()

Atmospheric ion-neutral collision frequency from total neutral density.

Formula constant 3.8e-11 expects density in cm^-3; t_nn is in cm^-3, so multiply by 1e-6 to convert (if you think you set it in m^-3): ν = 3.8e-11 * n[cm^-3] = 3.8e-17 * n[m^-3].

Source code in hfpytrace/collision.py
def atmospheric_ion_neutral_collision_frequency(self):
    """
    Atmospheric ion-neutral collision frequency from total neutral density.

    Formula constant 3.8e-11 expects density in cm^-3; t_nn is in cm^-3,
    so multiply by 1e-6 to convert (if you think you set it in m^-3):
    ν = 3.8e-11 * n[cm^-3] = 3.8e-17 * n[m^-3].
    """
    return 3.8e-11 * self.t_nn

calculate_SN_ei_collision_frequency(gamma=0.5572, zi=2)

Schunk-Nagy electron-ion collision frequency profile.

Source code in hfpytrace/collision.py
def calculate_SN_ei_collision_frequency(self, gamma: float = 0.5572, zi: int = 2):
    """
    Schunk-Nagy electron-ion collision frequency profile.
    """
    logger.warning("Compute Schunk-Nagy electron-ion collision frequency")

    e = pconst["q_e"]
    k = pconst["boltz"]
    me = pconst["m_e"]
    eps0 = pconst["eps0"]
    k_e = 1 / (4 * np.pi * eps0)

    Te = np.clip(self.Te, 1.0, None)
    Ti = np.clip(self.Ti, 1.0, None)
    Ne = np.clip(self.edens, 1e-12, None)

    # Plasma densities (edens, O2p, Op) are in cm^-3; convert to m^-3
    # for the SI Coulomb-logarithm and collision rate formula.
    Ne_m3 = Ne * 1e6

    for key, Ni in {"O2p": self.O2p, "Op": self.Op}.items():
        Ni = np.clip(Ni, 1e-12, None)
        Ni_m3 = Ni * 1e6

        ki2 = 4 * np.pi * Ni_m3 * e**2 * zi**2 * k_e / (k * Ti)
        ke2 = 4 * np.pi * Ne_m3 * e**2 * k_e / (k * Te)

        ki2 = np.clip(ki2, 1e-30, None)
        ke2 = np.clip(ke2, 1e-30, None)

        ke = np.sqrt(ke2)
        lam = np.log(4 * k * Te / (gamma**2 * zi * e**2 * k_e * ke)) - (
            ((ke2 + ki2) / ki2) * np.log(np.sqrt((ke2 + ki2) / ke2))
        )
        lam = np.clip(lam, 1e-6, None)

        nu_ei = (
            4
            * np.sqrt(2 * np.pi)
            * Ni_m3  # SI formula requires m^-3 here
            * (zi * e**2 * k_e) ** 2
            * lam
            / (3 * np.sqrt(me) * (k * Te) ** 1.5)
        )
        setattr(self.collision.nu_sn.ei, key, nu_ei)

    self.collision.nu_sn.ei.total = (
        self.collision.nu_sn.ei.O2p + self.collision.nu_sn.ei.Op
    )
    self.collision.nu_sn.total += self.collision.nu_sn.ei.total

calculate_SN_en_collision_frequency()

Schunk-Nagy electron-neutral collision frequency profile.

Source code in hfpytrace/collision.py
def calculate_SN_en_collision_frequency(self):
    """
    Schunk-Nagy electron-neutral collision frequency profile.
    """
    logger.warning("Compute Schunk-Nagy electron-neutral collision frequency")

    Te = np.clip(self.Te, 1.0, None)
    sqrt_Te = np.sqrt(Te)

    self.collision.nu_sn.en.N2 = 1e-6 * 2.33e-11 * self.N2 * (1 - 1.12e-4 * Te) * Te
    self.collision.nu_sn.en.O2 = (
        1e-6 * 1.82e-10 * self.O2 * (1 + 3.6e-2 * sqrt_Te) * sqrt_Te
    )
    self.collision.nu_sn.en.O = (
        1e-6 * 8.9e-11 * self.O * (1 + 5.7e-4 * Te) * sqrt_Te
    )
    self.collision.nu_sn.en.He = 1e-6 * 4.6e-10 * self.He * sqrt_Te
    self.collision.nu_sn.en.H = (
        1e-6 * 4.5e-9 * self.H * (1 - 1.35e-4 * Te) * sqrt_Te
    )

    self.collision.nu_sn.en.total = (
        self.collision.nu_sn.en.N2
        + self.collision.nu_sn.en.O2
        + self.collision.nu_sn.en.O
        + self.collision.nu_sn.en.He
        + self.collision.nu_sn.en.H
    )
    self.collision.nu_sn.total += self.collision.nu_sn.en.total

atmospheric_collision_frequency(ni, nn, T) staticmethod

Atmospheric collision profile from ion(electron)/neutral density and temperature.

Source code in hfpytrace/collision.py
@staticmethod
def atmospheric_collision_frequency(ni, nn, T):
    """
    Atmospheric collision profile from ion(electron)/neutral density and temperature.
    """
    na_profile = lambda T, nn: (1.8 * 1e-8 * nn * np.sqrt(T / 300))
    ni_profile = lambda T, ni: (6.1 * 1e-3 * ni * (300 / T) * np.sqrt(300 / T))
    return ni_profile(T, ni) + na_profile(T, nn)

Source Code

hfpytrace/collision.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
"""Electron collision-frequency models.

Provides NRLMSISE-00-based neutral background models (2D and 3D) and
multiple formulations for computing electron collision frequencies:

* **Friedrich-Tonker (FT)** — pressure-based approximation.
* **Schunk-Nagy (SN) electron-neutral** — species-resolved (N₂, O₂, O, H, He).
* **Schunk-Nagy (SN) electron-ion** — Coulomb logarithm formulation (O₂⁺, O⁺).

The results are stored as a nested :class:`Collision` dataclass, which can
be passed directly to HF ray-tracing engine grid construction.

Requires
--------
nrlmsise00 : for neutral atmosphere profiles (``pip install 'nrlmsise00[dataset]'``).

Classes
-------
Collision_en
    Per-species electron-neutral collision frequency container.
Collision_ei
    Per-species electron-ion collision frequency container.
Collision_SN
    Combined Schunk-Nagy collision container (SN-en + SN-ei + total).
Collision
    Top-level collision dataclass (FT variants + SN).
NRLMSISE2D
    NRLMSISE-00 neutral background on a 2D (height × route) grid.
NRLMSISE3D
    NRLMSISE-00 neutral background on a 3D (lat × lon × height) grid.
ComputeCollision
    Derives all collision profiles from plasma/neutral state arrays.
"""

import datetime as dt
import warnings
from concurrent.futures import ProcessPoolExecutor
from dataclasses import dataclass

import numpy as np
from loguru import logger

from hfpytrace.utils import pconst


@dataclass
class Collision_en:
    """Per-species electron-neutral collision frequency arrays.

    Each field has the same shape as the input plasma/neutral grids.
    Units are Hz (s⁻¹) throughout.

    Attributes
    ----------
    N2, O2, O, H, He : np.ndarray or None
        Species-resolved collision frequency contributions.
    total : np.ndarray or None
        Sum of all species contributions.
    """

    N2: np.ndarray | None = None
    O2: np.ndarray | None = None
    O: np.ndarray | None = None
    H: np.ndarray | None = None
    He: np.ndarray | None = None
    total: np.ndarray | None = None


@dataclass
class Collision_ei:
    """Per-species electron-ion collision frequency arrays.

    Attributes
    ----------
    O2p, Op : np.ndarray or None
        Species-resolved collision frequency contributions.
    total : np.ndarray or None
        Sum of O₂⁺ and O⁺ contributions.
    """

    O2p: np.ndarray | None = None
    Op: np.ndarray | None = None
    total: np.ndarray | None = None


@dataclass
class Collision_SN:
    """Schunk-Nagy collision container combining electron-neutral and electron-ion terms.

    Attributes
    ----------
    en : Collision_en or None
        Electron-neutral contributions per species.
    ei : Collision_ei or None
        Electron-ion contributions per species.
    total : np.ndarray or None
        Sum of all Schunk-Nagy contributions (en.total + ei.total).
    """

    en: Collision_en | None = None
    ei: Collision_ei | None = None
    total: np.ndarray | None = None


@dataclass
class Collision:
    """Top-level collision-frequency container.

    Attributes
    ----------
    nu_ft : np.ndarray or None
        Friedrich-Tonker electron-neutral collision frequency (frac=1.0).
    nu_av_cc : np.ndarray or None
        Friedrich-Tonker with classical Coulomb correction (frac=2.5).
    nu_av_mb : np.ndarray or None
        Friedrich-Tonker with Maxwell-Boltzmann correction (frac=1.5).
    nu_sn : Collision_SN or None
        Full Schunk-Nagy (electron-neutral + electron-ion) collision container.
    """

    nu_ft: np.ndarray | None = None
    nu_av_cc: np.ndarray | None = None
    nu_av_mb: np.ndarray | None = None
    nu_sn: Collision_SN | None = None


def _msise3d_chunk(args):
    """
    Process-safe NRLMSISE chunk evaluator on a latitude subset.
    Returns (lat_chunk, out_dict) with arrays in (lat, lon, alt).
    """
    date, heights_km, lat_chunk, lons, suppress_spaceweather_warning = args
    from nrlmsise00.dataset import msise_4d

    with warnings.catch_warnings():
        if suppress_spaceweather_warning:
            warnings.filterwarnings(
                "ignore",
                message="Local data files are older than 30days.*",
                category=UserWarning,
            )
        ds = msise_4d(date, heights_km, lat_chunk, lons)

    def _llh(var_name: str) -> np.ndarray:
        arr = ds.variables[var_name].values[0, :, :, :]  # alt, lat, lon
        return np.transpose(arr, (1, 2, 0))  # lat, lon, alt

    out = dict(
        N2=_llh("N2"),
        O2=_llh("O2"),
        O=_llh("O"),
        H=_llh("H"),
        He=_llh("He"),
        Tn=_llh("Talt"),
    )
    out["t_nn"] = out["N2"] + out["O2"] + out["O"] + out["H"] + out["He"]
    return np.asarray(lat_chunk, dtype=float), out


def _msise2d_chunk(args):
    """
    Process-safe NRLMSISE evaluator on a route-point subset.
    Returns (idx_chunk, out_dict) where each array is (height, n_chunk).
    """
    (
        date,
        heights_km,
        lats_chunk,
        lons_chunk,
        idx_chunk,
        suppress_spaceweather_warning,
    ) = args
    from nrlmsise00.dataset import msise_4d

    nh = int(np.asarray(heights_km).size)
    nc = int(np.asarray(idx_chunk).size)
    out = dict(
        N2=np.zeros((nh, nc), dtype=float),
        O2=np.zeros((nh, nc), dtype=float),
        O=np.zeros((nh, nc), dtype=float),
        H=np.zeros((nh, nc), dtype=float),
        He=np.zeros((nh, nc), dtype=float),
        Tn=np.zeros((nh, nc), dtype=float),
        t_nn=np.zeros((nh, nc), dtype=float),
    )

    for j, (lat, lon) in enumerate(zip(lats_chunk, lons_chunk)):
        with warnings.catch_warnings():
            if suppress_spaceweather_warning:
                warnings.filterwarnings(
                    "ignore",
                    message="Local data files are older than 30days.*",
                    category=UserWarning,
                )
            ds = msise_4d(date, heights_km, np.array([lat]), np.array([lon]))
        out["N2"][:, j] = ds.variables["N2"].values[0, :, 0, 0]
        out["O2"][:, j] = ds.variables["O2"].values[0, :, 0, 0]
        out["O"][:, j] = ds.variables["O"].values[0, :, 0, 0]
        out["H"][:, j] = ds.variables["H"].values[0, :, 0, 0]
        out["He"][:, j] = ds.variables["He"].values[0, :, 0, 0]
        out["Tn"][:, j] = ds.variables["Talt"].values[0, :, 0, 0]

    out["t_nn"] = out["N2"] + out["O2"] + out["O"] + out["H"] + out["He"]
    return np.asarray(idx_chunk, dtype=int), out


class NRLMSISE2D(object):
    """
    Build NRLMSISE-00 neutral background on a 2D (height x path-range) grid.

    Inputs:
    - date: datetime for model evaluation
    - lats, lons: 1D path coordinates, length Nr
    - heights_km: 1D heights, length Nh

    Outputs are stored in `self.msise` as arrays of shape (Nh, Nr), with
    densities in m^-3 (SI, as returned by nrlmsise00) and temperatures in K.
    """

    def __init__(
        self,
        date: dt.datetime,
        lats,
        lons,
        heights_km,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ):
        self.date = date
        self.lats = np.asarray(lats, dtype=float)
        self.lons = np.asarray(lons, dtype=float)
        self.heights_km = np.asarray(heights_km, dtype=float)
        self.workers = max(1, int(workers))
        self.update_spaceweather = update_spaceweather
        self.suppress_spaceweather_warning = suppress_spaceweather_warning
        if self.lats.shape != self.lons.shape:
            raise ValueError("lats and lons must have the same shape")
        if self.lats.ndim != 1:
            raise ValueError("lats and lons must be 1D arrays")
        if self.heights_km.ndim != 1:
            raise ValueError("heights_km must be a 1D array")
        self.msise = self.fetch_dataset()

    def fetch_dataset(self) -> dict[str, np.ndarray]:
        try:
            from nrlmsise00.dataset import msise_4d
        except ImportError as exc:
            raise ImportError(
                "nrlmsise00 dataset interface is unavailable. "
                "Install extras: pip install 'nrlmsise00[dataset]'"
            ) from exc

        if self.update_spaceweather:
            try:
                from spaceweather import sw

                sw.update_data()
                logger.info("Updated spaceweather local data files.")
            except Exception as exc:
                logger.warning(f"spaceweather update failed: {exc}")

        nh = self.heights_km.size
        nr = self.lats.size
        out = dict(
            N2=np.zeros((nh, nr), dtype=float),
            O2=np.zeros((nh, nr), dtype=float),
            O=np.zeros((nh, nr), dtype=float),
            H=np.zeros((nh, nr), dtype=float),
            He=np.zeros((nh, nr), dtype=float),
            Tn=np.zeros((nh, nr), dtype=float),
            t_nn=np.zeros((nh, nr), dtype=float),
        )

        logger.info(
            f"Running NRLMSISE-00 for {self.date} on grid Nh={nh}, Nr={nr} "
            f"with workers={self.workers}"
        )
        if self.workers == 1:
            for j, (lat, lon) in enumerate(zip(self.lats, self.lons)):
                with warnings.catch_warnings():
                    if self.suppress_spaceweather_warning:
                        warnings.filterwarnings(
                            "ignore",
                            message="Local data files are older than 30days.*",
                            category=UserWarning,
                        )
                    ds = msise_4d(
                        self.date, self.heights_km, np.array([lat]), np.array([lon])
                    )
                out["N2"][:, j] = ds.variables["N2"].values[0, :, 0, 0]
                out["O2"][:, j] = ds.variables["O2"].values[0, :, 0, 0]
                out["O"][:, j] = ds.variables["O"].values[0, :, 0, 0]
                out["H"][:, j] = ds.variables["H"].values[0, :, 0, 0]
                out["He"][:, j] = ds.variables["He"].values[0, :, 0, 0]
                out["Tn"][:, j] = ds.variables["Talt"].values[0, :, 0, 0]
        else:
            idx_chunks = np.array_split(np.arange(nr, dtype=int), self.workers)
            idx_chunks = [c for c in idx_chunks if c.size > 0]
            logger.info(
                f"Running NRLMSISE2D with process workers={self.workers} "
                f"on {len(idx_chunks)} route chunks"
            )
            with ProcessPoolExecutor(max_workers=self.workers) as ex:
                results = list(
                    ex.map(
                        _msise2d_chunk,
                        [
                            (
                                self.date,
                                self.heights_km,
                                self.lats[idx],
                                self.lons[idx],
                                idx,
                                self.suppress_spaceweather_warning,
                            )
                            for idx in idx_chunks
                        ],
                    )
                )
            for idx, chunk in results:
                out["N2"][:, idx] = chunk["N2"]
                out["O2"][:, idx] = chunk["O2"]
                out["O"][:, idx] = chunk["O"]
                out["H"][:, idx] = chunk["H"]
                out["He"][:, idx] = chunk["He"]
                out["Tn"][:, idx] = chunk["Tn"]

        out["t_nn"] = out["N2"] + out["O2"] + out["O"] + out["H"] + out["He"]
        return out

    def as_collision_kwargs(self) -> dict[str, np.ndarray]:
        """
        Convenience mapping for ComputeCollision neutral inputs.
        """
        return dict(
            Tn=self.msise["Tn"],
            N2=self.msise["N2"],
            O2=self.msise["O2"],
            O=self.msise["O"],
            H=self.msise["H"],
            He=self.msise["He"],
        )


class NRLMSISE3D(object):
    """
    Build NRLMSISE-00 neutral background on a 3D (lat x lon x height) grid.

    This path is vectorized through one `msise_4d` call and is substantially
    faster than point-by-point evaluation for large 3D grids.
    """

    def __init__(
        self,
        date: dt.datetime,
        lats,
        lons,
        heights_km,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ):
        self.date = date
        self.lats = np.asarray(lats, dtype=float)
        self.lons = np.asarray(lons, dtype=float)
        self.heights_km = np.asarray(heights_km, dtype=float)
        self.workers = max(1, int(workers))
        self.update_spaceweather = update_spaceweather
        self.suppress_spaceweather_warning = suppress_spaceweather_warning
        if self.lats.ndim != 1 or self.lons.ndim != 1:
            raise ValueError("lats and lons must be 1D arrays for NRLMSISE3D")
        if self.heights_km.ndim != 1:
            raise ValueError("heights_km must be a 1D array for NRLMSISE3D")
        self.msise = self.fetch_dataset()

    def fetch_dataset(self) -> dict[str, np.ndarray]:
        try:
            from nrlmsise00.dataset import msise_4d
        except ImportError as exc:
            raise ImportError(
                "nrlmsise00 dataset interface is unavailable. "
                "Install extras: pip install 'nrlmsise00[dataset]'"
            ) from exc

        if self.update_spaceweather:
            try:
                from spaceweather import sw

                sw.update_data()
                logger.info("Updated spaceweather local data files.")
            except Exception as exc:
                logger.warning(f"spaceweather update failed: {exc}")

        if self.workers == 1:
            with warnings.catch_warnings():
                if self.suppress_spaceweather_warning:
                    warnings.filterwarnings(
                        "ignore",
                        message="Local data files are older than 30days.*",
                        category=UserWarning,
                    )
                ds = msise_4d(self.date, self.heights_km, self.lats, self.lons)

            def _llh(var_name: str) -> np.ndarray:
                arr = ds.variables[var_name].values[0, :, :, :]  # alt, lat, lon
                return np.transpose(arr, (1, 2, 0))  # lat, lon, alt

            out = dict(
                N2=_llh("N2"),
                O2=_llh("O2"),
                O=_llh("O"),
                H=_llh("H"),
                He=_llh("He"),
                Tn=_llh("Talt"),
            )
            out["t_nn"] = out["N2"] + out["O2"] + out["O"] + out["H"] + out["He"]
            return out

        lat_chunks = np.array_split(self.lats, self.workers)
        lat_chunks = [c for c in lat_chunks if c.size > 0]
        logger.info(
            f"Running NRLMSISE3D with process workers={self.workers} "
            f"on {len(lat_chunks)} latitude chunks"
        )
        with ProcessPoolExecutor(max_workers=self.workers) as ex:
            results = list(
                ex.map(
                    _msise3d_chunk,
                    [
                        (
                            self.date,
                            self.heights_km,
                            c,
                            self.lons,
                            self.suppress_spaceweather_warning,
                        )
                        for c in lat_chunks
                    ],
                )
            )

        results.sort(key=lambda x: x[0][0])
        keys = ["N2", "O2", "O", "H", "He", "Tn", "t_nn"]
        out = {k: np.concatenate([r[1][k] for r in results], axis=0) for k in keys}
        return out

    def as_collision_kwargs(self) -> dict[str, np.ndarray]:
        return dict(
            Tn=self.msise["Tn"],
            N2=self.msise["N2"],
            O2=self.msise["O2"],
            O=self.msise["O"],
            H=self.msise["H"],
            He=self.msise["He"],
        )


class ComputeCollision(object):
    """
    Estimate collision profiles from provided plasma/neutral state arrays.

    Expected units:
    - Temperatures (Te, Ti, Tn): K
    - Neutral densities (N2, O2, O, H, He): m^-3  (SI; as returned by NRLMSISE-00)
    - Plasma densities (edens, O2p, Op): cm^-3  (as returned by IRI and RT model profiles)

    The SN electron-neutral formulas apply a 1e-6 factor internally to handle the
    m^-3 neutral inputs. The FT formula uses neutral pressure (m^-3 × k_B × T) in
    SI throughout. The SN electron-ion formula converts plasma densities to m^-3
    internally for both the Debye length and the collision rate.
    """

    def __init__(
        self,
        Te,
        Ti,
        Tn,
        edens,
        O2p,
        Op,
        N2,
        O2,
        O,
        H,
        He,
        date: dt.datetime | None = None,
    ):
        self.Te = np.asarray(Te, dtype=float)
        self.Ti = np.asarray(Ti, dtype=float)
        self.Tn = np.asarray(Tn, dtype=float)

        self.edens = np.asarray(edens, dtype=float)
        self.O2p = np.asarray(O2p, dtype=float)
        self.Op = np.asarray(Op, dtype=float)

        self.N2 = np.asarray(N2, dtype=float)
        self.O2 = np.asarray(O2, dtype=float)
        self.O = np.asarray(O, dtype=float)
        self.H = np.asarray(H, dtype=float)
        self.He = np.asarray(He, dtype=float)

        self.t_nn = self.N2 + self.O2 + self.O + self.H + self.He
        self.date = date
        if date:
            logger.info(f"Compute collision profiles for {date}")

        self.collision = Collision()
        self.collision.nu_sn = Collision_SN(
            en=Collision_en(),
            ei=Collision_ei(),
            total=np.zeros_like(self.Te),
        )

        self.collision.nu_ft = self.calculate_FT_collision_frequency()
        self.collision.nu_av_cc = self.calculate_FT_collision_frequency(2.5)
        self.collision.nu_av_mb = self.calculate_FT_collision_frequency(1.5)
        self.calculate_SN_en_collision_frequency()
        self.calculate_SN_ei_collision_frequency()
        return

    @classmethod
    def from_nrlmsise(
        cls,
        *,
        date: dt.datetime,
        lats,
        lons,
        heights_km,
        Te,
        Ti,
        edens,
        O2p,
        Op,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ):
        """
        Build collision model using neutral fields from NRLMSISE2D and plasma
        fields from the caller (e.g., IRI).
        """
        bg = NRLMSISE2D(
            date=date,
            lats=lats,
            lons=lons,
            heights_km=heights_km,
            workers=workers,
            update_spaceweather=update_spaceweather,
            suppress_spaceweather_warning=suppress_spaceweather_warning,
        )
        return cls(
            Te=Te,
            Ti=Ti,
            Tn=bg.msise["Tn"],
            edens=edens,
            O2p=O2p,
            Op=Op,
            N2=bg.msise["N2"],
            O2=bg.msise["O2"],
            O=bg.msise["O"],
            H=bg.msise["H"],
            He=bg.msise["He"],
            date=date,
        )

    @classmethod
    def from_nrlmsise_3d(
        cls,
        *,
        date: dt.datetime,
        lats,
        lons,
        heights_km,
        Te,
        Ti,
        edens,
        O2p,
        Op,
        workers: int = 1,
        update_spaceweather: bool = False,
        suppress_spaceweather_warning: bool = True,
    ):
        """
        Build collision model using neutral fields from NRLMSISE3D and plasma
        fields on a 3D (lat x lon x height) grid.
        """
        bg = NRLMSISE3D(
            date=date,
            lats=lats,
            lons=lons,
            heights_km=heights_km,
            workers=workers,
            update_spaceweather=update_spaceweather,
            suppress_spaceweather_warning=suppress_spaceweather_warning,
        )
        return cls(
            Te=Te,
            Ti=Ti,
            Tn=bg.msise["Tn"],
            edens=edens,
            O2p=O2p,
            Op=Op,
            N2=bg.msise["N2"],
            O2=bg.msise["O2"],
            O=bg.msise["O"],
            H=bg.msise["H"],
            He=bg.msise["He"],
            date=date,
        )

    def calculate_FT_collision_frequency(self, frac: float = 1.0):
        """
        Friedrich-Tonker electron-neutral collision frequency.

        t_nn is in cm^-3 (SI) need to convert; pressure p = n [m^-3] * k_B [J/K] * T [K] in Pa.
        """
        logger.info(
            f"Compute Friedrich-Tonker electron-neutral collision frequency with a={frac}"
        )
        t_nn = 1e6 * self.t_nn
        Te = np.clip(self.Te, 1.0, None)
        p = t_nn * self.Tn * pconst["boltz"]
        nu = (2.637e6 / np.sqrt(Te) + 4.945e5) * p
        return frac * nu

    def atmospheric_ion_neutral_collision_frequency(self):
        """
        Atmospheric ion-neutral collision frequency from total neutral density.

        Formula constant 3.8e-11 expects density in cm^-3; t_nn is in cm^-3,
        so multiply by 1e-6 to convert (if you think you set it in m^-3):
        ν = 3.8e-11 * n[cm^-3] = 3.8e-17 * n[m^-3].
        """
        return 3.8e-11 * self.t_nn

    def calculate_SN_ei_collision_frequency(self, gamma: float = 0.5572, zi: int = 2):
        """
        Schunk-Nagy electron-ion collision frequency profile.
        """
        logger.warning("Compute Schunk-Nagy electron-ion collision frequency")

        e = pconst["q_e"]
        k = pconst["boltz"]
        me = pconst["m_e"]
        eps0 = pconst["eps0"]
        k_e = 1 / (4 * np.pi * eps0)

        Te = np.clip(self.Te, 1.0, None)
        Ti = np.clip(self.Ti, 1.0, None)
        Ne = np.clip(self.edens, 1e-12, None)

        # Plasma densities (edens, O2p, Op) are in cm^-3; convert to m^-3
        # for the SI Coulomb-logarithm and collision rate formula.
        Ne_m3 = Ne * 1e6

        for key, Ni in {"O2p": self.O2p, "Op": self.Op}.items():
            Ni = np.clip(Ni, 1e-12, None)
            Ni_m3 = Ni * 1e6

            ki2 = 4 * np.pi * Ni_m3 * e**2 * zi**2 * k_e / (k * Ti)
            ke2 = 4 * np.pi * Ne_m3 * e**2 * k_e / (k * Te)

            ki2 = np.clip(ki2, 1e-30, None)
            ke2 = np.clip(ke2, 1e-30, None)

            ke = np.sqrt(ke2)
            lam = np.log(4 * k * Te / (gamma**2 * zi * e**2 * k_e * ke)) - (
                ((ke2 + ki2) / ki2) * np.log(np.sqrt((ke2 + ki2) / ke2))
            )
            lam = np.clip(lam, 1e-6, None)

            nu_ei = (
                4
                * np.sqrt(2 * np.pi)
                * Ni_m3  # SI formula requires m^-3 here
                * (zi * e**2 * k_e) ** 2
                * lam
                / (3 * np.sqrt(me) * (k * Te) ** 1.5)
            )
            setattr(self.collision.nu_sn.ei, key, nu_ei)

        self.collision.nu_sn.ei.total = (
            self.collision.nu_sn.ei.O2p + self.collision.nu_sn.ei.Op
        )
        self.collision.nu_sn.total += self.collision.nu_sn.ei.total

    def calculate_SN_en_collision_frequency(self):
        """
        Schunk-Nagy electron-neutral collision frequency profile.
        """
        logger.warning("Compute Schunk-Nagy electron-neutral collision frequency")

        Te = np.clip(self.Te, 1.0, None)
        sqrt_Te = np.sqrt(Te)

        self.collision.nu_sn.en.N2 = 1e-6 * 2.33e-11 * self.N2 * (1 - 1.12e-4 * Te) * Te
        self.collision.nu_sn.en.O2 = (
            1e-6 * 1.82e-10 * self.O2 * (1 + 3.6e-2 * sqrt_Te) * sqrt_Te
        )
        self.collision.nu_sn.en.O = (
            1e-6 * 8.9e-11 * self.O * (1 + 5.7e-4 * Te) * sqrt_Te
        )
        self.collision.nu_sn.en.He = 1e-6 * 4.6e-10 * self.He * sqrt_Te
        self.collision.nu_sn.en.H = (
            1e-6 * 4.5e-9 * self.H * (1 - 1.35e-4 * Te) * sqrt_Te
        )

        self.collision.nu_sn.en.total = (
            self.collision.nu_sn.en.N2
            + self.collision.nu_sn.en.O2
            + self.collision.nu_sn.en.O
            + self.collision.nu_sn.en.He
            + self.collision.nu_sn.en.H
        )
        self.collision.nu_sn.total += self.collision.nu_sn.en.total

    @staticmethod
    def atmospheric_collision_frequency(ni, nn, T):
        """
        Atmospheric collision profile from ion(electron)/neutral density and temperature.
        """
        na_profile = lambda T, nn: (1.8 * 1e-8 * nn * np.sqrt(T / 300))
        ni_profile = lambda T, ni: (6.1 * 1e-3 * ni * (300 / T) * np.sqrt(300 / T))
        return ni_profile(T, ni) + na_profile(T, nn)