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], ...]
|
|
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 |
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. |
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 |
alternative |
str
|
|
offset |
float
|
The difference tested against: the null hypothesis is
|
zero_method |
str | None
|
How the Wilcoxon test treated zero differences; |
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
|
Infinite draws are left out of |
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 |
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 |
2000
|
interval
|
str
|
|
'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 |
None
|
acceleration
|
float | None
|
BCa only. Defaults to the jackknife acceleration of |
None
|
Returns:
| Type | Description |
|---|---|
(low, high): tuple[float, float]
|
|
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 |
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 |
bootstrap_interval(draws, estimate=None, level=0.95, interval='percentile', acceleration=0.0)
¶
Confidence interval read from bootstrap draws.
"percentile": thealpha/2and1 - alpha/2quantiles 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 levelsPhi(z0 + (z0 + z) / (1 - a (z0 + z))), with the bias correctionz0(seebootstrap_bias) and theaccelerationa(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 |
None
|
level
|
float
|
Confidence level (default 0.95). |
0.95
|
interval
|
str
|
|
'percentile'
|
acceleration
|
float
|
|
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'
|
interval
|
str
|
The interval the p-value inverts: |
'percentile'
|
estimate
|
float | None
|
The point estimate; required for |
None
|
acceleration
|
float
|
|
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 |
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 |
True
|
n_permutations
|
int
|
Number of random permutations (default 1000). When the number of distinct sign flips
( |
1000
|
cluster_alpha
|
float
|
Sets the cluster-forming threshold: the t quantile at |
0.05
|
tail
|
int
|
0 (default, two-sided), 1 (clusters where |
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:
|
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'
|
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,)
|
|
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 (
yomitted): the pseudo-median ofx, 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 differencesx - y. - Independent (default with
y): the median of every differencex_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), whereR+/R-are the rank sums of the positive/negative differencesa - b, ranked by absolute value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zero_method
|
str
|
Paired only, as in the Wilcoxon test: |
'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 |
required |
max_lag
|
int | None
|
Largest lag to include. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Clipped to |
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'
|
alternative
|
str
|
|
'two-sided'
|
offset
|
float
|
The location shift tested against (default 0): the test compares
|
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'
|
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'
|
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
|
|
required |
test
|
str
|
|
'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'
|
alternative
|
str
|
|
'two-sided'
|
offset
|
float
|
The difference tested against (default 0): the null hypothesis is
|
0.0
|
zero_method
|
str | None
|
Wilcoxon only: what to do with pairs whose shifted difference is
exactly 0. |
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 |
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 |
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 |
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 |
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 |
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. |