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
¶
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 |
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)
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 |
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 |
None
|
statistic_units
|
str or None
|
Unit of the score, such as |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
z_score |
float
|
Standard score of the observed score against the null scores, from
:func: |
n_shuffles |
int
|
Number of shuffles performed, |
n_shuffles_used |
int
|
Shuffles with a defined (non-NaN) score, the n of the p-value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> 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¶
n_shuffles
property
¶
Shuffles performed, len(null_scores), including undefined ones.
n_shuffles_used
property
¶
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;
|
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: |
"greater"
|
statistic
|
str or None
|
Name of the score. |
None
|
statistic_units
|
str or None
|
Unit of the score; |
None
|
Returns:
| Type | Description |
|---|---|
ShuffleTestResult
|
The p-value of :func: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
is_significant
¶
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 |
Source code in src/neurospatial/stats/shuffle.py
summary
¶
Flat dict of scalar headline metrics for this result.
Source code in src/neurospatial/stats/shuffle.py
plot
¶
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:
>>> 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
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:
|
required |
angle_unit
|
('rad', 'deg')
|
Unit of input angles. Use |
'rad'
|
Returns:
| Type | Description |
|---|---|
CircularBasisResult
|
Result object containing:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 | |
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
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
See Also
circular_basis : Create design matrix for GLM.
Notes
Interpretation (log link, as in a Poisson GLM):
- the rate peaks at
phaseand is lowest opposite it; the peak-to-trough rate ratio isexp(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
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 | |
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 | |
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
|
pval |
float
|
P-value from the large-sample chi-squared approximation (see Notes).
NaN when |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 | |
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 |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Circular mean in radians, range [-π, π], whatever |
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
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 |
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
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
|
0.2
|
Returns:
| Type | Description |
|---|---|
bool
|
True if BOTH:
- p-value < alpha (statistically significant)
- magnitude >= min_magnitude (practically meaningful)
False otherwise, including when |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 | |
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 |
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
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
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 |
None
|
rates
|
(array, shape(n_bins))
|
Firing rate or response in each bin.
Required if |
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
|
0.0
|
cov_matrix
|
(ndarray, shape(3, 3) or (2, 2))
|
Covariance of the GLM coefficients, required if |
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 |
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 |
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 |
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
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 | |
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 |
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 |
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
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 | |
wrap_angle
¶
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
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"
|
Returns:
| Type | Description |
|---|---|
float
|
The Monte Carlo p-value in the range (0, 1]. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
The Phipson-Smyth correction (k + 1) / (n + 1) ensures that:
- The p-value is never exactly zero, which is important for downstream corrections (e.g., Bonferroni, FDR).
- 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:
>>> # 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
See Also
shuffle_zscore : Compute z-score from null distribution. ShuffleTestResult : Container for shuffle test results.
Source code in src/neurospatial/stats/shuffle.py
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 | |
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
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
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.
|
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 |
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:
>>> 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
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 | |
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.
|
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 |
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:
>>> 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
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.
|
None
|
Yields:
| Name | Type | Description |
|---|---|---|
shuffled_labels |
(NDArray[int64], shape(n_samples))
|
Trial labels permuted across trials. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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:
>>> 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
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 | |
shuffle_zscore
¶
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:
>>> 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
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
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.
|
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 |
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
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | |
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.
|
None
|
window
|
tuple[float, float] | None
|
Half-open recording window |
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 |
Examples:
>>> 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
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | |
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.
|
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 |
Examples:
>>> 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