Skip to content

neurospatial.stats

stats

Statistical methods.

This module provides general-purpose statistical utilities used across encoding, decoding, and behavior analysis. Shuffles of rate maps and posteriors for replay tests live in :mod:neurospatial.replay.

Submodules

circular : Circular statistics, Rayleigh test shuffle : Temporal, trial and spike-train shuffles; Monte Carlo p-values surrogates : Surrogate data generation

Imports

from neurospatial.stats import rayleigh_test, circular_mean from neurospatial.stats import shuffle_time_bins, shuffle_pvalue from neurospatial.stats import generate_poisson_surrogates, generate_jittered_spikes from neurospatial.stats import circular_basis from neurospatial.stats import ShuffleTestResult from neurospatial.stats import generate_inhomogeneous_poisson_surrogates

Classes

CircularBasisResult dataclass

CircularBasisResult(angles: NDArray[float64])

Bases: ReadOnlyArraysMixin

Result from circular_basis() function.

Holds the angles of a circular predictor; the sin/cos components for a GLM design matrix are derived from them.

Attributes:

Name Type Description
angles (ndarray, shape(n_samples))

Angles in radians (converted from degrees if angle_unit='deg').

Properties

sin_component : ndarray, shape (n_samples,) Sine of angles: sin(angles). cos_component : ndarray, shape (n_samples,) Cosine of angles: cos(angles). design_matrix : ndarray, shape (n_samples, 2) Design matrix with columns [sin_component, cos_component].

Examples:

>>> import numpy as np
>>> from neurospatial.stats.circular import circular_basis
>>> angles = np.linspace(0, 2 * np.pi, 100, endpoint=False)
>>> result = circular_basis(angles)
>>> result.design_matrix.shape
(100, 2)
Attributes
sin_component property
sin_component: NDArray[float64]

Sine of the angles, shape (n_samples,).

cos_component property
cos_component: NDArray[float64]

Cosine of the angles, shape (n_samples,).

design_matrix property
design_matrix: NDArray[float64]

Return design matrix with columns [sin_component, cos_component].

Returns:

Type Description
(ndarray, shape(n_samples, 2))

Design matrix suitable for GLM.

ShuffleTestResult dataclass

ShuffleTestResult(
    observed_score: float,
    null_scores: NDArray[float64],
    p_value: float,
    shuffle_type: str,
    alternative: Literal["greater", "less", "two-sided"] = "greater",
    statistic: str | None = None,
    statistic_units: str | None = None,
)

Bases: ResultMixin, ReadOnlyArraysMixin

Result container for shuffle-based significance testing.

A frozen dataclass containing the observed score, null distribution, and computed statistics (p-value, z-score) from a shuffle test. Build one from scores with :meth:from_null.

Parameters:

Name Type Description Default
observed_score float

The score computed from the original (non-shuffled) data.

required
null_scores (NDArray[float64], shape(n_shuffles))

Score of each shuffle, forming the null distribution. NaN marks a shuffle whose score is undefined. Stored as a read-only float64 copy.

required
p_value float

Monte Carlo p-value (k + 1) / (n + 1) in (0, 1], where k counts the defined null scores at least as extreme as observed in the direction of alternative and n is n_shuffles_used. NaN when the test is undefined: a non-finite observed score or no defined null score.

required
shuffle_type str

Name of the shuffle method used (e.g., "time_bins", "cell_identity").

required
alternative ('greater', 'less', 'two-sided')

Direction of the test the p-value belongs to.

"greater"
statistic str or None

Name of the score, such as "spatial_information"; None when unnamed.

None
statistic_units str or None

Unit of the score, such as "bits/spike"; "" for a dimensionless score, None when unknown.

None

Attributes:

Name Type Description
z_score float

Standard score of the observed score against the null scores, from :func:shuffle_zscore: (observed - mean(null)) / std(null) over the defined null scores. NaN if they have zero variance, fewer than two are defined, or a null score is infinite.

n_shuffles int

Number of shuffles performed, len(null_scores), including any with an undefined score.

n_shuffles_used int

Shuffles with a defined (non-NaN) score, the n of the p-value.

Raises:

Type Description
ValueError

If null_scores is not 1-D, p_value is neither in (0, 1] nor NaN, or alternative is unknown.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.shuffle import ShuffleTestResult
>>> result = ShuffleTestResult.from_null(
...     5.0, np.array([1.0, 2.0, 3.0, 4.0]), shuffle_type="time_bins"
... )
>>> result.p_value
0.2
>>> result.is_significant()
False
>>> result.is_significant(alpha=0.25)
True
See Also

shuffle_pvalue : Compute Monte Carlo p-value from null distribution. shuffle_zscore : Compute z-score from null distribution.

Attributes
z_score property
z_score: float

Standard score of the observed score against the null scores.

n_shuffles property
n_shuffles: int

Shuffles performed, len(null_scores), including undefined ones.

n_shuffles_used property
n_shuffles_used: int

Shuffles with a defined (non-NaN) score: the n of the p-value.

Functions
from_null classmethod
from_null(
    observed_score: float,
    null_scores: NDArray[float64],
    *,
    shuffle_type: str,
    alternative: Literal["greater", "less", "two-sided"] = "greater",
    statistic: str | None = None,
    statistic_units: str | None = None,
) -> ShuffleTestResult

Test an observed score against the scores of its shuffles.

Parameters:

Name Type Description Default
observed_score float

The score of the original (non-shuffled) data.

required
null_scores (NDArray[float64], shape(n_shuffles))

The score of each shuffle. NaN scores (shuffles whose score is undefined) are left out of the p-value and z-score; n_shuffles_used counts the rest, so a value below n_shuffles means some shuffles were undefined.

required
shuffle_type str

Name of the shuffle method (e.g., "time_bins", "cell_identity").

required
alternative ('greater', 'less', 'two-sided')

Direction of the test, as for :func:shuffle_pvalue.

"greater"
statistic str or None

Name of the score.

None
statistic_units str or None

Unit of the score; "" for a dimensionless score.

None

Returns:

Type Description
ShuffleTestResult

The p-value of :func:shuffle_pvalue and the z-score of :func:shuffle_zscore, over the defined null scores.

Raises:

Type Description
ValueError

If observed_score is not finite, no null score is defined, alternative is unknown, or null_scores is not 1-D.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.shuffle import ShuffleTestResult
>>> result = ShuffleTestResult.from_null(
...     10.0, np.array([1.0, 2.0, 3.0, 4.0]), shuffle_type="time_bins"
... )
>>> result.p_value, result.n_shuffles
(0.2, 4)
Source code in src/neurospatial/stats/shuffle.py
@classmethod
def from_null(
    cls,
    observed_score: float,
    null_scores: NDArray[np.float64],
    *,
    shuffle_type: str,
    alternative: Literal["greater", "less", "two-sided"] = "greater",
    statistic: str | None = None,
    statistic_units: str | None = None,
) -> ShuffleTestResult:
    """Test an observed score against the scores of its shuffles.

    Parameters
    ----------
    observed_score : float
        The score of the original (non-shuffled) data.
    null_scores : NDArray[np.float64], shape (n_shuffles,)
        The score of each shuffle. NaN scores (shuffles whose score is
        undefined) are left out of the p-value and z-score;
        ``n_shuffles_used`` counts the rest, so a value below
        ``n_shuffles`` means some shuffles were undefined.
    shuffle_type : str
        Name of the shuffle method (e.g., "time_bins", "cell_identity").
    alternative : {"greater", "less", "two-sided"}, default="greater"
        Direction of the test, as for :func:`shuffle_pvalue`.
    statistic : str or None, default=None
        Name of the score.
    statistic_units : str or None, default=None
        Unit of the score; ``""`` for a dimensionless score.

    Returns
    -------
    ShuffleTestResult
        The p-value of :func:`shuffle_pvalue` and the z-score of
        :func:`shuffle_zscore`, over the defined null scores.

    Raises
    ------
    ValueError
        If ``observed_score`` is not finite, no null score is defined,
        ``alternative`` is unknown, or ``null_scores`` is not 1-D.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.shuffle import ShuffleTestResult
    >>> result = ShuffleTestResult.from_null(
    ...     10.0, np.array([1.0, 2.0, 3.0, 4.0]), shuffle_type="time_bins"
    ... )
    >>> result.p_value, result.n_shuffles
    (0.2, 4)
    """
    null = np.asarray(null_scores, dtype=np.float64)
    undefined = np.isnan(null)
    defined = null[~undefined]
    p_value = shuffle_pvalue(observed_score, defined, alternative=alternative)
    return cls(
        observed_score=observed_score,
        null_scores=null,
        p_value=p_value,
        shuffle_type=shuffle_type,
        alternative=alternative,
        statistic=statistic,
        statistic_units=statistic_units,
    )
is_significant
is_significant(alpha: float = 0.05) -> bool

Return True if p_value < alpha.

Parameters:

Name Type Description Default
alpha float

Significance level.

0.05

Returns:

Type Description
bool

True if the result is significant at alpha; False when the p-value is NaN.

Source code in src/neurospatial/stats/shuffle.py
def is_significant(self, alpha: float = 0.05) -> bool:
    """Return True if ``p_value < alpha``.

    Parameters
    ----------
    alpha : float, default=0.05
        Significance level.

    Returns
    -------
    bool
        True if the result is significant at ``alpha``; False when the
        p-value is NaN.
    """
    return bool(self.p_value < alpha)
summary
summary() -> dict[str, Any]

Flat dict of scalar headline metrics for this result.

Source code in src/neurospatial/stats/shuffle.py
def summary(self) -> dict[str, Any]:
    """Flat dict of scalar headline metrics for this result."""
    return {
        "statistic": self.statistic,
        "statistic_units": self.statistic_units,
        "observed_score": float(self.observed_score),
        "p_value": float(self.p_value),
        "z_score": float(self.z_score),
        "alternative": self.alternative,
        "shuffle_type": self.shuffle_type,
        "n_shuffles": self.n_shuffles,
        "n_shuffles_used": self.n_shuffles_used,
    }
plot
plot(*, ax: Axes | None = None, **kwargs: Any) -> Axes

Plot the null distribution with observed score.

Creates a histogram of the finite null scores with a vertical line showing the observed score and annotations for the p-value, its alternative and the z-score. Undefined (NaN) and infinite null scores cannot be drawn; the title gives how many are left out.

Parameters:

Name Type Description Default
ax Axes | None

Axes to plot on. If None, creates a new figure.

None
**kwargs Any

Additional keyword arguments passed to matplotlib's hist().

{}

Returns:

Type Description
Axes

The axes containing the plot.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.shuffle import ShuffleTestResult
>>> result = ShuffleTestResult.from_null(
...     5.0,
...     np.random.default_rng(42).normal(2.0, 1.0, 100),
...     shuffle_type="time_bins",
... )
>>> ax = result.plot()
Source code in src/neurospatial/stats/shuffle.py
def plot(self, *, ax: Axes | None = None, **kwargs: Any) -> Axes:
    """Plot the null distribution with observed score.

    Creates a histogram of the finite null scores with a vertical line
    showing the observed score and annotations for the p-value, its alternative
    and the z-score. Undefined (NaN) and infinite null scores cannot be
    drawn; the title gives how many are left out.

    Parameters
    ----------
    ax : matplotlib.axes.Axes | None, default=None
        Axes to plot on. If None, creates a new figure.
    **kwargs
        Additional keyword arguments passed to matplotlib's hist().

    Returns
    -------
    matplotlib.axes.Axes
        The axes containing the plot.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.shuffle import ShuffleTestResult

    >>> result = ShuffleTestResult.from_null(
    ...     5.0,
    ...     np.random.default_rng(42).normal(2.0, 1.0, 100),
    ...     shuffle_type="time_bins",
    ... )
    >>> ax = result.plot()  # doctest: +SKIP
    """
    import matplotlib.pyplot as plt

    if ax is None:
        _, ax = plt.subplots()

    # Default histogram settings
    hist_kwargs = {
        "bins": 30,
        "alpha": 0.7,
        "color": "steelblue",
        "edgecolor": "white",
    }
    hist_kwargs.update(kwargs)

    finite = self.null_scores[np.isfinite(self.null_scores)]
    ax.hist(finite, **hist_kwargs)  # type: ignore[arg-type]

    # Add observed score line
    ax.axvline(
        self.observed_score,
        color="red",
        linestyle="--",
        linewidth=2,
        label=f"Observed: {self.observed_score:.3f}",
    )

    # Add annotations
    sig_marker = "*" if self.is_significant() else ""
    n_hidden = self.n_shuffles - finite.size
    hidden = f", {n_hidden} non-finite not drawn" if n_hidden else ""
    ax.set_title(
        f"Shuffle Test ({self.shuffle_type}, {self.alternative})\n"
        f"p = {self.p_value:.4f}{sig_marker}, z = {self.z_score:.2f}{hidden}"
    )
    label = "Score" if self.statistic is None else self.statistic
    if self.statistic_units:
        label = f"{label} ({self.statistic_units})"
    ax.set_xlabel(label)
    ax.set_ylabel("Count")
    ax.legend()

    return ax

Functions

circular_basis

circular_basis(
    angles: NDArray[float64], *, angle_unit: Literal["rad", "deg"] = "rad"
) -> CircularBasisResult

Compute sine/cosine basis functions for circular variables.

Creates a design matrix for use in GLMs (Generalized Linear Models) where the sin and cos components capture circular modulation. This is the standard approach for including circular predictors in regression models.

Parameters:

Name Type Description Default
angles (array, shape(n_samples))

Circular variable, one value per GLM sample (e.g., per time bin). Common use cases:

  • Head direction: Animal's facing direction
  • Theta phase: LFP phase in each time bin
  • Running direction: Direction of movement
  • Time of day: Circadian phase
required
angle_unit ('rad', 'deg')

Unit of input angles. Use 'deg' for angles recorded in degrees.

'rad'

Returns:

Type Description
CircularBasisResult

Result object containing:

  • angles: angles in radians
  • sin_component: sin(angles)
  • cos_component: cos(angles)
  • design_matrix property: (n_samples, 2) array for GLM

Raises:

Type Description
ValueError

If angle_unit is unknown, or angles is not a 1-D array of finite values.

See Also

circular_basis_metrics : Compute amplitude/phase from GLM coefficients. is_modulated : Quick significance test for circular modulation. plot_circular_basis_tuning : Visualize fitted tuning curve.

Notes

Why sin/cos basis?

For a circular predictor θ, using sin(θ) and cos(θ) as separate predictors allows the model to capture any phase and amplitude of circular modulation. The fitted coefficients (β_sin, β_cos) can be converted to:

  • Amplitude: sqrt(β_sin² + β_cos²) — modulation strength
  • Phase: atan2(β_sin, β_cos) — preferred direction/phase

GLM vs. Binned Tuning Curves:

  • Binned: Non-parametric, intuitive, good for visualization. Requires many spikes per bin.
  • GLM (circular_basis): Parametric, statistically rigorous, can include covariates. Better for low spike counts.

Examples:

Head direction tuning (GLM approach):

>>> import numpy as np
>>> from neurospatial.stats.circular import circular_basis
>>> # Head direction in each time bin (in degrees)
>>> headings = np.array([45, 50, 48, 52, 180, 185, 170])  # degrees
>>> result = circular_basis(headings, angle_unit="deg")
>>> result.design_matrix.shape
(7, 2)

Theta phase modulation:

>>> # LFP phase in each time bin (in radians)
>>> theta_phases = np.random.default_rng(0).uniform(0, 2 * np.pi, 100)
>>> result = circular_basis(theta_phases)  # angle_unit='rad' is default
>>> X = result.design_matrix
>>> # Now fit a Poisson GLM of the spike counts per time bin, e.g.
>>> # sm.GLM(spike_counts, sm.add_constant(X), family=sm.families.Poisson())
Source code in src/neurospatial/stats/circular.py
def circular_basis(
    angles: NDArray[np.float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
) -> CircularBasisResult:
    """
    Compute sine/cosine basis functions for circular variables.

    Creates a design matrix for use in GLMs (Generalized Linear Models) where
    the sin and cos components capture circular modulation. This is the standard
    approach for including circular predictors in regression models.

    Parameters
    ----------
    angles : array, shape (n_samples,)
        Circular variable, one value per GLM sample (e.g., per time bin).
        Common use cases:

        - **Head direction**: Animal's facing direction
        - **Theta phase**: LFP phase in each time bin
        - **Running direction**: Direction of movement
        - **Time of day**: Circadian phase

    angle_unit : {'rad', 'deg'}, default='rad'
        Unit of input angles. Use ``'deg'`` for angles recorded in degrees.

    Returns
    -------
    CircularBasisResult
        Result object containing:

        - angles: angles in radians
        - sin_component: sin(angles)
        - cos_component: cos(angles)
        - design_matrix property: (n_samples, 2) array for GLM

    Raises
    ------
    ValueError
        If ``angle_unit`` is unknown, or ``angles`` is not a 1-D array of
        finite values.

    See Also
    --------
    circular_basis_metrics : Compute amplitude/phase from GLM coefficients.
    is_modulated : Quick significance test for circular modulation.
    plot_circular_basis_tuning : Visualize fitted tuning curve.

    Notes
    -----
    **Why sin/cos basis?**

    For a circular predictor θ, using sin(θ) and cos(θ) as separate
    predictors allows the model to capture any phase and amplitude of circular
    modulation. The fitted coefficients (β_sin, β_cos) can be converted to:

    - Amplitude: sqrt(β_sin² + β_cos²) — modulation strength
    - Phase: atan2(β_sin, β_cos) — preferred direction/phase

    **GLM vs. Binned Tuning Curves**:

    - **Binned**: Non-parametric, intuitive, good for visualization.
      Requires many spikes per bin.
    - **GLM** (``circular_basis``): Parametric, statistically rigorous, can
      include covariates. Better for low spike counts.

    Examples
    --------
    **Head direction tuning (GLM approach)**:

    >>> import numpy as np
    >>> from neurospatial.stats.circular import circular_basis
    >>> # Head direction in each time bin (in degrees)
    >>> headings = np.array([45, 50, 48, 52, 180, 185, 170])  # degrees
    >>> result = circular_basis(headings, angle_unit="deg")
    >>> result.design_matrix.shape
    (7, 2)

    **Theta phase modulation**:

    >>> # LFP phase in each time bin (in radians)
    >>> theta_phases = np.random.default_rng(0).uniform(0, 2 * np.pi, 100)
    >>> result = circular_basis(theta_phases)  # angle_unit='rad' is default
    >>> X = result.design_matrix
    >>> # Now fit a Poisson GLM of the spike counts per time bin, e.g.
    >>> # sm.GLM(spike_counts, sm.add_constant(X), family=sm.families.Poisson())
    """
    angles = np.asarray(angles, dtype=np.float64)
    if angles.ndim != 1 or not np.all(np.isfinite(angles)):
        msg = (
            f"angles must be a 1-D array of finite values, got shape "
            f"{angles.shape} with {int(np.sum(~np.isfinite(angles)))} "
            f"non-finite value(s).\n"
            f"Fix: pass one angle per GLM sample, and drop the samples (with "
            f"their spike counts) where the angle is missing."
        )
        raise ValueError(msg)
    return CircularBasisResult(angles=to_radians(angles, angle_unit))

circular_basis_metrics

circular_basis_metrics(
    beta_sin: float, beta_cos: float, cov_matrix: NDArray[float64] | None = None
) -> tuple[float, float, float]

Compute amplitude, phase, and p-value from GLM coefficients.

Given fitted coefficients for sin and cos basis functions, compute: - Amplitude (strength of modulation) - Phase (preferred angle) - P-value (statistical significance via Wald test)

Parameters:

Name Type Description Default
beta_sin float

Coefficient for sin(angle) from fitted GLM.

required
beta_cos float

Coefficient for cos(angle) from fitted GLM.

required
cov_matrix (ndarray, shape(2, 2))

Covariance matrix for [beta_sin, beta_cos] from GLM fit. If provided, computes p-value via Wald test.

None

Returns:

Name Type Description
amplitude float

Modulation amplitude: sqrt(beta_sin^2 + beta_cos^2). Larger values indicate stronger circular modulation.

phase float

Preferred phase angle in radians, range [-π, π]. Computed as atan2(beta_sin, beta_cos).

pvalue float

Wald-test p-value for H0: amplitude = 0 (no modulation). NaN if cov_matrix is not provided or is singular.

Raises:

Type Description
ValueError

If cov_matrix is not 2x2, is not finite, or is not symmetric positive semi-definite, or the coefficients are not finite.

See Also

circular_basis : Create design matrix for GLM.

Notes

Interpretation (log link, as in a Poisson GLM):

  • the rate peaks at phase and is lowest opposite it; the peak-to-trough rate ratio is exp(2 * amplitude), so amplitude 0.2 is a 1.49-fold and 0.5 a 2.7-fold modulation
  • pvalue < 0.05 indicates statistically significant modulation

Calibration. The Wald statistic beta' cov^-1 beta is compared with chi-squared on 2 degrees of freedom, a large-sample test. With a Poisson GLM fit by statsmodels to untuned Poisson counts at uniform random angles (2000 cells per row), pvalue < 0.05 occurred in 5.0% of cells with 100 spikes and 5.4% with 1000, but in 3.6-3.7% of cells with 20 to 50 spikes, where the test is conservative. A fitted cell with a planted modulation of amplitude 0.3 and about 400 spikes had the true (beta_sin, beta_cos) inside its 95% Wald ellipse in 94.5% of 2000 fits. amplitude is biased upward when the modulation is weak compared with its standard error: a true 0.1 was estimated as 0.13 on average.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.circular import circular_basis_metrics
>>> # After fitting GLM with circular basis
>>> beta_sin, beta_cos = 0.5, 0.3
>>> cov = np.array([[0.01, 0.001], [0.001, 0.01]])
>>> amplitude, phase, pval = circular_basis_metrics(beta_sin, beta_cos, cov)
>>> print(f"Amplitude: {amplitude:.2f}, Phase: {np.degrees(phase):.1f}°")
Amplitude: 0.58, Phase: 59.0°
Source code in src/neurospatial/stats/circular.py
def circular_basis_metrics(
    beta_sin: float,
    beta_cos: float,
    cov_matrix: NDArray[np.float64] | None = None,
) -> tuple[float, float, float]:
    """
    Compute amplitude, phase, and p-value from GLM coefficients.

    Given fitted coefficients for sin and cos basis functions, compute:
    - Amplitude (strength of modulation)
    - Phase (preferred angle)
    - P-value (statistical significance via Wald test)

    Parameters
    ----------
    beta_sin : float
        Coefficient for sin(angle) from fitted GLM.
    beta_cos : float
        Coefficient for cos(angle) from fitted GLM.
    cov_matrix : ndarray, shape (2, 2), optional
        Covariance matrix for [beta_sin, beta_cos] from GLM fit.
        If provided, computes p-value via Wald test.

    Returns
    -------
    amplitude : float
        Modulation amplitude: sqrt(beta_sin^2 + beta_cos^2).
        Larger values indicate stronger circular modulation.
    phase : float
        Preferred phase angle in radians, range [-π, π].
        Computed as atan2(beta_sin, beta_cos).
    pvalue : float
        Wald-test p-value for H0: amplitude = 0 (no modulation). NaN if
        ``cov_matrix`` is not provided or is singular.

    Raises
    ------
    ValueError
        If ``cov_matrix`` is not 2x2, is not finite, or is not symmetric
        positive semi-definite, or the coefficients are not finite.

    See Also
    --------
    circular_basis : Create design matrix for GLM.

    Notes
    -----
    **Interpretation** (log link, as in a Poisson GLM):

    - the rate peaks at ``phase`` and is lowest opposite it; the
      peak-to-trough rate ratio is ``exp(2 * amplitude)``, so amplitude 0.2
      is a 1.49-fold and 0.5 a 2.7-fold modulation
    - pvalue < 0.05 indicates statistically significant modulation

    **Calibration.** The Wald statistic ``beta' cov^-1 beta`` is compared
    with chi-squared on 2 degrees of freedom, a large-sample test. With a
    Poisson GLM fit by statsmodels to untuned Poisson counts at uniform
    random angles (2000 cells per row), ``pvalue < 0.05`` occurred in 5.0%
    of cells with 100 spikes and 5.4% with 1000, but in 3.6-3.7% of cells
    with 20 to 50 spikes, where the test is conservative. A fitted cell with
    a planted modulation of amplitude 0.3 and about 400 spikes had the true
    ``(beta_sin, beta_cos)`` inside its 95% Wald ellipse in 94.5% of 2000
    fits. ``amplitude`` is biased upward when the modulation is weak
    compared with its standard error: a true 0.1 was estimated as 0.13 on
    average.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.circular import circular_basis_metrics
    >>> # After fitting GLM with circular basis
    >>> beta_sin, beta_cos = 0.5, 0.3
    >>> cov = np.array([[0.01, 0.001], [0.001, 0.01]])
    >>> amplitude, phase, pval = circular_basis_metrics(beta_sin, beta_cos, cov)
    >>> print(f"Amplitude: {amplitude:.2f}, Phase: {np.degrees(phase):.1f}°")
    Amplitude: 0.58, Phase: 59.0°
    """
    amplitude = float(np.sqrt(beta_sin**2 + beta_cos**2))
    phase = float(np.arctan2(beta_sin, beta_cos))
    pvalue = (
        np.nan
        if cov_matrix is None
        else _wald_test_magnitude(beta_sin, beta_cos, _validated_cov(cov_matrix))
    )
    return amplitude, phase, pvalue

circular_circular_correlation

circular_circular_correlation(
    angles_a: NDArray[float64],
    angles_b: NDArray[float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
) -> tuple[float, float]

Circular-circular correlation coefficient.

Computes the Jammalamadaka & Sarma (1988) circular correlation coefficient between two circular variables, as CircStat's circ_corrcc.

Parameters:

Name Type Description Default
angles_a ndarray of shape (n_samples,)

First circular variable in radians or degrees.

required
angles_b ndarray of shape (n_samples,)

Second circular variable in radians or degrees. Must have same length as angles_a. A pair with a NaN in either array is dropped with a warning and the correlation uses the remaining pairs.

required
angle_unit ('rad', 'deg')

Unit of input angles (applies to both arrays).

'rad'

Returns:

Name Type Description
r float

Circular correlation coefficient in [-1, 1]. - r > 0: positive association (angles increase together) - r < 0: negative association (angles move in opposite directions) - r = 0: no circular correlation NaN when either variable is constant.

pval float

Two-sided p-value from the large-sample normal approximation. NaN when r is undefined or the statistic's variance is zero.

Raises:

Type Description
ValueError

If angle_unit is unknown, the arrays have different lengths, or fewer than 5 pairs remain after dropping pairs with NaN.

See Also

circular_linear_correlation : For circular-linear correlation.

Notes

Formula (Jammalamadaka & SenGupta, 2001, p. 176):

rho = sum(sin(a1 - mean1) * sin(a2 - mean2)) /
      sqrt(sum(sin(a1 - mean1)^2) * sum(sin(a2 - mean2)^2))

Interpretation:

  • |r| > 0.3: Moderate association
  • |r| > 0.5: Strong association

Important Properties:

  • Symmetric: r(a1, a2) == r(a2, a1)
  • Invariant to constant offsets: r(a, a + c) = 1.0 for any constant c (because deviations from circular means remain identical)
  • Anticorrelation requires reflection: r(a, -a) approaches -1.0

Calibration. The p-value is CircStat's normal approximation (circ_corrcc, Berens 2009). For two independent samples it is calibrated from about 30 pairs: pval < 0.05 occurred in 4.7-5.3% of 20 000 draws of von Mises angles (kappa 0.5 to 2) at n = 30, 100 and 300, and in 4.5-5.4% of 5000 draws of uniform angles at n = 30 to 200. It is conservative for very small samples: in 5000 draws, pval < 0.05 occurred in 1.1-1.9% at n = 5 and 4.3-5.7% at n = 10, and pval < 0.01 in 0.2-0.4% at n = 10.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.circular import circular_circular_correlation
>>> angles_a = np.random.default_rng(42).uniform(0, 2 * np.pi, 100)
>>> angles_b = angles_a + 0.1 * np.random.default_rng(42).standard_normal(100)
>>> r, p = circular_circular_correlation(angles_a, angles_b)
>>> r > 0.8
True

This is not the Fisher & Lee (1983) coefficient, which is built from pairwise angle differences and gives different values.

References

Jammalamadaka, S.R. & Sarma, Y.R. (1988). A correlation coefficient for angular variables. In Statistical Theory and Data Analysis II, 349-364. North-Holland. Jammalamadaka, S.R. & SenGupta, A. (2001). Topics in Circular Statistics. World Scientific, p. 176. Berens, P. (2009). CircStat: a MATLAB toolbox for circular statistics. Journal of Statistical Software, 31(10).

Source code in src/neurospatial/stats/circular.py
def circular_circular_correlation(
    angles_a: NDArray[np.float64],
    angles_b: NDArray[np.float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
) -> tuple[float, float]:
    """
    Circular-circular correlation coefficient.

    Computes the Jammalamadaka & Sarma (1988) circular correlation
    coefficient between two circular variables, as CircStat's
    ``circ_corrcc``.

    Parameters
    ----------
    angles_a : ndarray of shape (n_samples,)
        First circular variable in radians or degrees.
    angles_b : ndarray of shape (n_samples,)
        Second circular variable in radians or degrees. Must have same
        length as ``angles_a``. A pair with a NaN in either array is dropped
        with a warning and the correlation uses the remaining pairs.
    angle_unit : {'rad', 'deg'}, default='rad'
        Unit of input angles (applies to both arrays).

    Returns
    -------
    r : float
        Circular correlation coefficient in [-1, 1].
        - r > 0: positive association (angles increase together)
        - r < 0: negative association (angles move in opposite directions)
        - r = 0: no circular correlation
        NaN when either variable is constant.
    pval : float
        Two-sided p-value from the large-sample normal approximation. NaN
        when ``r`` is undefined or the statistic's variance is zero.

    Raises
    ------
    ValueError
        If ``angle_unit`` is unknown, the arrays have different lengths, or
        fewer than 5 pairs remain after dropping pairs with NaN.

    See Also
    --------
    circular_linear_correlation : For circular-linear correlation.

    Notes
    -----
    **Formula** (Jammalamadaka & SenGupta, 2001, p. 176):

        rho = sum(sin(a1 - mean1) * sin(a2 - mean2)) /
              sqrt(sum(sin(a1 - mean1)^2) * sum(sin(a2 - mean2)^2))

    **Interpretation**:

    - |r| > 0.3: Moderate association
    - |r| > 0.5: Strong association

    **Important Properties**:

    - Symmetric: r(a1, a2) == r(a2, a1)
    - Invariant to constant offsets: r(a, a + c) = 1.0 for any constant c
      (because deviations from circular means remain identical)
    - Anticorrelation requires reflection: r(a, -a) approaches -1.0

    **Calibration.** The p-value is CircStat's normal approximation
    (``circ_corrcc``, Berens 2009). For two independent samples it is
    calibrated from about 30 pairs: ``pval < 0.05`` occurred in 4.7-5.3% of
    20 000 draws of von Mises angles (kappa 0.5 to 2) at n = 30, 100 and 300,
    and in 4.5-5.4% of 5000 draws of uniform angles at n = 30 to 200. It is
    conservative for very small samples: in 5000 draws, ``pval < 0.05``
    occurred in 1.1-1.9% at n = 5 and 4.3-5.7% at n = 10, and
    ``pval < 0.01`` in 0.2-0.4% at n = 10.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.circular import circular_circular_correlation
    >>> angles_a = np.random.default_rng(42).uniform(0, 2 * np.pi, 100)
    >>> angles_b = angles_a + 0.1 * np.random.default_rng(42).standard_normal(100)
    >>> r, p = circular_circular_correlation(angles_a, angles_b)
    >>> r > 0.8
    True

    This is not the Fisher & Lee (1983) coefficient, which is built from
    pairwise angle differences and gives different values.

    References
    ----------
    Jammalamadaka, S.R. & Sarma, Y.R. (1988). A correlation coefficient for
        angular variables. In Statistical Theory and Data Analysis II,
        349-364. North-Holland.
    Jammalamadaka, S.R. & SenGupta, A. (2001). Topics in Circular Statistics.
        World Scientific, p. 176.
    Berens, P. (2009). CircStat: a MATLAB toolbox for circular statistics.
        Journal of Statistical Software, 31(10).
    """
    from scipy import stats

    angles_a = to_radians(angles_a, angle_unit)
    angles_b = to_radians(angles_b, angle_unit)

    # Validate paired inputs (handles NaN removal and length check)
    angles_a, angles_b = _validate_paired_input(
        angles_a, angles_b, "angles_a", "angles_b", min_samples=5
    )

    n = len(angles_a)

    # Compute circular means using scipy
    alpha_bar = float(stats.circmean(angles_a, high=2 * np.pi, low=0))
    beta_bar = float(stats.circmean(angles_b, high=2 * np.pi, low=0))

    # Compute deviations from circular mean
    sin_dev1 = np.sin(angles_a - alpha_bar)
    sin_dev2 = np.sin(angles_b - beta_bar)

    l20 = np.mean(sin_dev1**2)
    l02 = np.mean(sin_dev2**2)
    # A spread below 1e-10 rad RMS is rounding error around a constant angle.
    if min(l20, l02) <= 1e-20:
        return np.nan, np.nan

    # Jammalamadaka & Sarma coefficient
    num = np.sum(sin_dev1 * sin_dev2)
    den = np.sqrt(np.sum(sin_dev1**2) * np.sum(sin_dev2**2))
    rho = num / den

    # Clip to valid range (numerical stability)
    rho = float(np.clip(rho, -1.0, 1.0))

    # Significance test (normal approximation)
    # From Jammalamadaka & SenGupta (2001), p. 177
    l22 = np.mean(sin_dev1**2 * sin_dev2**2)

    if l22 == 0:
        return rho, np.nan

    # Test statistic follows standard normal under null hypothesis
    ts = np.sqrt((n * l20 * l02) / l22) * rho
    return rho, float(2 * stats.norm.sf(np.abs(ts)))

circular_linear_correlation

circular_linear_correlation(
    angles: NDArray[float64],
    linear_values: NDArray[float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
) -> tuple[float, float]

Circular-linear correlation coefficient.

Computes the correlation between a circular and a linear variable using the Mardia & Jupp formula.

Parameters:

Name Type Description Default
angles ndarray of shape (n_samples,)

Circular variable (e.g., spike phases) in radians or degrees.

required
linear_values ndarray of shape (n_samples,)

Linear variable (e.g., positions, time). A pair with a NaN in either array is dropped with a warning and the correlation uses the remaining pairs.

required
angle_unit ('rad', 'deg')

Unit of input angles.

'rad'

Returns:

Name Type Description
r float

Correlation coefficient in [0, 1]. It has no sign, so it cannot tell phase precession from procession; for slope and direction use compute_phase_precession. NaN when the correlation is undefined: constant linear_values or constant angles.

pval float

P-value from the large-sample chi-squared approximation (see Notes). NaN when r is undefined.

Raises:

Type Description
ValueError

If angle_unit is unknown, the arrays have different lengths, or fewer than 3 pairs remain after dropping pairs with NaN.

See Also

phase_position_correlation : Alias with neuroscience naming. circular_circular_correlation : For two circular variables.

Notes

r is the multiple correlation of the linear variable on cos(angles) and sin(angles): r**2 is the fraction of its variance a least-squares fit x ~ a + b cos(angles) + c sin(angles) explains (Mardia & Jupp 2000, ch. 11). With full-rank cos/sin columns this equals

r^2 = (r_xs^2 + r_xc^2 - 2*r_xs*r_xc*r_cs) / (1 - r_cs^2)

where r_xs, r_xc and r_cs are the Pearson correlations of x with sin(angles), of x with cos(angles), and of cos(angles) with sin(angles). The projection form stays defined when cos and sin are collinear, for example when the angles take only two values; the fit then has one degree of freedom instead of two.

Under independence, n * r**2 is approximately chi-squared with as many degrees of freedom as the fit (2, or 1 for collinear cos/sin), as in CircStat's circ_corrcl (Berens 2009). The approximation is conservative for small samples. r is at most 1, so pval is never below exp(-n / 2): with 5 or fewer pairs it cannot fall below 0.05. In simulation (4000-5000 draws per row, x normal and independent of uniform or von Mises angles), pval < 0.05 occurred in 4.0-4.5% of draws at n = 10, 4.6-5.0% at n = 20 to 50 and 4.8-5.0% at n = 200; pval < 0.01 occurred in 0-0.02% at n = 10 and 0.8-1.1% at n = 200. With two-valued angles (1 degree of freedom) pval < 0.05 occurred in 5.5% at n = 10 and 4.8-4.9% at n = 30 and 200. For a small sample with a 1% level, a permutation test of r is exact.

r is not a measure of how tightly points follow a wrapped line. The fit has one cycle of cosine and sine to work with, so a noiseless line that turns through c whole cycles gives r = sqrt(6) / (pi * c): 0.78 at one cycle and 0.39 at two. For phase precession use mean_resultant_length or rho from compute_phase_precession.

References

Mardia, K.V. & Jupp, P.E. (2000). Directional Statistics. Wiley. Berens, P. (2009). CircStat: a MATLAB toolbox for circular statistics. Journal of Statistical Software, 31(10).

Examples:

>>> import numpy as np
>>> from neurospatial.stats.circular import circular_linear_correlation
>>> positions = np.linspace(0, 100, 50)
>>> phases = np.linspace(0, 2 * np.pi, 50)  # Linear relationship
>>> r, p = circular_linear_correlation(phases, positions)
>>> r > 0.5 and p < 0.05  # Significant correlation
True
Source code in src/neurospatial/stats/circular.py
def circular_linear_correlation(
    angles: NDArray[np.float64],
    linear_values: NDArray[np.float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
) -> tuple[float, float]:
    """
    Circular-linear correlation coefficient.

    Computes the correlation between a circular and a linear variable
    using the Mardia & Jupp formula.

    Parameters
    ----------
    angles : ndarray of shape (n_samples,)
        Circular variable (e.g., spike phases) in radians or degrees.
    linear_values : ndarray of shape (n_samples,)
        Linear variable (e.g., positions, time). A pair with a NaN in either
        array is dropped with a warning and the correlation uses the remaining
        pairs.
    angle_unit : {'rad', 'deg'}, default='rad'
        Unit of input angles.

    Returns
    -------
    r : float
        Correlation coefficient in [0, 1]. It has no sign, so it cannot tell
        phase precession from procession; for slope and direction use
        ``compute_phase_precession``. NaN when the correlation is undefined:
        constant ``linear_values`` or constant angles.
    pval : float
        P-value from the large-sample chi-squared approximation (see Notes).
        NaN when ``r`` is undefined.

    Raises
    ------
    ValueError
        If ``angle_unit`` is unknown, the arrays have different lengths, or
        fewer than 3 pairs remain after dropping pairs with NaN.

    See Also
    --------
    phase_position_correlation : Alias with neuroscience naming.
    circular_circular_correlation : For two circular variables.

    Notes
    -----
    ``r`` is the multiple correlation of the linear variable on cos(angles)
    and sin(angles): ``r**2`` is the fraction of its variance a least-squares
    fit ``x ~ a + b cos(angles) + c sin(angles)`` explains (Mardia & Jupp
    2000, ch. 11). With full-rank cos/sin columns this equals

        r^2 = (r_xs^2 + r_xc^2 - 2*r_xs*r_xc*r_cs) / (1 - r_cs^2)

    where r_xs, r_xc and r_cs are the Pearson correlations of x with
    sin(angles), of x with cos(angles), and of cos(angles) with sin(angles).
    The projection form stays defined when cos and sin are collinear, for
    example when the angles take only two values; the fit then has one
    degree of freedom instead of two.

    Under independence, ``n * r**2`` is approximately chi-squared with as many
    degrees of freedom as the fit (2, or 1 for collinear cos/sin), as in
    CircStat's ``circ_corrcl`` (Berens 2009). The approximation is
    conservative for small samples. ``r`` is at most 1, so ``pval`` is never
    below ``exp(-n / 2)``: with 5 or fewer pairs it cannot fall below 0.05.
    In simulation (4000-5000 draws per row, x normal and independent of
    uniform or von Mises angles), ``pval < 0.05`` occurred in 4.0-4.5% of
    draws at n = 10, 4.6-5.0% at n = 20 to 50 and 4.8-5.0% at n = 200;
    ``pval < 0.01`` occurred in 0-0.02% at n = 10 and 0.8-1.1% at n = 200.
    With two-valued angles (1 degree of freedom) ``pval < 0.05`` occurred in
    5.5% at n = 10 and 4.8-4.9% at n = 30 and 200.
    For a small sample with a 1% level, a permutation test of ``r`` is
    exact.

    ``r`` is not a measure of how tightly points follow a wrapped line. The
    fit has one cycle of cosine and sine to work with, so a noiseless line
    that turns through ``c`` whole cycles gives ``r = sqrt(6) / (pi * c)``:
    0.78 at one cycle and 0.39 at two. For phase precession use
    ``mean_resultant_length`` or ``rho`` from ``compute_phase_precession``.

    References
    ----------
    Mardia, K.V. & Jupp, P.E. (2000). Directional Statistics. Wiley.
    Berens, P. (2009). CircStat: a MATLAB toolbox for circular statistics.
        Journal of Statistical Software, 31(10).

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.circular import circular_linear_correlation
    >>> positions = np.linspace(0, 100, 50)
    >>> phases = np.linspace(0, 2 * np.pi, 50)  # Linear relationship
    >>> r, p = circular_linear_correlation(phases, positions)
    >>> r > 0.5 and p < 0.05  # Significant correlation
    True
    """
    # scipy.stats is imported on use; it adds ~0.2 s to importing the package.
    from scipy.stats import chi2

    angles = to_radians(angles, angle_unit)

    # Validate paired inputs (handles length mismatch, NaN removal)
    angles, linear_values = _validate_paired_input(
        angles, linear_values, "angles", "linear_values", min_samples=3
    )

    n = len(angles)

    if np.ptp(linear_values) == 0:
        return np.nan, np.nan

    # Project the centered linear variable onto the span of the centered
    # cos/sin columns. cos and sin lie in [-1, 1], so an absolute singular
    # value cutoff (RMS spread 1e-10) decides which directions exist. r^2 does
    # not depend on the scale of x; scaling it to at most 1 keeps the sums of
    # squares finite for very large values.
    x = linear_values - linear_values.mean()
    x /= np.max(np.abs(x))
    basis = np.column_stack([np.cos(angles), np.sin(angles)])
    basis -= basis.mean(axis=0)
    u, singular_values, _ = np.linalg.svd(basis, full_matrices=False)
    rank = int(np.sum(singular_values > 1e-10 * np.sqrt(n)))
    if rank == 0:
        return np.nan, np.nan

    projection = u[:, :rank].T @ x
    r_squared = min(float(projection @ projection) / float(x @ x), 1.0)
    pval = float(chi2.sf(n * r_squared, df=rank))
    return float(np.sqrt(r_squared)), pval

circular_mean

circular_mean(
    angles: NDArray[float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
    weights: NDArray[float64] | None = None,
) -> float

Compute the circular mean (mean direction) of angles.

Parameters:

Name Type Description Default
angles ndarray of shape (n_samples,)

Sample of angles. NaN angles (and their weights) are dropped with a warning.

required
angle_unit ('rad', 'deg')

Unit of input angles.

'rad'
weights ndarray of shape (n_samples,)

Weights for each angle. If None, uniform weights are used. Must be the same length as angles, finite and non-negative.

None

Returns:

Type Description
float

Circular mean in radians, range [-π, π], whatever angle_unit. NaN when no angle carries weight, or when the mean direction is undefined because the resultant vector is zero (e.g., two opposite angles).

Examples:

>>> import numpy as np
>>> from neurospatial.stats.circular import circular_mean
>>> angles = np.array([0, np.pi / 4, np.pi / 2])
>>> mean = circular_mean(angles)
>>> bool(np.abs(mean - np.pi / 4) < 0.1)
True
Source code in src/neurospatial/stats/circular.py
def circular_mean(
    angles: NDArray[np.float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
    weights: NDArray[np.float64] | None = None,
) -> float:
    """
    Compute the circular mean (mean direction) of angles.

    Parameters
    ----------
    angles : ndarray of shape (n_samples,)
        Sample of angles. NaN angles (and their weights) are dropped with a
        warning.
    angle_unit : {'rad', 'deg'}, default='rad'
        Unit of input angles.
    weights : ndarray of shape (n_samples,), optional
        Weights for each angle. If None, uniform weights are used.
        Must be the same length as ``angles``, finite and non-negative.

    Returns
    -------
    float
        Circular mean in radians, range [-π, π], whatever ``angle_unit``.
        NaN when no angle carries weight, or when the mean direction is
        undefined because the resultant vector is zero (e.g., two opposite
        angles).

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.circular import circular_mean
    >>> angles = np.array([0, np.pi / 4, np.pi / 2])
    >>> mean = circular_mean(angles)
    >>> bool(np.abs(mean - np.pi / 4) < 0.1)
    True
    """
    mean_cos, mean_sin = _mean_vector(
        *_valid_angles(angles, angle_unit, weights, min_samples=0)
    )
    # A resultant below rounding error has no direction (NaN fails the test).
    if not np.hypot(mean_cos, mean_sin) > 1e-12:
        return np.nan
    return float(np.arctan2(mean_sin, mean_cos))

circular_variance

circular_variance(
    angles: NDArray[float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
    weights: NDArray[float64] | None = None,
) -> float

Compute the circular variance of angles.

The circular variance is defined as V = 1 - R, where R is the mean resultant length.

Parameters:

Name Type Description Default
angles ndarray of shape (n_samples,)

Sample of angles. NaN angles (and their weights) are dropped with a warning.

required
angle_unit ('rad', 'deg')

Unit of input angles.

'rad'
weights ndarray of shape (n_samples,)

Weights for each angle. If None, uniform weights are used. Must be the same length as angles, finite and non-negative.

None

Returns:

Type Description
float

Circular variance in [0, 1]. 0 indicates all angles are identical, 1 indicates maximum dispersion (uniform distribution). NaN when no angle carries weight.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.circular import circular_variance
>>> # Concentrated distribution - low variance
>>> concentrated = np.array([0.1, 0.15, 0.05, 0.12])
>>> var = circular_variance(concentrated)
>>> var < 0.1
True
Source code in src/neurospatial/stats/circular.py
def circular_variance(
    angles: NDArray[np.float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
    weights: NDArray[np.float64] | None = None,
) -> float:
    """
    Compute the circular variance of angles.

    The circular variance is defined as V = 1 - R, where R is the mean
    resultant length.

    Parameters
    ----------
    angles : ndarray of shape (n_samples,)
        Sample of angles. NaN angles (and their weights) are dropped with a
        warning.
    angle_unit : {'rad', 'deg'}, default='rad'
        Unit of input angles.
    weights : ndarray of shape (n_samples,), optional
        Weights for each angle. If None, uniform weights are used.
        Must be the same length as ``angles``, finite and non-negative.

    Returns
    -------
    float
        Circular variance in [0, 1]. 0 indicates all angles are identical,
        1 indicates maximum dispersion (uniform distribution). NaN when no
        angle carries weight.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.circular import circular_variance
    >>> # Concentrated distribution - low variance
    >>> concentrated = np.array([0.1, 0.15, 0.05, 0.12])
    >>> var = circular_variance(concentrated)
    >>> var < 0.1
    True
    """
    return 1.0 - _mean_resultant_length(
        *_valid_angles(angles, angle_unit, weights, min_samples=0)
    )

is_modulated

is_modulated(
    beta_sin: float,
    beta_cos: float,
    cov_matrix: NDArray[float64],
    *,
    alpha: float = 0.05,
    min_magnitude: float = 0.2,
) -> bool

Quick check: Do GLM coefficients show significant circular modulation?

This is a convenience function that combines statistical significance (Wald test p-value) with a practical magnitude threshold.

Parameters:

Name Type Description Default
beta_sin float

Coefficient for sin(angle) from fitted GLM.

required
beta_cos float

Coefficient for cos(angle) from fitted GLM.

required
cov_matrix (ndarray, shape(2, 2))

Covariance matrix for [beta_sin, beta_cos] from GLM fit. Required for significance testing.

required
alpha float

Significance level for Wald test.

0.05
min_magnitude float

Minimum modulation magnitude (amplitude) required. Amplitude = sqrt(beta_sin^2 + beta_cos^2).

With a log link (Poisson GLM) the peak-to-trough rate ratio is exp(2 * amplitude), so the default 0.2 asks for at least a 1.49-fold modulation of the rate. This is a screening convention, not a statistical criterion; set it from the effect size that matters for your question.

0.2

Returns:

Type Description
bool

True if BOTH: - p-value < alpha (statistically significant) - magnitude >= min_magnitude (practically meaningful) False otherwise, including when cov_matrix is singular (the p-value is then NaN).

Raises:

Type Description
ValueError

If cov_matrix is not a finite, symmetric positive semi-definite 2x2 matrix, or the coefficients are not finite.

See Also

circular_basis_metrics : For full analysis with all metrics.

Notes

Why both thresholds?

Statistical significance alone can occur with very weak modulation when sample sizes are large. Requiring both significance AND a minimum magnitude ensures the modulation is both reliable and biologically meaningful.

The magnitude gate is neurospatial's own screening rule, not part of the Wald test. For untuned Poisson cells it changes the false-positive rate only when there are many spikes: with 20 to 100 spikes every significant null amplitude was above 0.2, so the screen rejected as often as the Wald test (3.6-5.0%); with 1000 spikes it rejected 0 to 1 of 2000 cells. See :func:circular_basis_metrics for the Wald test's calibration.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.circular import is_modulated
>>> # Strong significant modulation
>>> is_modulated(2.0, 2.0, np.array([[0.01, 0], [0, 0.01]]))
True
>>> # Weak (non-significant) modulation
>>> is_modulated(0.1, 0.1, np.array([[1.0, 0], [0, 1.0]]))
False
Source code in src/neurospatial/stats/circular.py
def is_modulated(
    beta_sin: float,
    beta_cos: float,
    cov_matrix: NDArray[np.float64],
    *,
    alpha: float = 0.05,
    min_magnitude: float = 0.2,
) -> bool:
    """
    Quick check: Do GLM coefficients show significant circular modulation?

    This is a convenience function that combines statistical significance
    (Wald test p-value) with a practical magnitude threshold.

    Parameters
    ----------
    beta_sin : float
        Coefficient for sin(angle) from fitted GLM.
    beta_cos : float
        Coefficient for cos(angle) from fitted GLM.
    cov_matrix : ndarray, shape (2, 2)
        Covariance matrix for [beta_sin, beta_cos] from GLM fit.
        Required for significance testing.
    alpha : float, default=0.05
        Significance level for Wald test.
    min_magnitude : float, default=0.2
        Minimum modulation magnitude (amplitude) required.
        Amplitude = sqrt(beta_sin^2 + beta_cos^2).

        With a log link (Poisson GLM) the peak-to-trough rate ratio is
        ``exp(2 * amplitude)``, so the default 0.2 asks for at least a
        1.49-fold modulation of the rate. This is a screening convention,
        not a statistical criterion; set it from the effect size that
        matters for your question.

    Returns
    -------
    bool
        True if BOTH:
        - p-value < alpha (statistically significant)
        - magnitude >= min_magnitude (practically meaningful)
        False otherwise, including when ``cov_matrix`` is singular (the
        p-value is then NaN).

    Raises
    ------
    ValueError
        If ``cov_matrix`` is not a finite, symmetric positive semi-definite
        2x2 matrix, or the coefficients are not finite.

    See Also
    --------
    circular_basis_metrics : For full analysis with all metrics.

    Notes
    -----
    **Why both thresholds?**

    Statistical significance alone can occur with very weak modulation
    when sample sizes are large. Requiring both significance AND a
    minimum magnitude ensures the modulation is both reliable and
    biologically meaningful.

    The magnitude gate is neurospatial's own screening rule, not part of the
    Wald test. For untuned Poisson cells it changes the false-positive rate
    only when there are many spikes: with 20 to 100 spikes every significant
    null amplitude was above 0.2, so the screen rejected as often as the
    Wald test (3.6-5.0%); with 1000 spikes it rejected 0 to 1 of 2000 cells.
    See :func:`circular_basis_metrics` for the Wald test's calibration.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.circular import is_modulated
    >>> # Strong significant modulation
    >>> is_modulated(2.0, 2.0, np.array([[0.01, 0], [0, 0.01]]))
    True
    >>> # Weak (non-significant) modulation
    >>> is_modulated(0.1, 0.1, np.array([[1.0, 0], [0, 1.0]]))
    False
    """
    amplitude, _, pvalue = circular_basis_metrics(beta_sin, beta_cos, cov_matrix)
    return bool(pvalue < alpha and amplitude >= min_magnitude)

mean_resultant_length

mean_resultant_length(
    angles: NDArray[float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
    weights: NDArray[float64] | None = None,
) -> float

Compute the mean resultant length (Rayleigh vector length).

The mean resultant length R measures concentration of circular data. It equals 1 if all angles are identical and approaches 0 for uniform distributions.

Parameters:

Name Type Description Default
angles ndarray of shape (n_samples,)

Sample of angles. NaN angles (and their weights) are dropped with a warning.

required
angle_unit ('rad', 'deg')

Unit of input angles.

'rad'
weights ndarray of shape (n_samples,)

Weights for each angle. If None, uniform weights are used. Must be the same length as angles, finite and non-negative.

None

Returns:

Type Description
float

Mean resultant length R in [0, 1]. NaN when no angle carries weight.

Notes

The mean resultant length is defined as:

R = |mean(exp(i * angles))| = sqrt(mean(cos)^2 + mean(sin)^2)

Examples:

>>> import numpy as np
>>> from neurospatial.stats.circular import mean_resultant_length
>>> # All angles identical - R should be 1
>>> r = mean_resultant_length(np.array([0, 0, 0, 0]))
>>> bool(np.abs(r - 1.0) < 0.01)
True
Source code in src/neurospatial/stats/circular.py
def mean_resultant_length(
    angles: NDArray[np.float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
    weights: NDArray[np.float64] | None = None,
) -> float:
    """
    Compute the mean resultant length (Rayleigh vector length).

    The mean resultant length R measures concentration of circular data.
    It equals 1 if all angles are identical and approaches 0 for uniform
    distributions.

    Parameters
    ----------
    angles : ndarray of shape (n_samples,)
        Sample of angles. NaN angles (and their weights) are dropped with a
        warning.
    angle_unit : {'rad', 'deg'}, default='rad'
        Unit of input angles.
    weights : ndarray of shape (n_samples,), optional
        Weights for each angle. If None, uniform weights are used.
        Must be the same length as ``angles``, finite and non-negative.

    Returns
    -------
    float
        Mean resultant length R in [0, 1]. NaN when no angle carries weight.

    Notes
    -----
    The mean resultant length is defined as:

        R = |mean(exp(i * angles))| = sqrt(mean(cos)^2 + mean(sin)^2)

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.circular import mean_resultant_length
    >>> # All angles identical - R should be 1
    >>> r = mean_resultant_length(np.array([0, 0, 0, 0]))
    >>> bool(np.abs(r - 1.0) < 0.01)
    True
    """
    return _mean_resultant_length(
        *_valid_angles(angles, angle_unit, weights, min_samples=0)
    )

phase_position_correlation

phase_position_correlation(
    phases: NDArray[float64],
    positions: NDArray[float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
) -> tuple[float, float]

Correlation between spike phases and positions.

This is an alias for circular_linear_correlation with neuroscience naming conventions.

Parameters:

Name Type Description Default
phases ndarray of shape (n_spikes,)

Spike phases relative to LFP theta in radians or degrees.

required
positions ndarray of shape (n_spikes,)

Position at each spike.

required
angle_unit ('rad', 'deg')

Unit of input phases.

'rad'

Returns:

Name Type Description
r float

Correlation coefficient in [0, 1].

pval float

P-value from chi-squared distribution.

See Also

circular_linear_correlation : Generic version. phase_precession : Full phase precession analysis with slope.

Source code in src/neurospatial/stats/circular.py
@reads_pynapple_samples
def phase_position_correlation(
    phases: NDArray[np.float64],
    positions: NDArray[np.float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
) -> tuple[float, float]:
    """
    Correlation between spike phases and positions.

    This is an alias for ``circular_linear_correlation`` with neuroscience
    naming conventions.

    Parameters
    ----------
    phases : ndarray of shape (n_spikes,)
        Spike phases relative to LFP theta in radians or degrees.
    positions : ndarray of shape (n_spikes,)
        Position at each spike.
    angle_unit : {'rad', 'deg'}, default='rad'
        Unit of input phases.

    Returns
    -------
    r : float
        Correlation coefficient in [0, 1].
    pval : float
        P-value from chi-squared distribution.

    See Also
    --------
    circular_linear_correlation : Generic version.
    phase_precession : Full phase precession analysis with slope.
    """
    return circular_linear_correlation(phases, positions, angle_unit=angle_unit)

plot_circular_basis_tuning

plot_circular_basis_tuning(
    beta_sin: float,
    beta_cos: float,
    angles: NDArray[float64] | None = None,
    rates: NDArray[float64] | None = None,
    *,
    ax: Axes | PolarAxes | None = None,
    intercept: float = 0.0,
    cov_matrix: NDArray[float64] | None = None,
    projection: Literal["polar", "linear"] = "polar",
    n_points: int = 100,
    show_data: bool = False,
    show_fit: bool = True,
    show_ci: bool = False,
    ci: float = 0.95,
    color: str = "C0",
    data_color: str = "gray",
    data_alpha: float = 0.5,
    ci_alpha: float = 0.3,
    line_kwargs: dict[str, Any] | None = None,
    scatter_kwargs: dict[str, Any] | None = None,
) -> Axes | PolarAxes

Plot tuning curve from GLM circular basis coefficients.

Visualizes the fitted circular tuning curve from a GLM with sin/cos basis functions, optionally overlaying raw binned data.

Parameters:

Name Type Description Default
beta_sin float

Coefficient for sin(angle) from fitted GLM.

required
beta_cos float

Coefficient for cos(angle) from fitted GLM.

required
angles (array, shape(n_bins))

Center of each angular bin (radians) for raw data overlay. Required if show_data=True.

None
rates (array, shape(n_bins))

Firing rate or response in each bin. Required if show_data=True.

None
ax Axes

Axes to plot on. If None, creates new figure with appropriate projection.

None
intercept float

Intercept coefficient from GLM. The curve is exp(intercept + beta_sin sin + beta_cos cos): a rate in Hz if the GLM had a log(dt) offset, otherwise the expected count per time bin.

0.0
cov_matrix (ndarray, shape(3, 3) or (2, 2))

Covariance of the GLM coefficients, required if show_ci=True. Pass the 3x3 covariance of [intercept, beta_sin, beta_cos] (model.cov_params()[:3, :3]) for the pointwise interval of the rate. A 2x2 covariance of [beta_sin, beta_cos] leaves out the intercept's uncertainty: its band shows only the uncertainty of the tuning's shape and is narrower than the interval for the rate.

None
projection ('polar', 'linear')

Plot projection type.

'polar'
n_points int

Number of points for smooth fitted curve.

100
show_data bool

If True, overlay raw data points. Requires angles and rates.

False
show_fit bool

If True, show smooth curve from GLM fit.

True
show_ci bool

If True, show confidence band around fitted curve. Requires cov_matrix.

False
ci float

Confidence level for band (e.g., 0.95 for 95% CI).

0.95
color str

Color for fitted curve.

'C0'
data_color str

Color for data points.

'gray'
data_alpha float

Alpha (transparency) for data points.

0.5
ci_alpha float

Alpha (transparency) for confidence band fill.

0.3
line_kwargs dict

Additional kwargs for line plot (fitted curve).

None
scatter_kwargs dict

Additional kwargs for scatter plot (data points).

None

Returns:

Type Description
Axes

The axes object with the plot.

Raises:

Type Description
ValueError

If show_data=True but angles or rates not provided. If show_ci=True but cov_matrix not provided.

See Also

circular_basis_metrics : Compute amplitude/phase from coefficients. circular_basis : Create design matrix for GLM.

Notes

The curve assumes a log link (Poisson GLM). Data points from show_data share its axis, so give rates in the curve's units.

The polar projection draws angles as in the arena: 0 = East (right), π/2 = North (up), counter-clockwise, the convention in which circular_basis_metrics reports the preferred direction. A caller-supplied polar axis is reset to this orientation.

Examples:

Head direction GLM tuning curve:

>>> import numpy as np
>>> from neurospatial.stats.circular import plot_circular_basis_tuning
>>> # After fitting GLM to head direction data
>>> # Coefficients: preferred direction ~45° with strong modulation
>>> beta_sin, beta_cos = 0.7, 0.7  # atan2(0.7, 0.7) ≈ 45°
>>> ax = plot_circular_basis_tuning(
...     beta_sin, beta_cos, intercept=2.0
... )
Source code in src/neurospatial/stats/circular.py
def plot_circular_basis_tuning(
    beta_sin: float,
    beta_cos: float,
    angles: NDArray[np.float64] | None = None,
    rates: NDArray[np.float64] | None = None,
    *,
    ax: Axes | PolarAxes | None = None,
    intercept: float = 0.0,
    cov_matrix: NDArray[np.float64] | None = None,
    projection: Literal["polar", "linear"] = "polar",
    n_points: int = 100,
    show_data: bool = False,
    show_fit: bool = True,
    show_ci: bool = False,
    ci: float = 0.95,
    color: str = "C0",
    data_color: str = "gray",
    data_alpha: float = 0.5,
    ci_alpha: float = 0.3,
    line_kwargs: dict[str, Any] | None = None,
    scatter_kwargs: dict[str, Any] | None = None,
) -> Axes | PolarAxes:
    """
    Plot tuning curve from GLM circular basis coefficients.

    Visualizes the fitted circular tuning curve from a GLM with sin/cos
    basis functions, optionally overlaying raw binned data.

    Parameters
    ----------
    beta_sin : float
        Coefficient for sin(angle) from fitted GLM.
    beta_cos : float
        Coefficient for cos(angle) from fitted GLM.
    angles : array, shape (n_bins,), optional
        Center of each angular bin (radians) for raw data overlay.
        Required if ``show_data=True``.
    rates : array, shape (n_bins,), optional
        Firing rate or response in each bin.
        Required if ``show_data=True``.
    ax : matplotlib.axes.Axes, optional
        Axes to plot on. If None, creates new figure with appropriate projection.
    intercept : float, default=0.0
        Intercept coefficient from GLM. The curve is
        ``exp(intercept + beta_sin sin + beta_cos cos)``: a rate in Hz if
        the GLM had a ``log(dt)`` offset, otherwise the expected count per
        time bin.
    cov_matrix : ndarray, shape (3, 3) or (2, 2), optional
        Covariance of the GLM coefficients, required if ``show_ci=True``.
        Pass the 3x3 covariance of [intercept, beta_sin, beta_cos]
        (``model.cov_params()[:3, :3]``) for the pointwise interval of the
        rate. A 2x2 covariance of [beta_sin, beta_cos] leaves out the
        intercept's uncertainty: its band shows only the uncertainty of the
        tuning's shape and is narrower than the interval for the rate.
    projection : {'polar', 'linear'}, default='polar'
        Plot projection type.
    n_points : int, default=100
        Number of points for smooth fitted curve.
    show_data : bool, default=False
        If True, overlay raw data points. Requires ``angles`` and ``rates``.
    show_fit : bool, default=True
        If True, show smooth curve from GLM fit.
    show_ci : bool, default=False
        If True, show confidence band around fitted curve. Requires ``cov_matrix``.
    ci : float, default=0.95
        Confidence level for band (e.g., 0.95 for 95% CI).
    color : str, default='C0'
        Color for fitted curve.
    data_color : str, default='gray'
        Color for data points.
    data_alpha : float, default=0.5
        Alpha (transparency) for data points.
    ci_alpha : float, default=0.3
        Alpha (transparency) for confidence band fill.
    line_kwargs : dict, optional
        Additional kwargs for line plot (fitted curve).
    scatter_kwargs : dict, optional
        Additional kwargs for scatter plot (data points).

    Returns
    -------
    matplotlib.axes.Axes
        The axes object with the plot.

    Raises
    ------
    ValueError
        If ``show_data=True`` but ``angles`` or ``rates`` not provided.
        If ``show_ci=True`` but ``cov_matrix`` not provided.

    See Also
    --------
    circular_basis_metrics : Compute amplitude/phase from coefficients.
    circular_basis : Create design matrix for GLM.

    Notes
    -----
    The curve assumes a log link (Poisson GLM). Data points from
    ``show_data`` share its axis, so give ``rates`` in the curve's units.

    The polar projection draws angles as in the arena: 0 = East (right),
    π/2 = North (up), counter-clockwise, the convention in which
    ``circular_basis_metrics`` reports the preferred direction. A
    caller-supplied polar axis is reset to this orientation.

    Examples
    --------
    **Head direction GLM tuning curve**:

    >>> import numpy as np
    >>> from neurospatial.stats.circular import plot_circular_basis_tuning
    >>> # After fitting GLM to head direction data
    >>> # Coefficients: preferred direction ~45° with strong modulation
    >>> beta_sin, beta_cos = 0.7, 0.7  # atan2(0.7, 0.7) ≈ 45°
    >>> ax = plot_circular_basis_tuning(
    ...     beta_sin, beta_cos, intercept=2.0
    ... )  # doctest: +SKIP
    """
    import matplotlib.pyplot as plt
    from scipy import stats

    # Validate show_data requirements
    if show_data and (angles is None or rates is None):
        msg = (
            "show_data=True requires both angles and rates arguments.\n\n"
            "To show model fit over raw data:\n"
            "  plot_circular_basis_tuning(beta_sin, beta_cos, "
            "angles=bins, rates=rates, show_data=True)\n\n"
            "To show only the fitted curve:\n"
            "  plot_circular_basis_tuning(beta_sin, beta_cos, show_data=False)"
        )
        raise ValueError(msg)

    # Validate show_ci requirements
    if show_ci and cov_matrix is None:
        msg = (
            "show_ci=True requires cov_matrix argument.\n\n"
            "To show confidence bands:\n"
            "  cov = model.cov_params()[:3, :3]  # intercept, sin, cos\n"
            "  plot_circular_basis_tuning(beta_sin, beta_cos, cov_matrix=cov, show_ci=True)"
        )
        raise ValueError(msg)

    # Create figure if needed
    if ax is None:
        if projection == "polar":
            _, ax = plt.subplots(subplot_kw={"projection": "polar"})
        else:
            _, ax = plt.subplots()
    elif projection == "polar":
        _require_polar(
            ax, "plot_circular_basis_tuning", alternative='pass `projection="linear"`'
        )

    line_kw = {"color": color, "linewidth": 2, "zorder": 2, **(line_kwargs or {})}
    scatter_kw = {
        "color": data_color,
        "alpha": data_alpha,
        "s": 30,
        "zorder": 1,
        **(scatter_kwargs or {}),
    }

    # A closed curve: the last point repeats the first, one turn later.
    theta = np.linspace(0, 2 * np.pi, n_points + 1)
    theta[-1] = theta[0] + 2 * np.pi
    design = np.column_stack([np.sin(theta), np.cos(theta)])
    # GLM prediction on the log-link scale: intercept + beta_sin sin + beta_cos cos
    linear_pred = intercept + design @ np.array([beta_sin, beta_cos])

    if projection == "polar":
        # Draw angles as in the arena: 0 = East (right), counter-clockwise.
        polar_ax = cast("PolarAxes", ax)
        polar_ax.set_theta_zero_location("E")
        polar_ax.set_theta_direction(1)

    if show_ci:
        # Pointwise band on the linear predictor, then mapped through exp.
        cov = _validated_cov(
            cast("NDArray[np.float64]", cov_matrix), intercept_allowed=True
        )
        rows = (
            np.column_stack([np.ones_like(theta), design])
            if cov.shape == (3, 3)
            else design
        )
        se_linear = np.sqrt(np.maximum(np.sum((rows @ cov) * rows, axis=1), 0))
        z = stats.norm.ppf((1 + ci) / 2)
        ax.fill_between(
            theta,
            np.exp(linear_pred - z * se_linear),
            np.exp(linear_pred + z * se_linear),
            color=color,
            alpha=ci_alpha,
            zorder=0,
        )
    if show_fit:
        ax.plot(theta, np.exp(linear_pred), **line_kw)
    if show_data:
        ax.scatter(
            np.asarray(angles, dtype=np.float64).ravel(),
            np.asarray(rates, dtype=np.float64).ravel(),
            **scatter_kw,
        )

    if projection != "polar":
        ax.set_xlabel("Angle (rad)")
        ax.set_ylabel("Response")
        ax.set_xlim(0, 2 * np.pi)

    return ax

rayleigh_test

rayleigh_test(
    angles: NDArray[float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
    weights: NDArray[float64] | None = None,
) -> tuple[float, float]

Rayleigh test for non-uniformity of circular data.

Tests H0: angles are uniformly distributed on the circle. Rejection indicates a preferred direction exists.

Parameters:

Name Type Description Default
angles ndarray of shape (n_samples,)

Sample of angles. NaN angles are dropped with a warning.

required
angle_unit ('rad', 'deg')

Unit of input angles.

'rad'
weights ndarray of shape (n_samples,)

Whole-number weights for each angle, interpreted as counts (e.g., spike counts per phase bin). If None, uniform unit weights are used. Weighting an angle by k is equivalent to observing that angle k times; the test statistic is z = sum(weights) * R**2 (see Notes). Occupancy times or rates are not counts: the p-value would change with their units.

None

Returns:

Name Type Description
z float

Rayleigh z-statistic (n * R^2 where R is mean resultant length). Range: [0, n], with n = sum(weights) for weighted input. Higher values indicate stronger directionality.

pval float

P-value in [0, 1] from Zar's approximation (see Notes). Small p-values (< 0.05) indicate a non-uniform distribution. It is 0.0 when the true value is below the smallest float64 (about 1e-308), for example 1000 angles with R = 0.995, as in CircStat.

Raises:

Type Description
ValueError

If angle_unit is unknown; if angles are empty, all NaN, contain Inf, or number fewer than 3; if weights is not the same length as angles (a length-1 array is rejected, not broadcast), is not finite, or contains negative or non-integer values; or if the total weight (sum of weights) is below 3.

See Also

circular_linear_correlation : Test correlation with linear variable.

Notes

The unweighted statistic is z = n * R**2 where R is the mean resultant length and n the number of angles. The p-value is Zar's approximation (Zar 1999, p. 617), as in CircStat's circ_rtest::

p = exp(sqrt(1 + 4n + 4(n**2 - (n R)**2)) - (1 + 2n))

It decreases as R grows and holds its level for small samples, where exp(-z) is conservative: on uniform angles, exp(-z) < 0.05 rejects 4.2% of samples of 5 angles and 4.6% of 10, against 5.1% and 5.0% for Zar's value. For n < 6 Zar's value is also conservative (p too large) below p = 0.01.

Independence. The test assumes independent angles. Spike phases are not independent when spikes come in bursts, because spikes in a burst share nearly the same phase. With burst sizes measured on running CA1 spikes in two recordings (1.2 to 1.3 spikes per event, grouping inter-spike intervals up to 10 ms), simulated uniform phases reached p < 0.05 in 12-17% of cells, not 5%. Testing one phase per burst gave 4-6%.

Weighted variant. When weights are supplied this is the grouped-data Rayleigh test: weights are frequencies, the resultant length is the weighted mean resultant length R = |sum_i w_i exp(i theta_i)| / sum_i w_i, and n = sum_i w_i. With unit weights this reduces exactly to the unweighted test, and integer weights match physically replicating each angle by its weight. This is intentionally not the effective-sample-size form n_eff = (sum w)**2 / sum(w**2). When the counts come from phase bins, R is biased low by the bin width (grouping).

References

Zar, J.H. (1999). Biostatistical Analysis, 4th ed. Prentice Hall. Berens, P. (2009). CircStat: a MATLAB toolbox for circular statistics. Journal of Statistical Software, 31(10).

Examples:

>>> import numpy as np
>>> from neurospatial.stats.circular import rayleigh_test
>>> # Uniform distribution - expect high p-value
>>> uniform_angles = np.linspace(0, 2 * np.pi, 100, endpoint=False)
>>> z, p = rayleigh_test(uniform_angles)
>>> p > 0.5
True
Source code in src/neurospatial/stats/circular.py
def rayleigh_test(
    angles: NDArray[np.float64],
    *,
    angle_unit: Literal["rad", "deg"] = "rad",
    weights: NDArray[np.float64] | None = None,
) -> tuple[float, float]:
    """
    Rayleigh test for non-uniformity of circular data.

    Tests H0: angles are uniformly distributed on the circle.
    Rejection indicates a preferred direction exists.

    Parameters
    ----------
    angles : ndarray of shape (n_samples,)
        Sample of angles. NaN angles are dropped with a warning.
    angle_unit : {'rad', 'deg'}, default='rad'
        Unit of input angles.
    weights : ndarray of shape (n_samples,), optional
        Whole-number weights for each angle, interpreted as **counts**
        (e.g., spike counts per phase bin). If None, uniform unit weights
        are used. Weighting an angle by ``k`` is equivalent to observing
        that angle ``k`` times; the test statistic is
        ``z = sum(weights) * R**2`` (see Notes). Occupancy times or rates
        are not counts: the p-value would change with their units.

    Returns
    -------
    z : float
        Rayleigh z-statistic (n * R^2 where R is mean resultant length).
        Range: [0, n], with n = sum(weights) for weighted input. Higher
        values indicate stronger directionality.
    pval : float
        P-value in [0, 1] from Zar's approximation (see Notes). Small
        p-values (< 0.05) indicate a non-uniform distribution. It is 0.0
        when the true value is below the smallest float64 (about 1e-308),
        for example 1000 angles with R = 0.995, as in CircStat.

    Raises
    ------
    ValueError
        If ``angle_unit`` is unknown; if angles are empty, all NaN, contain
        Inf, or number fewer than 3; if ``weights`` is not the same length
        as ``angles`` (a length-1 array is rejected, not broadcast), is not
        finite, or contains negative or non-integer values; or if the total
        weight (sum of weights) is below 3.

    See Also
    --------
    circular_linear_correlation : Test correlation with linear variable.

    Notes
    -----
    The unweighted statistic is ``z = n * R**2`` where ``R`` is the mean
    resultant length and ``n`` the number of angles. The p-value is Zar's
    approximation (Zar 1999, p. 617), as in CircStat's ``circ_rtest``::

        p = exp(sqrt(1 + 4n + 4(n**2 - (n R)**2)) - (1 + 2n))

    It decreases as ``R`` grows and holds its level for small samples,
    where ``exp(-z)`` is conservative: on uniform angles, ``exp(-z) < 0.05``
    rejects 4.2% of samples of 5 angles and 4.6% of 10, against 5.1% and
    5.0% for Zar's value. For n < 6 Zar's value is also conservative (p too
    large) below p = 0.01.

    **Independence.** The test assumes independent angles. Spike phases are
    not independent when spikes come in bursts, because spikes in a burst
    share nearly the same phase. With burst sizes measured on running CA1
    spikes in two recordings (1.2 to 1.3 spikes per event, grouping
    inter-spike intervals up to 10 ms), simulated uniform phases reached
    ``p < 0.05`` in 12-17% of cells, not 5%. Testing one phase per burst gave
    4-6%.

    **Weighted variant.** When ``weights`` are supplied this is the
    grouped-data Rayleigh test: weights are frequencies, the resultant
    length is the weighted mean resultant length
    ``R = |sum_i w_i exp(i theta_i)| / sum_i w_i``, and ``n = sum_i w_i``.
    With unit weights this reduces exactly to the unweighted test, and
    integer weights match physically replicating each angle by its weight.
    This is intentionally *not* the effective-sample-size form
    ``n_eff = (sum w)**2 / sum(w**2)``. When the counts come from phase
    bins, ``R`` is biased low by the bin width (grouping).

    References
    ----------
    Zar, J.H. (1999). Biostatistical Analysis, 4th ed. Prentice Hall.
    Berens, P. (2009). CircStat: a MATLAB toolbox for circular statistics.
        Journal of Statistical Software, 31(10).

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.circular import rayleigh_test
    >>> # Uniform distribution - expect high p-value
    >>> uniform_angles = np.linspace(0, 2 * np.pi, 100, endpoint=False)
    >>> z, p = rayleigh_test(uniform_angles)
    >>> p > 0.5
    True
    """
    # The weighted test's sample size is the total count, not the number of
    # angles: a tuned cell can put 100 spikes into one or two phase bins. So
    # the 3-sample minimum applies to n_eff below.
    angles, weights = _valid_angles(
        angles, angle_unit, weights, min_samples=1 if weights is not None else 3
    )
    if weights is not None and np.any(weights != np.round(weights)):
        msg = (
            "rayleigh_test weights must be whole-number counts (e.g., spike "
            "counts per phase bin). The test's sample size is sum(weights), so "
            "non-count weights such as occupancy times or rates make the "
            "p-value depend on their units.\n"
            "Fix: pass integer counts, or use mean_resultant_length(angles, "
            "weights=...) for a descriptive weighted concentration."
        )
        raise ValueError(msg)
    n_eff = float(np.sum(weights)) if weights is not None else float(len(angles))
    if n_eff < 3:
        msg = (
            f"Need at least 3 total weight (sum of counts) for the weighted "
            f"Rayleigh test. Got sum(weights) = {n_eff:g}.\n"
            f"Fix: provide more spikes/counts (all-zero counts carry no "
            f"data), or use a different analysis method."
        )
        raise ValueError(msg)
    r_mean = _mean_resultant_length(angles, weights=weights)

    # Rayleigh z-statistic: z = n_eff * R^2.
    z = n_eff * r_mean**2

    # Zar (1999, p. 617), with the exponent sqrt(a) - b rewritten as
    # (a - b**2) / (sqrt(a) + b) = -4 R_n**2 / (sqrt(a) + b) to avoid
    # cancellation for large n.
    r_n = n_eff * r_mean
    root = np.sqrt(1 + 4 * n_eff + 4 * (n_eff**2 - r_n**2))
    pval = float(np.exp(-4 * r_n**2 / (root + 1 + 2 * n_eff)))
    return float(z), pval

wrap_angle

wrap_angle(angle: NDArray[float64]) -> NDArray[np.float64]

Wrap angle to (-π, π].

A half-turn in either direction maps to +π, so an egocentric bearing directly behind the animal is +π.

Parameters:

Name Type Description Default
angle NDArray[float64]

Angles in radians.

required

Returns:

Type Description
NDArray[float64]

Angles wrapped to (-π, π].

Examples:

>>> import numpy as np
>>> from neurospatial.stats.circular import wrap_angle
>>> wrap_angle(np.array([3 * np.pi / 2, np.pi, -np.pi]))
array([-1.57079633,  3.14159265,  3.14159265])
Source code in src/neurospatial/_angles.py
def wrap_angle(angle: NDArray[np.float64]) -> NDArray[np.float64]:
    """
    Wrap angle to (-π, π].

    A half-turn in either direction maps to +π, so an egocentric bearing
    directly behind the animal is +π.

    Parameters
    ----------
    angle : NDArray[np.float64]
        Angles in radians.

    Returns
    -------
    NDArray[np.float64]
        Angles wrapped to (-π, π].

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.circular import wrap_angle
    >>> wrap_angle(np.array([3 * np.pi / 2, np.pi, -np.pi]))
    array([-1.57079633,  3.14159265,  3.14159265])
    """
    # x % (-2π) lies in (-2π, 0], so shifting by -π then +π gives (-π, π].
    wrapped = (angle - np.pi) % (-2 * np.pi) + np.pi
    # A remainder just below 0 can round to -2π, which would give -π.
    out: NDArray[np.float64] = np.where(wrapped <= -np.pi, np.pi, wrapped)
    return out

shuffle_pvalue

shuffle_pvalue(
    observed: float,
    null_scores: NDArray[float64],
    *,
    alternative: Literal["greater", "less", "two-sided"] = "greater",
) -> float

Compute Monte Carlo p-value with Phipson-Smyth correction.

Computes the probability of observing a score at least as extreme as the observed value under the null distribution using the formula (k + 1) / (n + 1). Counting the observed data as one draw from the null makes the p-value valid (never anti-conservative) and never zero.

Parameters:

Name Type Description Default
observed float

The observed score from the original (non-shuffled) data. Must be finite.

required
null_scores NDArray[float64]

Array of scores from shuffled data, forming the null distribution.

required
alternative ('greater', 'less', 'two-sided')

Direction of the test:

  • "greater": Tests if observed is significantly greater than null (counts null >= observed).
  • "less": Tests if observed is significantly less than null (counts null <= observed).
  • "two-sided": Tests if observed is significantly different from null in either direction. Computed as 2 * min(p_greater, p_less), capped at 1.0.
"greater"

Returns:

Type Description
float

The Monte Carlo p-value in the range (0, 1].

Raises:

Type Description
ValueError

If observed is not finite, alternative is unknown, or no null score is defined (all NaN or empty).

Notes

The Phipson-Smyth correction (k + 1) / (n + 1) ensures that:

  1. The p-value is never exactly zero, which is important for downstream corrections (e.g., Bonferroni, FDR).
  2. P(p <= alpha) <= alpha under the null: the test is valid, and slightly conservative as an estimate of the exact permutation p-value.

For replay analysis, "greater" is typically used because we expect significant sequences to have higher scores than shuffled controls.

NaN null scores (shuffles whose score is undefined) are dropped with a UserWarning and excluded from n. Infinite null scores are defined, extreme scores and are counted like any other.

References

.. [1] Phipson, B., & Smyth, G. K. (2010). Permutation P-values should never be zero: calculating exact P-values when permutations are randomly drawn. Statistical Applications in Genetics and Molecular Biology, 9(1).

Examples:

>>> import numpy as np
>>> from neurospatial.stats.shuffle import shuffle_pvalue
>>> # Observed score higher than all null values
>>> observed = 10.0
>>> null = np.array([1.0, 2.0, 3.0, 4.0])
>>> shuffle_pvalue(observed, null, alternative="greater")
0.2
>>> # Two-sided test
>>> shuffle_pvalue(observed, null, alternative="two-sided")
0.4
See Also

shuffle_zscore : Compute z-score from null distribution. ShuffleTestResult : Container for shuffle test results.

Source code in src/neurospatial/stats/shuffle.py
def shuffle_pvalue(
    observed: float,
    null_scores: NDArray[np.float64],
    *,
    alternative: Literal["greater", "less", "two-sided"] = "greater",
) -> float:
    """Compute Monte Carlo p-value with Phipson-Smyth correction.

    Computes the probability of observing a score at least as extreme as
    the observed value under the null distribution using the formula
    (k + 1) / (n + 1). Counting the observed data as one draw from the null
    makes the p-value valid (never anti-conservative) and never zero.

    Parameters
    ----------
    observed : float
        The observed score from the original (non-shuffled) data. Must be
        finite.
    null_scores : NDArray[np.float64]
        Array of scores from shuffled data, forming the null distribution.
    alternative : {"greater", "less", "two-sided"}, default="greater"
        Direction of the test:

        - "greater": Tests if observed is significantly greater than null
          (counts null >= observed).
        - "less": Tests if observed is significantly less than null
          (counts null <= observed).
        - "two-sided": Tests if observed is significantly different from
          null in either direction. Computed as 2 * min(p_greater, p_less),
          capped at 1.0.

    Returns
    -------
    float
        The Monte Carlo p-value in the range (0, 1].

    Raises
    ------
    ValueError
        If ``observed`` is not finite, ``alternative`` is unknown, or no null score
        is defined (all NaN or empty).

    Notes
    -----
    The Phipson-Smyth correction (k + 1) / (n + 1) ensures that:

    1. The p-value is never exactly zero, which is important for downstream
       corrections (e.g., Bonferroni, FDR).
    2. P(p <= alpha) <= alpha under the null: the test is valid, and
       slightly conservative as an estimate of the exact permutation p-value.

    For replay analysis, "greater" is typically used because we expect
    significant sequences to have higher scores than shuffled controls.

    NaN null scores (shuffles whose score is undefined) are dropped with a
    ``UserWarning`` and excluded from ``n``. Infinite null scores are
    defined, extreme scores and are counted like any other.

    References
    ----------
    .. [1] Phipson, B., & Smyth, G. K. (2010). Permutation P-values should
           never be zero: calculating exact P-values when permutations are
           randomly drawn. Statistical Applications in Genetics and Molecular
           Biology, 9(1).

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.shuffle import shuffle_pvalue

    >>> # Observed score higher than all null values
    >>> observed = 10.0
    >>> null = np.array([1.0, 2.0, 3.0, 4.0])
    >>> shuffle_pvalue(observed, null, alternative="greater")
    0.2

    >>> # Two-sided test
    >>> shuffle_pvalue(observed, null, alternative="two-sided")
    0.4

    See Also
    --------
    shuffle_zscore : Compute z-score from null distribution.
    ShuffleTestResult : Container for shuffle test results.
    """
    if not np.isfinite(observed):
        msg = (
            f"observed must be a finite value, got {observed!r}. A non-finite "
            "observed score makes all comparisons against the null False, which "
            "would silently return the floor p-value 1/(n+1)."
        )
        raise ValueError(msg)
    validate_choice(
        alternative, _ALTERNATIVES, name="alternative", owner="shuffle_pvalue()"
    )

    null_scores = np.asarray(null_scores, dtype=np.float64).ravel()
    undefined = np.isnan(null_scores)
    if undefined.all():
        msg = (
            "null_scores contains no defined (non-NaN) values; cannot compute a "
            "shuffle p-value. Check that the shuffle produced valid scores."
        )
        raise ValueError(msg)
    if undefined.any():
        warnings.warn(
            f"Dropped {int(undefined.sum())} undefined (NaN) null score(s) out "
            f"of {null_scores.size} before computing the p-value; it counts the "
            f"other {int((~undefined).sum())}.",
            category=UserWarning,
            stacklevel=_external_stacklevel(),
        )
    return float(_shuffle_p_values(observed, null_scores, alternative))

shuffle_spike_times_circular

shuffle_spike_times_circular(
    spike_times: NDArray[float64],
    windows: NDArray[float64],
    *,
    n_shuffles: int = 1000,
    min_shift: float = 20.0,
    rng: Generator | int | None = None,
) -> Generator[NDArray[np.float64], None, None]

Circularly shift spikes on the joined analyzed-time axis.

Join valid recording windows into one circular axis. Each draw adds one uniform offset in [min_shift, T-min_shift] to all retained spikes. Counts and circular spacings on that compressed clock are preserved; spikes never enter a recording gap. Physical spacings across removed gaps can differ.

Parameters:

Name Type Description Default
spike_times (ndarray, shape(n_spikes))

Spike timestamps in seconds. Spikes outside windows are dropped; a warning says so when every spike falls outside them.

required
windows (ndarray, shape(n_windows, 2))

Half-open analyzed recording windows in seconds, on the spike clock. The shared interval normalizer sorts and merges touching/overlapping rows.

required
n_shuffles int

Positive number of shifted trains to yield.

1000
min_shift float

Minimum offset in either direction, in seconds of analyzed time.

20.0
rng (Generator, int or None)

Random generator or reproducible integer seed.

None

Yields:

Type Description
(ndarray, shape(n_spikes_in_windows))

Sorted shifted spike times on the original recording clock.

Raises:

Type Description
ValueError

If windows/settings are invalid or analyzed time is not longer than twice min_shift.

Examples:

>>> import numpy as np
>>> from neurospatial.stats import shuffle_spike_times_circular
>>> draws = list(
...     shuffle_spike_times_circular(
...         np.array([1.0, 10.0, 205.0]),
...         np.array([[0.0, 100.0], [200.0, 300.0]]),
...         n_shuffles=3,
...         rng=7,
...     )
... )
>>> [len(train) for train in draws]
[3, 3, 3]
Source code in src/neurospatial/stats/shuffle.py
@reads_pynapple_samples
def shuffle_spike_times_circular(
    spike_times: NDArray[np.float64],
    windows: NDArray[np.float64],
    *,
    n_shuffles: int = 1000,
    min_shift: float = 20.0,
    rng: np.random.Generator | int | None = None,
) -> Generator[NDArray[np.float64], None, None]:
    """Circularly shift spikes on the joined analyzed-time axis.

    Join valid recording windows into one circular axis. Each draw adds one
    uniform offset in [min_shift, T-min_shift] to all retained spikes. Counts
    and circular spacings on that compressed clock are preserved; spikes never
    enter a recording gap. Physical spacings across removed gaps can differ.

    Parameters
    ----------
    spike_times : ndarray, shape (n_spikes,)
        Spike timestamps in seconds. Spikes outside windows are dropped; a
        warning says so when every spike falls outside them.
    windows : ndarray, shape (n_windows, 2)
        Half-open analyzed recording windows in seconds, on the spike clock.
        The shared interval normalizer sorts and merges touching/overlapping rows.
    n_shuffles : int, default=1000
        Positive number of shifted trains to yield.
    min_shift : float, default=20.0
        Minimum offset in either direction, in seconds of analyzed time.
    rng : numpy.random.Generator, int or None, default=None
        Random generator or reproducible integer seed.

    Yields
    ------
    ndarray, shape (n_spikes_in_windows,)
        Sorted shifted spike times on the original recording clock.

    Raises
    ------
    ValueError
        If windows/settings are invalid or analyzed time is not longer than
        twice min_shift.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats import shuffle_spike_times_circular
    >>> draws = list(
    ...     shuffle_spike_times_circular(
    ...         np.array([1.0, 10.0, 205.0]),
    ...         np.array([[0.0, 100.0], [200.0, 300.0]]),
    ...         n_shuffles=3,
    ...         rng=7,
    ...     )
    ... )
    >>> [len(train) for train in draws]
    [3, 3, 3]
    """
    _validate_circular_shift_settings(n_shuffles, min_shift)
    normalized, problems = _resolve_intervals(windows, "windows")
    if normalized is None:
        problem = (
            "; ".join(problems) or "windows must contain analyzed recording intervals"
        )
        raise ValueError(
            _format_error(
                f"shuffle_spike_times_circular: {problem}.",
                why="Why: circular shifting requires finite half-open analyzed-time windows with start < stop",
                fix="pass windows=np.array([[0.0, 100.0], [200.0, 300.0]]) in seconds",
            )
        )
    spike_times = _spike_train(spike_times, call="shuffle_spike_times_circular()")
    offsets = np.concatenate([[0.0], np.cumsum(normalized[:, 1] - normalized[:, 0])])
    total = float(offsets[-1])
    if total <= 2.0 * min_shift:
        raise ValueError(
            _format_error(
                f"Analyzed time is {total:.1f} s, not longer than 2 * min_shift = {2.0 * min_shift:.1f} s.",
                why="Why: no circular offset can move spikes by at least min_shift in both directions",
                fix=f"pass min_shift={total / 4:.1f}, or analyze a longer recording",
            )
        )
    idx = np.searchsorted(normalized[:, 0], spike_times, side="right") - 1
    inside = (idx >= 0) & (spike_times < normalized[np.maximum(idx, 0), 1])
    if spike_times.size and not inside.any():
        warnings.warn(
            f"shuffle_spike_times_circular: none of the {spike_times.size} spikes "
            f"falls inside the windows ([{normalized[0, 0]:g}, "
            f"{normalized[-1, 1]:g}) s), so every shuffle is empty. Check that "
            "spike_times and windows share a clock and units (seconds).",
            UserWarning,
            stacklevel=_external_stacklevel(),
        )
    idx = idx[inside]
    # Sorted, each shifted train is two sorted runs (see the draws).
    compressed = np.sort(offsets[idx] + (spike_times[inside] - normalized[idx, 0]))
    # Validation above runs at call time; only the draws are lazy.
    return _circular_shift_draws(
        compressed,
        normalized,
        offsets,
        total,
        n_shuffles=n_shuffles,
        min_shift=min_shift,
        generator=np.random.default_rng(rng),
    )

shuffle_spikes_isi

shuffle_spikes_isi(
    spike_times: NDArray[float64],
    *,
    n_shuffles: int = 1000,
    rng: Generator | int | None = None,
) -> Generator[NDArray[np.float64], None, None]

Shuffle inter-spike intervals to test ISI ordering significance.

Creates surrogate spike trains by randomly permuting the inter-spike intervals (ISIs). The first spike time is preserved, and ISIs are shuffled and cumulatively summed to create new spike times. This preserves the ISI distribution while destroying temporal correlations.

Parameters:

Name Type Description Default
spike_times (NDArray[float64], shape(n_spikes))

Sorted, finite spike times for a single neuron.

required
n_shuffles int

Number of shuffled versions to generate.

1000
rng Generator | int | None

Random number generator for reproducibility.

  • If Generator: Use directly
  • If int: Seed for np.random.default_rng()
  • If None: Use default RNG (not reproducible)
None

Yields:

Name Type Description
shuffled_times (NDArray[float64], shape(n_spikes))

Spike times with shuffled ISIs (same first spike time).

Raises:

Type Description
ValueError

If spike_times is not a sorted, finite 1-D array, or n_shuffles is not a positive integer.

Warns:

Type Description
UserWarning

With fewer than three spikes there is at most one ISI, so every shuffle equals the input.

Notes
  • Preserves the first spike time exactly
  • Preserves the ISI distribution (same ISI values, different order)
  • Preserves the last spike time, up to floating-point rounding
  • Destroys temporal correlations between consecutive ISIs
  • Output spike times are always sorted (monotonically increasing)
  • Useful for testing ISI-dependent effects (e.g., burst detection, adaptation)

Examples:

>>> import numpy as np
>>> from neurospatial.stats.shuffle import shuffle_spikes_isi
>>> spike_times = np.array([0.1, 0.15, 0.25, 0.4, 0.45, 0.7])
>>> for i, shuffled in enumerate(
...     shuffle_spikes_isi(spike_times, n_shuffles=3, rng=42)
... ):
...     print(
...         f"Shuffle {i}: first spike preserved = {shuffled[0] == spike_times[0]}"
...     )
Shuffle 0: first spike preserved = True
Shuffle 1: first spike preserved = True
Shuffle 2: first spike preserved = True
See Also

shuffle_time_bins : Shuffle temporal order of binned spike counts. generate_poisson_surrogates : Generate Poisson surrogate spike trains.

Source code in src/neurospatial/stats/shuffle.py
@reads_pynapple_samples
def shuffle_spikes_isi(
    spike_times: NDArray[np.float64],
    *,
    n_shuffles: int = 1000,
    rng: np.random.Generator | int | None = None,
) -> Generator[NDArray[np.float64], None, None]:
    """Shuffle inter-spike intervals to test ISI ordering significance.

    Creates surrogate spike trains by randomly permuting the inter-spike
    intervals (ISIs). The first spike time is preserved, and ISIs are
    shuffled and cumulatively summed to create new spike times. This
    preserves the ISI distribution while destroying temporal correlations.

    Parameters
    ----------
    spike_times : NDArray[np.float64], shape (n_spikes,)
        Sorted, finite spike times for a single neuron.
    n_shuffles : int, default=1000
        Number of shuffled versions to generate.
    rng : np.random.Generator | int | None, default=None
        Random number generator for reproducibility.

        - If Generator: Use directly
        - If int: Seed for ``np.random.default_rng()``
        - If None: Use default RNG (not reproducible)

    Yields
    ------
    shuffled_times : NDArray[np.float64], shape (n_spikes,)
        Spike times with shuffled ISIs (same first spike time).

    Raises
    ------
    ValueError
        If ``spike_times`` is not a sorted, finite 1-D array, or
        ``n_shuffles`` is not a positive integer.

    Warns
    -----
    UserWarning
        With fewer than three spikes there is at most one ISI, so every
        shuffle equals the input.

    Notes
    -----
    - Preserves the first spike time exactly
    - Preserves the ISI distribution (same ISI values, different order)
    - Preserves the last spike time, up to floating-point rounding
    - Destroys temporal correlations between consecutive ISIs
    - Output spike times are always sorted (monotonically increasing)
    - Useful for testing ISI-dependent effects (e.g., burst detection,
      adaptation)

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.shuffle import shuffle_spikes_isi

    >>> spike_times = np.array([0.1, 0.15, 0.25, 0.4, 0.45, 0.7])
    >>> for i, shuffled in enumerate(
    ...     shuffle_spikes_isi(spike_times, n_shuffles=3, rng=42)
    ... ):
    ...     print(
    ...         f"Shuffle {i}: first spike preserved = {shuffled[0] == spike_times[0]}"
    ...     )
    Shuffle 0: first spike preserved = True
    Shuffle 1: first spike preserved = True
    Shuffle 2: first spike preserved = True

    See Also
    --------
    shuffle_time_bins : Shuffle temporal order of binned spike counts.
    generate_poisson_surrogates : Generate Poisson surrogate spike trains.
    """
    spike_times = _spike_train(
        spike_times, call="shuffle_spikes_isi()", require_sorted=True
    )
    validate_draw_count(n_shuffles, name="n_shuffles", owner="shuffle_spikes_isi()")
    if spike_times.size < 3:
        warnings.warn(
            f"shuffle_spikes_isi: {spike_times.size} spike(s) give at most one "
            "inter-spike interval, so every shuffle equals the input.",
            UserWarning,
            stacklevel=_external_stacklevel(),
        )
    return _isi_permutations(spike_times, n_shuffles, np.random.default_rng(rng))

shuffle_time_bins

shuffle_time_bins(
    spike_counts: NDArray[int64],
    *,
    n_shuffles: int = 1000,
    rng: Generator | int | None = None,
) -> Generator[NDArray[np.int64], None, None]

Shuffle temporal order of time bins within an event.

Primary test for sequential structure. Disrupts temporal order while preserving instantaneous firing characteristics.

This shuffle randomly permutes the rows (time bins) of the spike count matrix. Each row is kept intact, so the spike counts per neuron per time bin are preserved, but the temporal sequence is destroyed.

Parameters:

Name Type Description Default
spike_counts (NDArray[int64], shape(n_time_bins, n_neurons))

Spike counts for a single candidate event (PBE/SWR).

required
n_shuffles int

Number of shuffled versions to generate.

1000
rng Generator | int | None

Random number generator for reproducibility.

  • If Generator: Use directly
  • If int: Seed for np.random.default_rng()
  • If None: Use default RNG (not reproducible)
None

Yields:

Name Type Description
shuffled_counts (NDArray[int64], shape(n_time_bins, n_neurons))

Spike counts with time bins in random order.

Raises:

Type Description
ValueError

If n_shuffles is not a positive integer.

Notes
  • Preserves spike counts per neuron per time bin
  • Preserves total spikes per neuron across event
  • Destroys temporal sequence information
  • Underpowered with very few time bins (<5)

Examples:

>>> import numpy as np
>>> from neurospatial.stats.shuffle import shuffle_time_bins
>>> spike_counts = np.array([[0, 1], [2, 0], [1, 1]], dtype=np.int64)
>>> for i, shuffled in enumerate(
...     shuffle_time_bins(spike_counts, n_shuffles=3, rng=42)
... ):
...     print(f"Shuffle {i}: shape={shuffled.shape}, sum={shuffled.sum()}")
Shuffle 0: shape=(3, 2), sum=5
Shuffle 1: shape=(3, 2), sum=5
Shuffle 2: shape=(3, 2), sum=5
Source code in src/neurospatial/stats/shuffle.py
def shuffle_time_bins(
    spike_counts: NDArray[np.int64],
    *,
    n_shuffles: int = 1000,
    rng: np.random.Generator | int | None = None,
) -> Generator[NDArray[np.int64], None, None]:
    """Shuffle temporal order of time bins within an event.

    **Primary test for sequential structure.** Disrupts temporal order while
    preserving instantaneous firing characteristics.

    This shuffle randomly permutes the rows (time bins) of the spike count
    matrix. Each row is kept intact, so the spike counts per neuron per
    time bin are preserved, but the temporal sequence is destroyed.

    Parameters
    ----------
    spike_counts : NDArray[np.int64], shape (n_time_bins, n_neurons)
        Spike counts for a single candidate event (PBE/SWR).
    n_shuffles : int, default=1000
        Number of shuffled versions to generate.
    rng : np.random.Generator | int | None, default=None
        Random number generator for reproducibility.

        - If Generator: Use directly
        - If int: Seed for ``np.random.default_rng()``
        - If None: Use default RNG (not reproducible)

    Yields
    ------
    shuffled_counts : NDArray[np.int64], shape (n_time_bins, n_neurons)
        Spike counts with time bins in random order.

    Raises
    ------
    ValueError
        If ``n_shuffles`` is not a positive integer.

    Notes
    -----
    - Preserves spike counts per neuron per time bin
    - Preserves total spikes per neuron across event
    - Destroys temporal sequence information
    - Underpowered with very few time bins (<5)

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.shuffle import shuffle_time_bins

    >>> spike_counts = np.array([[0, 1], [2, 0], [1, 1]], dtype=np.int64)
    >>> for i, shuffled in enumerate(
    ...     shuffle_time_bins(spike_counts, n_shuffles=3, rng=42)
    ... ):
    ...     print(f"Shuffle {i}: shape={shuffled.shape}, sum={shuffled.sum()}")
    Shuffle 0: shape=(3, 2), sum=5
    Shuffle 1: shape=(3, 2), sum=5
    Shuffle 2: shape=(3, 2), sum=5
    """
    validate_draw_count(n_shuffles, name="n_shuffles", owner="shuffle_time_bins()")
    return _row_permutations(
        np.asarray(spike_counts), n_shuffles, np.random.default_rng(rng)
    )

shuffle_trials

shuffle_trials(
    trial_labels: NDArray[int64],
    *,
    n_shuffles: int = 1000,
    rng: Generator | int | None = None,
) -> Generator[NDArray[np.int64], None, None]

Shuffle labels across trials to test trial identity significance.

A trial is a run of consecutive samples with the same label. Each shuffle permutes the labels among the trials and gives every sample its trial's new label, so each trial's samples stay together. Use it to test learning effects or trial-type differences: compute your statistic with the shuffled labels to build the null.

Parameters:

Name Type Description Default
trial_labels (NDArray[int64], shape(n_samples))

Label of the trial each sample (e.g., time point) belongs to, in time order. Labels can be trial IDs (0, 1, 2, ...) or trial types (e.g., 0 for left and 1 for right trials).

required
n_shuffles int

Number of shuffled versions to generate.

1000
rng Generator | int | None

Random number generator for reproducibility.

  • If Generator: Use directly
  • If int: Seed for np.random.default_rng()
  • If None: Use default RNG (not reproducible)
None

Yields:

Name Type Description
shuffled_labels (NDArray[int64], shape(n_samples))

Trial labels permuted across trials.

Raises:

Type Description
ValueError

If trial_labels is not 1-D or n_shuffles is not a positive integer.

Notes
  • Keeps each trial's samples together, so within-trial autocorrelation is preserved; permuting single samples would scatter every trial across time and make the null anti-conservative.
  • Preserves how many trials carry each label.
  • Trial lengths are not exchanged: a trial keeps its samples and takes another trial's label.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.shuffle import shuffle_trials
>>> trial_labels = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])
>>> for shuffled in shuffle_trials(trial_labels, n_shuffles=2, rng=42):
...     print(shuffled)
[2 2 2 1 1 1 0 0 0]
[0 0 0 2 2 2 1 1 1]
See Also

shuffle_time_bins : Shuffle temporal order of spike counts. neurospatial.replay.shuffle_cell_identity : Shuffle neuron-to-place-field mapping.

Source code in src/neurospatial/stats/shuffle.py
def shuffle_trials(
    trial_labels: NDArray[np.int64],
    *,
    n_shuffles: int = 1000,
    rng: np.random.Generator | int | None = None,
) -> Generator[NDArray[np.int64], None, None]:
    """Shuffle labels across trials to test trial identity significance.

    A trial is a run of consecutive samples with the same label. Each
    shuffle permutes the labels among the trials and gives every sample its
    trial's new label, so each trial's samples stay together. Use it to test
    learning effects or trial-type differences: compute your statistic with
    the shuffled labels to build the null.

    Parameters
    ----------
    trial_labels : NDArray[np.int64], shape (n_samples,)
        Label of the trial each sample (e.g., time point) belongs to, in time
        order. Labels can be trial IDs (0, 1, 2, ...) or trial types (e.g.,
        0 for left and 1 for right trials).
    n_shuffles : int, default=1000
        Number of shuffled versions to generate.
    rng : np.random.Generator | int | None, default=None
        Random number generator for reproducibility.

        - If Generator: Use directly
        - If int: Seed for ``np.random.default_rng()``
        - If None: Use default RNG (not reproducible)

    Yields
    ------
    shuffled_labels : NDArray[np.int64], shape (n_samples,)
        Trial labels permuted across trials.

    Raises
    ------
    ValueError
        If ``trial_labels`` is not 1-D or ``n_shuffles`` is not a positive
        integer.

    Notes
    -----
    - Keeps each trial's samples together, so within-trial autocorrelation
      is preserved; permuting single samples would scatter every trial
      across time and make the null anti-conservative.
    - Preserves how many trials carry each label.
    - Trial lengths are not exchanged: a trial keeps its samples and takes
      another trial's label.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.shuffle import shuffle_trials

    >>> trial_labels = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])
    >>> for shuffled in shuffle_trials(trial_labels, n_shuffles=2, rng=42):
    ...     print(shuffled)
    [2 2 2 1 1 1 0 0 0]
    [0 0 0 2 2 2 1 1 1]

    See Also
    --------
    shuffle_time_bins : Shuffle temporal order of spike counts.
    neurospatial.replay.shuffle_cell_identity : Shuffle neuron-to-place-field mapping.
    """
    trial_labels = np.asarray(trial_labels)
    if trial_labels.ndim != 1:
        raise ValueError(
            _format_error(
                f"trial_labels must be 1-D, got shape {trial_labels.shape}.",
                why="Why: trials are runs of consecutive samples with one label",
                fix="pass one label per sample, in time order",
            )
        )
    validate_draw_count(n_shuffles, name="n_shuffles", owner="shuffle_trials()")
    # Trial index of each sample: a new trial starts where the label changes.
    trial = np.concatenate([[0], np.cumsum(trial_labels[1:] != trial_labels[:-1])])
    run_labels = trial_labels[np.flatnonzero(np.diff(trial, prepend=-1))]
    return _relabeled_trials(run_labels, trial, n_shuffles, np.random.default_rng(rng))

shuffle_zscore

shuffle_zscore(observed: float, null_scores: NDArray[float64]) -> float

Compute z-score of observed value relative to null distribution.

Calculates the standard score: (observed - mean(null)) / std(null). Returns NaN if the null distribution has zero variance.

Parameters:

Name Type Description Default
observed float

The observed score from the original (non-shuffled) data.

required
null_scores NDArray[float64]

Array of scores from shuffled data, forming the null distribution.

required

Returns:

Type Description
float

The z-score (standard score). NaN if the defined null scores have zero variance, fewer than two are defined, or one is infinite (the mean and standard deviation are then undefined).

Notes

Undefined (NaN) null scores are left out of the mean and standard deviation, with a warning giving how many, as :func:shuffle_pvalue leaves them out of the p-value.

The z-score indicates how many standard deviations the observed value is from the mean of the null distribution. Positive values indicate the observed is above the null mean; negative values indicate below.

Common interpretation thresholds:

  • |z| > 1.96: Approximately p < 0.05 (two-tailed) if null is normal
  • |z| > 2.58: Approximately p < 0.01 (two-tailed) if null is normal
  • |z| > 3.0: Strong evidence against null hypothesis

Unlike p-values, z-scores are useful for comparing effect sizes across different analyses.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.shuffle import shuffle_zscore
>>> null = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
>>> observed = 5.0
>>> z = shuffle_zscore(observed, null)
>>> bool(np.isclose(z, (5.0 - 3.0) / np.std(null)))
True
>>> # Zero variance returns NaN
>>> shuffle_zscore(5.0, np.array([3.0, 3.0, 3.0]))
nan
See Also

shuffle_pvalue : Compute Monte Carlo p-value from null distribution. ShuffleTestResult : Container for shuffle test results.

Source code in src/neurospatial/stats/shuffle.py
def shuffle_zscore(
    observed: float,
    null_scores: NDArray[np.float64],
) -> float:
    """Compute z-score of observed value relative to null distribution.

    Calculates the standard score: (observed - mean(null)) / std(null).
    Returns NaN if the null distribution has zero variance.

    Parameters
    ----------
    observed : float
        The observed score from the original (non-shuffled) data.
    null_scores : NDArray[np.float64]
        Array of scores from shuffled data, forming the null distribution.

    Returns
    -------
    float
        The z-score (standard score). NaN if the defined null scores have
        zero variance, fewer than two are defined, or one is infinite (the
        mean and standard deviation are then undefined).

    Notes
    -----
    Undefined (NaN) null scores are left out of the mean and standard
    deviation, with a warning giving how many, as
    :func:`shuffle_pvalue` leaves them out of the p-value.

    The z-score indicates how many standard deviations the observed value
    is from the mean of the null distribution. Positive values indicate
    the observed is above the null mean; negative values indicate below.

    Common interpretation thresholds:

    - |z| > 1.96: Approximately p < 0.05 (two-tailed) if null is normal
    - |z| > 2.58: Approximately p < 0.01 (two-tailed) if null is normal
    - |z| > 3.0: Strong evidence against null hypothesis

    Unlike p-values, z-scores are useful for comparing effect sizes across
    different analyses.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.shuffle import shuffle_zscore

    >>> null = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
    >>> observed = 5.0
    >>> z = shuffle_zscore(observed, null)
    >>> bool(np.isclose(z, (5.0 - 3.0) / np.std(null)))
    True

    >>> # Zero variance returns NaN
    >>> shuffle_zscore(5.0, np.array([3.0, 3.0, 3.0]))
    nan

    See Also
    --------
    shuffle_pvalue : Compute Monte Carlo p-value from null distribution.
    ShuffleTestResult : Container for shuffle test results.
    """
    null_scores = np.asarray(null_scores, dtype=np.float64).ravel()
    undefined = np.isnan(null_scores)
    if undefined.any():
        warnings.warn(
            f"Dropped {int(undefined.sum())} undefined (NaN) null score(s) out "
            f"of {null_scores.size} before computing the z-score; it uses the "
            f"other {int((~undefined).sum())}.",
            category=UserWarning,
            stacklevel=_external_stacklevel(),
        )
    return _shuffle_zscore(observed, null_scores)

generate_inhomogeneous_poisson_surrogates

generate_inhomogeneous_poisson_surrogates(
    spike_counts: NDArray[int64],
    *,
    smooth_bins: int = 3,
    n_surrogates: int = 1000,
    rng: Generator | int | None = None,
) -> Generator[NDArray[np.int64], None, None]

Generate inhomogeneous Poisson surrogate spike trains with smoothed rates.

Creates surrogate spike counts by sampling from Poisson distributions with time-varying rates estimated from smoothed spike counts. This preserves slow rate fluctuations while destroying fine temporal structure.

Tests that structure exceeds time-varying rate expectations. More conservative than homogeneous surrogates: it keeps slow rate modulation, so it tests for structure beyond it.

Parameters:

Name Type Description Default
spike_counts (NDArray[int64], shape(n_time_bins, n_neurons))

Original spike counts per neuron per time bin.

required
smooth_bins int

Size of the uniform smoothing window (in time bins) applied to estimate time-varying rates. Larger values preserve less temporal detail (closer to homogeneous). Must be at least 1.

3
n_surrogates int

Number of surrogate spike trains to generate.

1000
rng Generator | int | None

Random number generator for reproducibility.

  • If Generator: Use directly
  • If int: Seed for np.random.default_rng()
  • If None: Use default RNG (not reproducible)
None

Yields:

Name Type Description
surrogate (NDArray[int64], shape(n_time_bins, n_neurons))

Surrogate spike counts sampled from time-varying Poisson distributions.

Notes
  • Uses uniform 1D filter to smooth spike counts in time
  • Smoothed counts are used as time-varying Poisson rate parameters
  • Preserves slow rate fluctuations (e.g., event onsets)
  • Destroys fine temporal correlations and millisecond-scale patterns
  • More appropriate than homogeneous surrogates when rate modulation is a confound (e.g., ramping activity during replay events)

Raises:

Type Description
ValueError

If spike_counts is not a 2-D array of non-negative whole-number counts, smooth_bins is not a positive integer, or n_surrogates is not a positive integer.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.surrogates import (
...     generate_inhomogeneous_poisson_surrogates,
... )
>>> spike_counts = np.array(
...     [[0, 1], [2, 2], [3, 3], [2, 2], [1, 1]], dtype=np.int64
... )
>>> for i, surrogate in enumerate(
...     generate_inhomogeneous_poisson_surrogates(
...         spike_counts, smooth_bins=3, n_surrogates=3, rng=42
...     )
... ):
...     print(f"Surrogate {i}: shape={surrogate.shape}")
Surrogate 0: shape=(5, 2)
Surrogate 1: shape=(5, 2)
Surrogate 2: shape=(5, 2)
See Also

generate_poisson_surrogates : Homogeneous Poisson surrogates generate_jittered_spikes : Temporal jitter surrogates

Source code in src/neurospatial/stats/surrogates.py
def generate_inhomogeneous_poisson_surrogates(
    spike_counts: NDArray[np.int64],
    *,
    smooth_bins: int = 3,
    n_surrogates: int = 1000,
    rng: np.random.Generator | int | None = None,
) -> Generator[NDArray[np.int64], None, None]:
    """Generate inhomogeneous Poisson surrogate spike trains with smoothed rates.

    Creates surrogate spike counts by sampling from Poisson distributions
    with time-varying rates estimated from smoothed spike counts. This
    preserves slow rate fluctuations while destroying fine temporal structure.

    **Tests that structure exceeds time-varying rate expectations.** More
    conservative than homogeneous surrogates: it keeps slow rate modulation,
    so it tests for structure beyond it.

    Parameters
    ----------
    spike_counts : NDArray[np.int64], shape (n_time_bins, n_neurons)
        Original spike counts per neuron per time bin.
    smooth_bins : int, default=3
        Size of the uniform smoothing window (in time bins) applied to
        estimate time-varying rates. Larger values preserve less temporal
        detail (closer to homogeneous). Must be at least 1.
    n_surrogates : int, default=1000
        Number of surrogate spike trains to generate.
    rng : np.random.Generator | int | None, default=None
        Random number generator for reproducibility.

        - If Generator: Use directly
        - If int: Seed for ``np.random.default_rng()``
        - If None: Use default RNG (not reproducible)

    Yields
    ------
    surrogate : NDArray[np.int64], shape (n_time_bins, n_neurons)
        Surrogate spike counts sampled from time-varying Poisson distributions.

    Notes
    -----
    - Uses uniform 1D filter to smooth spike counts in time
    - Smoothed counts are used as time-varying Poisson rate parameters
    - Preserves slow rate fluctuations (e.g., event onsets)
    - Destroys fine temporal correlations and millisecond-scale patterns
    - More appropriate than homogeneous surrogates when rate modulation
      is a confound (e.g., ramping activity during replay events)

    Raises
    ------
    ValueError
        If ``spike_counts`` is not a 2-D array of non-negative whole-number
        counts, ``smooth_bins`` is not a positive integer, or
        ``n_surrogates`` is not a positive integer.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.surrogates import (
    ...     generate_inhomogeneous_poisson_surrogates,
    ... )

    >>> spike_counts = np.array(
    ...     [[0, 1], [2, 2], [3, 3], [2, 2], [1, 1]], dtype=np.int64
    ... )
    >>> for i, surrogate in enumerate(
    ...     generate_inhomogeneous_poisson_surrogates(
    ...         spike_counts, smooth_bins=3, n_surrogates=3, rng=42
    ...     )
    ... ):
    ...     print(f"Surrogate {i}: shape={surrogate.shape}")
    Surrogate 0: shape=(5, 2)
    Surrogate 1: shape=(5, 2)
    Surrogate 2: shape=(5, 2)

    See Also
    --------
    generate_poisson_surrogates : Homogeneous Poisson surrogates
    generate_jittered_spikes : Temporal jitter surrogates
    """
    from scipy.ndimage import uniform_filter1d

    counts = _validated_counts(spike_counts)
    validate_integer_at_least(
        smooth_bins,
        1,
        name="smooth_bins",
        owner="generate_inhomogeneous_poisson_surrogates()",
        hint="it is the smoothing window length in time bins, e.g. 3",
    )
    validate_draw_count(
        n_surrogates,
        name="n_surrogates",
        owner="generate_inhomogeneous_poisson_surrogates()",
    )
    # Time-varying Poisson means: counts smoothed along time, edges extended.
    lam = (
        uniform_filter1d(counts, size=smooth_bins, axis=0, mode="nearest")
        if len(counts)
        else counts
    )
    return _poisson_draws(lam, n_surrogates, np.random.default_rng(rng))

generate_jittered_spikes

generate_jittered_spikes(
    spike_times: NDArray[float64],
    *,
    jitter_std: float,
    n_surrogates: int = 1000,
    rng: Generator | int | None = None,
    window: tuple[float, float] | None = None,
) -> Generator[NDArray[np.float64], None, None]

Generate temporally jittered surrogate spike trains.

Creates surrogate spike trains by adding Gaussian noise to each spike time. This tests whether precise spike timing is significant while preserving the approximate temporal distribution of spikes.

Tests that precise spike timing matters. If observed effects depend on exact spike times, jittered surrogates should produce weaker effects.

Parameters:

Name Type Description Default
spike_times (NDArray[float64], shape(n_spikes))

Finite spike times for a single neuron.

required
jitter_std float

Standard deviation of the Gaussian jitter added to each spike time. Must be positive; units should match spike_times (typically seconds).

required
n_surrogates int

Number of surrogate spike trains to generate.

1000
rng Generator | int | None

Random number generator for reproducibility.

  • If Generator: Use directly
  • If int: Seed for np.random.default_rng()
  • If None: Use default RNG (not reproducible)
None
window tuple[float, float] | None

Half-open recording window [start, stop) the jittered spikes must stay in. Each spike's jitter is then drawn from the Gaussian truncated to the window, as if out-of-window draws were redrawn, so no spikes pile up at the edges. Every spike must lie inside it.

None

Yields:

Name Type Description
jittered_times (NDArray[float64], shape(n_spikes))

Spike times with Gaussian jitter applied (sorted).

Notes
  • Each spike is independently jittered by adding Gaussian noise
  • Output spike times are always sorted (monotonically increasing)
  • Preserves the number of spikes exactly
  • Preserves approximate temporal distribution at scales > jitter_std
  • Destroys precise timing relationships at scales < jitter_std
  • Useful for testing phase locking, synchrony, or sequence timing

Raises:

Type Description
ValueError

If spike_times is not a finite 1-D array, jitter_std is not positive and finite, n_surrogates is not a positive integer, or window is not a finite (start, stop) with start < stop that contains every spike.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.surrogates import generate_jittered_spikes
>>> spike_times = np.array([0.1, 0.15, 0.25, 0.4, 0.45, 0.7])
>>> for i, jittered in enumerate(
...     generate_jittered_spikes(
...         spike_times, jitter_std=0.01, n_surrogates=3, rng=42
...     )
... ):
...     print(f"Surrogate {i}: n_spikes={len(jittered)}")
Surrogate 0: n_spikes=6
Surrogate 1: n_spikes=6
Surrogate 2: n_spikes=6
See Also

generate_poisson_surrogates : Rate-matched surrogates (destroys all timing) neurospatial.stats.shuffle.shuffle_spikes_isi : ISI-preserving shuffle

Source code in src/neurospatial/stats/surrogates.py
@reads_pynapple_samples
def generate_jittered_spikes(
    spike_times: NDArray[np.float64],
    *,
    jitter_std: float,
    n_surrogates: int = 1000,
    rng: np.random.Generator | int | None = None,
    window: tuple[float, float] | None = None,
) -> Generator[NDArray[np.float64], None, None]:
    """Generate temporally jittered surrogate spike trains.

    Creates surrogate spike trains by adding Gaussian noise to each spike
    time. This tests whether precise spike timing is significant while
    preserving the approximate temporal distribution of spikes.

    **Tests that precise spike timing matters.** If observed effects depend
    on exact spike times, jittered surrogates should produce weaker effects.

    Parameters
    ----------
    spike_times : NDArray[np.float64], shape (n_spikes,)
        Finite spike times for a single neuron.
    jitter_std : float
        Standard deviation of the Gaussian jitter added to each spike time.
        Must be positive; units should match spike_times (typically seconds).
    n_surrogates : int, default=1000
        Number of surrogate spike trains to generate.
    rng : np.random.Generator | int | None, default=None
        Random number generator for reproducibility.

        - If Generator: Use directly
        - If int: Seed for ``np.random.default_rng()``
        - If None: Use default RNG (not reproducible)
    window : tuple[float, float] | None, default=None
        Half-open recording window ``[start, stop)`` the jittered spikes must
        stay in. Each spike's jitter is then drawn from the Gaussian
        truncated to the window, as if out-of-window draws were redrawn, so
        no spikes pile up at the edges. Every spike must lie inside it.

    Yields
    ------
    jittered_times : NDArray[np.float64], shape (n_spikes,)
        Spike times with Gaussian jitter applied (sorted).

    Notes
    -----
    - Each spike is independently jittered by adding Gaussian noise
    - Output spike times are always sorted (monotonically increasing)
    - Preserves the number of spikes exactly
    - Preserves approximate temporal distribution at scales > jitter_std
    - Destroys precise timing relationships at scales < jitter_std
    - Useful for testing phase locking, synchrony, or sequence timing

    Raises
    ------
    ValueError
        If ``spike_times`` is not a finite 1-D array, ``jitter_std`` is not
        positive and finite, ``n_surrogates`` is not a positive integer, or
        ``window`` is not a finite ``(start, stop)`` with start < stop that
        contains every spike.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.surrogates import generate_jittered_spikes

    >>> spike_times = np.array([0.1, 0.15, 0.25, 0.4, 0.45, 0.7])
    >>> for i, jittered in enumerate(
    ...     generate_jittered_spikes(
    ...         spike_times, jitter_std=0.01, n_surrogates=3, rng=42
    ...     )
    ... ):
    ...     print(f"Surrogate {i}: n_spikes={len(jittered)}")
    Surrogate 0: n_spikes=6
    Surrogate 1: n_spikes=6
    Surrogate 2: n_spikes=6

    See Also
    --------
    generate_poisson_surrogates : Rate-matched surrogates (destroys all timing)
    neurospatial.stats.shuffle.shuffle_spikes_isi : ISI-preserving shuffle
    """
    spike_times = _spike_train(spike_times, call="generate_jittered_spikes()")
    if not (np.isfinite(jitter_std) and jitter_std > 0):
        raise ValueError(
            _format_error(
                f"jitter_std={jitter_std!r} must be positive and finite.",
                why="Why: it is the standard deviation of the timing noise",
                fix="pass jitter_std in the units of spike_times, e.g. 0.01 s",
            )
        )
    validate_draw_count(
        n_surrogates, name="n_surrogates", owner="generate_jittered_spikes()"
    )
    if window is not None:
        start, stop = (float(v) for v in window)
        outside = (spike_times < start) | (spike_times >= stop)
        if not (np.isfinite(start) and np.isfinite(stop) and start < stop) or (
            outside.any()
        ):
            raise ValueError(
                _format_error(
                    f"window={window!r} must be a finite (start, stop) with "
                    f"start < stop that contains every spike; "
                    f"{int(outside.sum())} spike(s) fall outside it.",
                    why="Why: jittered spikes are kept inside the window, so "
                    "spikes must start there",
                    fix="drop spikes outside the recording window first, or "
                    "pass the window the spikes were recorded in",
                )
            )
        window = (start, stop)
    return _jitter_draws(
        spike_times, jitter_std, window, n_surrogates, np.random.default_rng(rng)
    )

generate_poisson_surrogates

generate_poisson_surrogates(
    spike_counts: NDArray[int64],
    *,
    n_surrogates: int = 1000,
    rng: Generator | int | None = None,
) -> Generator[NDArray[np.int64], None, None]

Generate homogeneous Poisson surrogate spike trains.

Creates surrogate spike counts by sampling from Poisson distributions with rates equal to the mean firing rate of each neuron across all time bins. This destroys all temporal structure while preserving average rates.

Tests that observed structure exceeds rate-based expectations. If sequential decoding patterns are significant, they should score higher than patterns from rate-matched surrogates.

Parameters:

Name Type Description Default
spike_counts (NDArray[int64], shape(n_time_bins, n_neurons))

Original spike counts per neuron per time bin.

required
n_surrogates int

Number of surrogate spike trains to generate.

1000
rng Generator | int | None

Random number generator for reproducibility.

  • If Generator: Use directly
  • If int: Seed for np.random.default_rng()
  • If None: Use default RNG (not reproducible)
None

Yields:

Name Type Description
surrogate (NDArray[int64], shape(n_time_bins, n_neurons))

Surrogate spike counts sampled from Poisson distributions.

Notes
  • Computes mean spike count per neuron across all time bins
  • Each time bin independently samples from Poisson(mean_count_per_neuron)
  • Destroys all temporal correlations and patterns
  • Preserves mean firing rates per neuron (statistically)
  • The least conservative null here: it removes all structure except each neuron's mean count, so beating it only rules out a constant-rate explanation.

Raises:

Type Description
ValueError

If spike_counts is not a 2-D array of non-negative whole-number counts, or n_surrogates is not a positive integer.

Examples:

>>> import numpy as np
>>> from neurospatial.stats.surrogates import generate_poisson_surrogates
>>> spike_counts = np.array([[0, 1], [2, 0], [1, 1]], dtype=np.int64)
>>> for i, surrogate in enumerate(
...     generate_poisson_surrogates(spike_counts, n_surrogates=3, rng=42)
... ):
...     print(f"Surrogate {i}: shape={surrogate.shape}")
Surrogate 0: shape=(3, 2)
Surrogate 1: shape=(3, 2)
Surrogate 2: shape=(3, 2)
See Also

generate_inhomogeneous_poisson_surrogates : Time-varying rate surrogates generate_jittered_spikes : Temporal jitter surrogates

Source code in src/neurospatial/stats/surrogates.py
def generate_poisson_surrogates(
    spike_counts: NDArray[np.int64],
    *,
    n_surrogates: int = 1000,
    rng: np.random.Generator | int | None = None,
) -> Generator[NDArray[np.int64], None, None]:
    """Generate homogeneous Poisson surrogate spike trains.

    Creates surrogate spike counts by sampling from Poisson distributions
    with rates equal to the mean firing rate of each neuron across all time
    bins. This destroys all temporal structure while preserving average rates.

    **Tests that observed structure exceeds rate-based expectations.** If
    sequential decoding patterns are significant, they should score higher
    than patterns from rate-matched surrogates.

    Parameters
    ----------
    spike_counts : NDArray[np.int64], shape (n_time_bins, n_neurons)
        Original spike counts per neuron per time bin.
    n_surrogates : int, default=1000
        Number of surrogate spike trains to generate.
    rng : np.random.Generator | int | None, default=None
        Random number generator for reproducibility.

        - If Generator: Use directly
        - If int: Seed for ``np.random.default_rng()``
        - If None: Use default RNG (not reproducible)

    Yields
    ------
    surrogate : NDArray[np.int64], shape (n_time_bins, n_neurons)
        Surrogate spike counts sampled from Poisson distributions.

    Notes
    -----
    - Computes mean spike count per neuron across all time bins
    - Each time bin independently samples from Poisson(mean_count_per_neuron)
    - Destroys all temporal correlations and patterns
    - Preserves mean firing rates per neuron (statistically)
    - The least conservative null here: it removes all structure except each
      neuron's mean count, so beating it only rules out a constant-rate
      explanation.

    Raises
    ------
    ValueError
        If ``spike_counts`` is not a 2-D array of non-negative whole-number
        counts, or ``n_surrogates`` is not a positive integer.

    Examples
    --------
    >>> import numpy as np
    >>> from neurospatial.stats.surrogates import generate_poisson_surrogates

    >>> spike_counts = np.array([[0, 1], [2, 0], [1, 1]], dtype=np.int64)
    >>> for i, surrogate in enumerate(
    ...     generate_poisson_surrogates(spike_counts, n_surrogates=3, rng=42)
    ... ):
    ...     print(f"Surrogate {i}: shape={surrogate.shape}")
    Surrogate 0: shape=(3, 2)
    Surrogate 1: shape=(3, 2)
    Surrogate 2: shape=(3, 2)

    See Also
    --------
    generate_inhomogeneous_poisson_surrogates : Time-varying rate surrogates
    generate_jittered_spikes : Temporal jitter surrogates
    """
    counts = _validated_counts(spike_counts)
    validate_draw_count(
        n_surrogates, name="n_surrogates", owner="generate_poisson_surrogates()"
    )
    # Each (time_bin, neuron) pair samples Poisson(mean count of its neuron).
    lam = np.broadcast_to(counts.mean(axis=0) if len(counts) else 0.0, counts.shape)
    return _poisson_draws(lam, n_surrogates, np.random.default_rng(rng))