Skip to content

synaptome.engine

synaptome.engine

Array maths: hypothesis tests, estimators and effect sizes, analytic and bootstrap confidence intervals, multiple-comparison correction, effective sample size and cluster permutation, all on plain NumPy arrays. Everything here works without a Study.

ClusterStatResult dataclass

Outcome of one cluster permutation test.

Attributes:

Name Type Description
t_obs np.ndarray of shape (n_coords,)

Observed t statistic at each coordinate (paired: one-sample t of the differences; independent: Student t). Positive means the first sample is larger.

clusters tuple[tuple[int, int], ...]

(start, stop) index ranges (stop excluded) of the clusters found, in coordinate order.

masses ndarray

Each cluster's mass, the sum of its t values (signed).

p_values ndarray

Each cluster's p-value against the permutation distribution of the largest mass.

threshold float

Cluster-forming threshold on |t| (or on t / -t for one tail).

null np.ndarray of shape (n_permutations,)

Largest cluster mass of each permutation (0 when a permutation forms no cluster).

n_permutations int

Permutations actually used.

exact bool

True when every sign flip / relabelling was enumerated, which makes the p-values exact.

paired bool
tail int

0 (two-sided), 1 (first sample larger) or -1 (first sample smaller).

n int

Units used (after dropping rows with a NaN).

group_sizes tuple[int, int] | None

Independent only: units in each sample.

StatResult dataclass

Outcome of one hypothesis test.

Attributes:

Name Type Description
test str

Name of the test that was run.

statistic, p_value float

NaN when the test couldn't be run (e.g. too few observations).

n int

Observations actually used: pairs for paired tests (after dropping NaNs, and zero differences for Wilcoxon), subjects for repeated- measures omnibus tests, total observations otherwise.

effect_size float

NaN for tests without a natural effect size (normality tests).

effect_size_type str | None

e.g. "cohens_dz", "rank_biserial", "kendalls_w".

group_sizes tuple[int, ...] | None

Per-group sizes for independent-samples tests.

df float | tuple[float, float] | None

Degrees of freedom, for t- and F-tests.

n_eff float | None

Effective sample size, for paired_test(..., test="ttest_ess").

alternative str

"two-sided", "greater" or "less".

offset float

The difference tested against: the null hypothesis is first - second = offset.

zero_method str | None

How the Wilcoxon test treated zero differences; None for other tests.

to_dict()

The result as a plain dict.

bootstrap_bias(draws, estimate)

How far the bootstrap draws sit from the estimate.

Technical details

A bias above about a quarter of the standard error matters for the interval (Efron & Tibshirani, 1993, ch. 10): the percentile interval then lands about twice the bias off, towards where the draws lean. The basic and BCa intervals correct for it.

Returns:

Type Description
dict
  • bias: mean draw minus the estimate;
  • se: standard deviation of the draws (ddof=1);
  • bias_se_ratio: bias / se;
  • z0: the BCa bias correction, Phi^-1 of the share of draws below the estimate (ties counting half): 0 when the draws are median-unbiased, ±inf when all lie on one side.

Infinite draws are left out of bias and se; entries are NaN without two finite draws.

bootstrap_ci(statistic, *samples, paired=False, level=0.95, n_boot=2000, interval='bca', seed=None, draws=None, acceleration=None)

Bootstrap confidence interval of statistic(*samples) in one call: draws (bootstrap_draws), then the interval (bootstrap_interval).

Example: bootstrap_ci(hedges_g, a, b) or bootstrap_ci(cohens_dz, x, y, paired=True).

Parameters:

Name Type Description Default
statistic Callable[..., float]

Called as statistic(*samples), must return a float.

required
*samples ArrayLike

One or more 1-D samples.

()
paired bool

Resample all samples together (default False).

False
level float

Confidence level (default 0.95).

0.95
n_boot int

Number of resamples (default 2000). Unused with draws.

2000
interval str

"bca" (default), "percentile" or "basic" (see bootstrap_interval).

'bca'
seed int | Generator | None

For reproducible intervals.

None
draws ArrayLike | None

Pre-computed draws of the statistic (e.g. resampled upstream) to read the interval from instead of resampling samples.

None
acceleration float | None

BCa only. Defaults to the jackknife acceleration of samples, or to 0 (the "BC" interval) when draws are given, since those need not come from resampling samples.

None

Returns:

Type Description
(low, high): tuple[float, float]

(nan, nan) if the statistic is NaN on the original samples.

bootstrap_draws(statistic, *samples, paired=False, n_boot=2000, seed=None)

The bootstrap distribution of statistic(*samples): its value on n_boot resamples drawn with replacement.

Technical details

With paired=True every sample is resampled with the same indices, so pairs stay together (all samples must have the same length). Otherwise each sample is resampled on its own, keeping its size. NaNs in the samples are not dropped here: statistic decides (every function in synaptome.engine drops them).

Parameters:

Name Type Description Default
statistic Callable[..., float]

Called as statistic(*resampled_samples), must return a float.

required
*samples ArrayLike

One or more 1-D samples.

()
paired bool

Resample all samples together (default False).

False
n_boot int

Number of resamples (default 2000).

2000
seed int | Generator | None

For reproducible draws; a Generator is used as-is.

None

Returns:

Type Description
np.ndarray of shape (n_boot,)

NaN where statistic has no value on a resample.

bootstrap_interval(draws, estimate=None, level=0.95, interval='percentile', acceleration=0.0)

Confidence interval read from bootstrap draws.

  • "percentile": the alpha/2 and 1 - alpha/2 quantiles of the draws.
  • "basic": [2 * estimate - q_high, 2 * estimate - q_low], the percentile interval of the draws reflected around the estimate.
  • "bca": the quantiles at the levels Phi(z0 + (z0 + z) / (1 - a (z0 + z))), with the bias correction z0 (see bootstrap_bias) and the acceleration a (0 gives the bias-corrected "BC" interval).

Technical details

The percentile interval assumes the draws are median-unbiased; if they lean away from the estimate, it lands about twice the bias off. The basic interval corrects for that bias (Davison & Hinkley, 1997, ch. 5); BCa corrects for the bias and for a skew that changes with the parameter (Efron & Tibshirani, 1993, ch. 14). Basic and BCa suit unbounded, additive quantities only (a reflected odds ratio can be negative). Quantiles are order statistics (the draw just below / above), so infinite draws stay well defined. BCa warns (RuntimeWarning) when an adjusted level falls outside [1/n, 1 - 1/n] for n draws, where that end is just the extreme draw, and when every draw lies on one side of the estimate.

Parameters:

Name Type Description Default
draws ArrayLike

The bootstrap distribution; NaN draws are ignored.

required
estimate float | None

The point estimate; required for "basic" and "bca".

None
level float

Confidence level (default 0.95).

0.95
interval str

"percentile" (default), "basic" or "bca".

'percentile'
acceleration float

"bca" only (see jackknife_acceleration).

0.0

Returns:

Type Description
(low, high): tuple[float, float]

NaNs without any valid draw (or, for BCa, when every draw lies on one side of the estimate).

bootstrap_pvalue(draws, null=0.0, alternative='two-sided', interval='percentile', estimate=None, acceleration=0.0)

The p-value that matches a bootstrap interval: the two-sided p is below alpha exactly when the 1 - alpha interval of the same kind excludes null (up to quantile rounding), so the test and the interval never disagree.

Technical details

Percentile: "greater" (H1: the quantity is above null) is (#{draw <= null} + 1) / (B + 1), "less" the mirror image, two-sided twice the smaller, capped at 1. Draws exactly at null count against H1. Basic: the same count on the reflected draws 2 * estimate - draw. BCa: the share of draws beyond null, mapped back through the BCa adjustment. This resamples the observed data rather than data shifted to the null, the usual choice for interval inversion (Efron & Tibshirani, 1993, ch. 16). The smallest attainable two-sided p is 2 / (B + 1).

Parameters:

Name Type Description Default
draws ArrayLike

The bootstrap distribution; NaN draws are ignored.

required
null float

The value tested against (default 0).

0.0
alternative str

"two-sided" (default), "greater" or "less".

'two-sided'
interval str

The interval the p-value inverts: "percentile" (default), "basic" or "bca".

'percentile'
estimate float | None

The point estimate; required for "basic" and "bca".

None
acceleration float

"bca" only.

0.0

Returns:

Type Description
float

NaN without any valid draw.

jackknife_acceleration(*values)

BCa acceleration from leave-one-out values (see jackknife_values), one array per resampled unit set: the skewness of the jackknife influence values (Efron, 1987), in the multi-sample form scipy.stats.bootstrap uses. Works on values computed elsewhere too.

Returns:

Type Description
float

0 without spread. NaN values are ignored.

jackknife_values(statistic, *samples, paired=False)

Leave-one-out values of statistic(*samples), one array per resampled unit set: a single array when paired=True (each pair left out in turn) or with one sample, otherwise one array per sample (each of its values left out in turn, the other samples kept whole).

Returns:

Type Description
list[ndarray]

Input to jackknife_acceleration.

cluster_permutation(x, y, paired=True, n_permutations=1000, cluster_alpha=0.05, tail=0, seed=None)

Cluster permutation test of x vs y along an ordered coordinate (the columns).

Parameters:

Name Type Description Default
x ArrayLike

One row per unit, one column per coordinate, columns in their true order. Paired: the same units in the same row order. Independent: any number of rows each. Rows with a NaN are dropped (as whole pairs when paired).

required
y ArrayLike

One row per unit, one column per coordinate, columns in their true order. Paired: the same units in the same row order. Independent: any number of rows each. Rows with a NaN are dropped (as whole pairs when paired).

required
paired bool

True (default): t of the differences x - y, null by random sign flips of each unit's difference curve. False: Student t between the samples, null by shuffling the sample labels.

True
n_permutations int

Number of random permutations (default 1000). When the number of distinct sign flips (2^n) or relabellings (C(n_a + n_b, n_a)) is no larger, all of them are enumerated and the p-values are exact.

1000
cluster_alpha float

Sets the cluster-forming threshold: the t quantile at 1 - cluster_alpha / 2 (two-sided) or 1 - cluster_alpha (one tail), with n - 1 (paired) or n_a + n_b - 2 degrees of freedom. Not the significance level of the clusters.

0.05
tail int

0 (default, two-sided), 1 (clusters where x > y) or -1 (x < y).

0
seed int | Generator | None

For reproducible permutations.

None

Returns:

Type Description
ClusterStatResult
!!! note "Technical details"

A cluster's p-value is the share of permutations whose largest cluster mass (in absolute value for two-sided tests) reaches the cluster's mass, with the observed labelling counted once: (#{null >= mass} + 1) / (N + 1) for random permutations, and #{null >= mass} / N when enumerating (the identity is then among the N). A coordinate without spread and a nonzero mean difference gets t = ±inf.

correct_pvalues(p_values, method='fdr_bh', alpha=0.05)

Adjusts one family of p-values for multiple comparisons.

Technical details

NaN p-values (e.g. from a test that couldn't run) are left out of the family: they stay NaN, are never significant, and don't count towards the family size.

Parameters:

Name Type Description Default
p_values ArrayLike
required
method str
  • "fdr_bh" (default): Benjamini-Hochberg false discovery rate.
  • "fdr_by": Benjamini-Yekutieli, FDR under arbitrary dependence.
  • "holm": Holm-Bonferroni step-down, family-wise error rate.
  • "bonferroni": p * m, family-wise error rate.
  • "none": unchanged.
'fdr_bh'
alpha float

Significance threshold applied to the corrected p-values (default 0.05).

0.05

Returns:

Name Type Description
p_corrected np.ndarray of shape (m,)
significant np.ndarray[bool] of shape (m,)

p_corrected <= alpha.

cles(a, b)

Common-language effect size: the probability that a random value of a exceeds a random value of b, ties counting half. 0.5 means no effect.

cohens_d(a, b)

Cohen's d for two independent samples: (mean(a) - mean(b)) / pooled_sd, with the pooled standard deviation using ddof=1 in each sample.

Returns nan if either sample has fewer than 2 values.

cohens_dz(x, y=None)

Cohen's dz for paired data: mean(x - y) / sd(x - y) (ddof=1). With y omitted, x is taken to already be the differences.

epsilon_squared(samples)

Epsilon-squared, the rank-based effect size that goes with the Kruskal-Wallis test: H / (N - 1), in [0, 1] (Tomczak & Tomczak, 2014).

eta_squared(samples)

Eta-squared of a one-way independent design: SS_between / SS_total.

hedges_g(a, b)

Hedges' g: Cohen's d multiplied by the exact small-sample bias correction J(df) = Gamma(df/2) / (sqrt(df/2) * Gamma((df-1)/2)), df = n_a + n_b - 2.

hedges_gz(x, y=None, n_eff=None)

Hedges' gz for paired data: Cohen's dz multiplied by the exact small-sample bias correction J(df) (see hedges_g), with df = n - 1, or n_eff - 1 when an effective sample size is given (see effective_sample_size). With y omitted, x is taken to already be the differences.

Returns nan with fewer than 3 pairs (or n_eff <= 2), where J is undefined.

hodges_lehmann(x, y=None, paired=False)

Hodges-Lehmann estimate of location (shift).

  • One sample (y omitted): the pseudo-median of x, the median of its Walsh averages (x_i + x_j) / 2, i <= j. The estimate that goes with the signed-rank test.
  • Paired (paired=True): the pseudo-median of the differences x - y.
  • Independent (default with y): the median of every difference x_i - y_j, the estimate that goes with the Mann-Whitney test.

Memory grows with n^2; very large samples raise. Returns nan on an empty sample.

kendalls_w(wide)

Kendall's coefficient of concordance W, the effect size that goes with the Friedman test: chi2_friedman / (n * (k - 1)), in [0, 1].

wide has shape (n_subjects, n_groups); rows with any NaN are dropped. Uses the tie-corrected Friedman statistic.

mean_diff(a, b, paired=False)

Difference of means, mean(a) - mean(b).

With paired=True, a and b are matched and pairs with a NaN on either side are dropped (so this is the mean of the differences); otherwise NaNs are dropped from each sample separately.

Returns nan if a sample is empty.

odds_ratio(x, y)

Conditional (McNemar) odds ratio of two matched 0/1 samples, b / c, where b counts the pairs with x = 1, y = 0 and c those with x = 0, y = 1. 1 means no effect.

Returns inf when c = 0 < b, and nan without discordant pairs.

partial_eta_squared_rm(wide)

Partial eta-squared of a one-way repeated-measures design: SS_conditions / (SS_conditions + SS_error).

wide has shape (n_subjects, n_groups); rows with any NaN are dropped.

prop_diff(x, y)

Difference in the proportion of 1s between two matched 0/1 samples, (b - c) / n, where b counts the pairs with x = 1, y = 0, c those with x = 0, y = 1 and n the complete pairs.

Returns nan without complete pairs; raises on values other than 0, 1 and NaN.

rank_biserial(a, b, paired=False, zero_method='wilcox')

Rank-biserial correlation, in [-1, 1].

  • Independent (paired=False): 2 * cles(a, b) - 1, the effect size that goes with the Mann-Whitney U test.
  • Paired (paired=True): the matched-pairs version that goes with the Wilcoxon signed-rank test (Kerby, 2014) -- (R+ - R-) / (sum of ranks), where R+/R- are the rank sums of the positive/negative differences a - b, ranked by absolute value.

Parameters:

Name Type Description Default
zero_method str

Paired only, as in the Wilcoxon test: "wilcox" (default) drops zero differences before ranking; "pratt" and "zsplit" rank them with the rest and keep their ranks in the denominator, so ties pull r toward 0.

'wilcox'

effective_sample_size(x, max_lag=None)

How many independent observations an autocorrelated series is worth:

n_eff = n / (1 + 2 * sum_{k=1}^{K} rho_k)

where rho_k is the lag-k autocorrelation of x (Quenouille, 1952; Thiebaux & Zwiers, 1984). Close to n for white noise, much smaller for strongly serially correlated data (adjacent time points, neighbouring sensors, ...).

Technical details

The sum stops at the first lag whose autocorrelation falls inside the white-noise 95% band 1.96 / sqrt(n), and never goes beyond min(max_lag, n // 4), since autocorrelations at long lags are unreliable. x must be in its true temporal/spatial order -- a shuffled series gives a meaningless result, and this can't be checked. NaNs are dropped first.

Parameters:

Name Type Description Default
x ArrayLike

The series, typically paired differences a - b, in their true order.

required
max_lag int | None

Largest lag to include. Defaults to n // 4.

None

Returns:

Type Description
float

Clipped to [1, n]: the correction can only shrink n.

independent_test(a, b, test='mannwhitneyu', alternative='two-sided', offset=0.0)

Compares two independent samples (no correspondence between them; sizes may differ).

Parameters:

Name Type Description Default
a ArrayLike

NaNs are dropped.

required
b ArrayLike

NaNs are dropped.

required
test str
  • "mannwhitneyu" (default): Mann-Whitney U test, no normality assumption. Statistic: U of a. Effect size: rank-biserial correlation.
  • "ttest": Student's t-test (equal variances). Effect size: Cohen's d.
  • "welch": Welch's t-test (unequal variances). Effect size: Cohen's d.
'mannwhitneyu'
alternative str

"two-sided" (default), "greater" (a shifted above b by more than offset) or "less".

'two-sided'
offset float

The location shift tested against (default 0): the test compares a - offset with b. The effect size always describes the raw a vs b.

0.0

Returns:

Type Description
StatResult

normality(x, test='shapiro')

Tests whether a sample could come from a normal distribution. The null hypothesis is normality, so a small p-value is evidence against it.

Parameters:

Name Type Description Default
x ArrayLike

NaNs are dropped.

required
test str
  • "shapiro" (default): Shapiro-Wilk, the most powerful general test for small and moderate samples (needs n >= 3).
  • "normaltest": D'Agostino-Pearson K^2, based on skewness and kurtosis (needs n >= 8, reliable from n >= 20). Less prone than Shapiro-Wilk to flag negligible deviations at large n.
'shapiro'

Returns:

Type Description
StatResult

No effect size.

omnibus_independent(samples, test='kruskal')

Tests whether k independent groups differ at all.

Parameters:

Name Type Description Default
samples Sequence[ArrayLike]

One sample per group; NaNs are dropped, sizes may differ.

required
test str
  • "kruskal" (default): Kruskal-Wallis H test, no normality assumption. Effect size: epsilon-squared.
  • "anova": one-way ANOVA. Effect size: eta-squared.
'kruskal'

Returns:

Type Description
StatResult

omnibus_paired(wide, test='friedman')

Tests whether k matched groups differ at all ("is there any difference between these methods?"). The usual next step after a significant result is pairwise paired_tests with correct_pvalues.

Parameters:

Name Type Description Default
wide ArrayLike

wide[i, j] is subject i's value in group j. Rows with any NaN are dropped (every subject must be observed in every group).

required
test str
  • "friedman" (default): Friedman test, no normality assumption, needs k >= 3. Effect size: Kendall's W.
  • "rm_anova": one-way repeated-measures ANOVA, needs k >= 2. Effect size: partial eta-squared. For k = 2, F equals the paired t statistic squared.
'friedman'

Returns:

Type Description
StatResult

paired_test(x, y, test='wilcoxon', alternative='two-sided', offset=0.0, zero_method=None)

Compares two matched samples (x[i] and y[i] come from the same unit).

Parameters:

Name Type Description Default
x ArrayLike

Pairs with a NaN on either side are dropped.

required
y ArrayLike

Pairs with a NaN on either side are dropped.

required
test str
  • "wilcoxon" (default): Wilcoxon signed-rank test, no normality assumption. Effect size: matched-pairs rank-biserial correlation, ranked with the same zero_method.
  • "ttest": paired t-test. Effect size: Cohen's dz.
  • "ttest_ess": paired t-test whose standard error and degrees of freedom use the effective sample size of the differences instead of n -- for pairs indexed by something with serial correlation (time points, neighbouring sensors). x/y must be in that true order. Effect size: Cohen's dz.
  • "mcnemar": exact McNemar test for a binary outcome coded 0/1. Only discordant pairs carry information: b pairs with x = 1, y = 0 and c with x = 0, y = 1; under the null b ~ Binomial(b + c, 1/2). Statistic: b. p = 1 without discordant pairs. Effect size: difference in proportions. No offset.
'wilcoxon'
alternative str

"two-sided" (default), "greater" (x - y > offset) or "less".

'two-sided'
offset float

The difference tested against (default 0): the null hypothesis is x - y = offset, so offset=0.1, alternative="greater" asks whether x beats y by more than 0.1. The test runs on x - y - offset; the effect size always describes the raw x - y.

0.0
zero_method str | None

Wilcoxon only: what to do with pairs whose shifted difference is exactly 0. "wilcox" (default) drops them (n counts the rest); "pratt" ranks them and leaves their ranks out of both sums; "zsplit" splits their ranks evenly between the sums. With "pratt"/"zsplit", n counts every pair.

None

Returns:

Type Description
StatResult

binomial_median_interval(x, level=0.95)

Exact distribution-free interval for the median: the k-th smallest and k-th largest values, with k from the Binomial(n, 1/2) distribution of the number of values below the median. Its coverage is at least level.

Returns:

Type Description
(low, high): tuple[float, float]

NaNs when the sample is too small for level (n < 6 at 95%).

mann_whitney_interval(a, b, level=0.95)

Interval for the two-sample Hodges-Lehmann shift median(a_i - b_j): order statistics of the sorted pairwise differences at the depth given by the normal approximation of the Mann-Whitney U null distribution. No correction for ties.

Returns:

Type Description
(low, high): tuple[float, float]

NaNs when the samples are too small for level.

newcombe_interval(x, y, level=0.95)

Newcombe's hybrid score interval for the difference of two paired proportions, mean(x) - mean(y) for matched 0/1 samples (Newcombe, 1998, method 10): a Wilson interval for each proportion, combined with a correction phi for their correlation.

Returns:

Type Description
(low, high): tuple[float, float]

NaNs without complete pairs; raises on values other than 0, 1 and NaN.

odds_ratio_interval(x, y, level=0.95)

Exact interval for the conditional odds ratio b / c of matched 0/1 samples (see odds_ratio): the Clopper-Pearson interval of b / (b + c), the share of discordant pairs favouring x, mapped through p / (1 - p) (Breslow & Day, 1980).

Returns:

Type Description
(low, high): tuple[float, float]

NaNs without discordant pairs; the upper bound is inf when c = 0.

signed_rank_interval(x, level=0.95)

Distribution-free interval for the one-sample (or paired-difference) Hodges-Lehmann estimate: order statistics of the sorted Walsh averages, at the depth given by the signed-rank null distribution -- exact for n <= 200, normal approximation above (Hollander & Wolfe). No correction for ties or serial correlation.

Returns:

Type Description
(low, high): tuple[float, float]

NaNs when the sample is too small for level (e.g. n < 6 at 95%).

t_interval(x, level=0.95, n_eff=None)

Student t interval for the mean of one sample (or of paired differences): mean ± t(1 - alpha/2, df) * sd / sqrt(n), df = n - 1.

Parameters:

Name Type Description Default
x ArrayLike

One sample, or the differences of matched pairs.

required
level float

Confidence level (default 0.95).

0.95
n_eff float | None

An effective sample size (see effective_sample_size) for a serially correlated series: used instead of n in the standard error, with df = max(n_eff - 1, 1).

None

Returns:

Type Description
(low, high): tuple[float, float]

NaNs with fewer than 2 values.

welch_interval(a, b, level=0.95)

Welch interval for the difference of means of two independent samples, mean(a) - mean(b), with Welch-Satterthwaite degrees of freedom (no equal-variance assumption).

Returns:

Type Description
(low, high): tuple[float, float]

NaNs if either sample has fewer than 2 values.

wilson_interval(x, level=0.95)

Wilson score interval for the proportion of 1s in a 0/1 sample (Wilson, 1927). Stays within [0, 1] and keeps close to nominal coverage at small n.

Returns:

Type Description
(low, high): tuple[float, float]

NaNs for an empty sample; raises on values other than 0, 1 and NaN.