groupunit 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- groupunit/__init__.py +60 -0
- groupunit/core.py +148 -0
- groupunit/design.py +168 -0
- groupunit/diagnostics.py +273 -0
- groupunit/inference.py +554 -0
- groupunit/methods.py +149 -0
- groupunit/scores.py +80 -0
- groupunit/similarity.py +199 -0
- groupunit/simulate.py +44 -0
- groupunit/validation.py +106 -0
- groupunit/weights.py +102 -0
- groupunit-0.2.0.dist-info/METADATA +107 -0
- groupunit-0.2.0.dist-info/RECORD +16 -0
- groupunit-0.2.0.dist-info/WHEEL +5 -0
- groupunit-0.2.0.dist-info/licenses/LICENSE +21 -0
- groupunit-0.2.0.dist-info/top_level.txt +1 -0
groupunit/methods.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""PLS correlation, CCA and LDA, written through the group means (the identity, Results 2-3).
|
|
2
|
+
|
|
3
|
+
These are plain reference implementations. They exist so that the tests in
|
|
4
|
+
`groupunit.inference` can refit them under permutation, and so that each
|
|
5
|
+
result can be checked against the identities of the paper. Every fit returns
|
|
6
|
+
a `Components` object with the same fields.
|
|
7
|
+
"""
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from .core import check_groups, group_means, wcentre, weighted_basis
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Components:
|
|
17
|
+
"""Paired feature-side and annotation-side components.
|
|
18
|
+
|
|
19
|
+
Attributes
|
|
20
|
+
----------
|
|
21
|
+
strength : (k,) singular values (PLS) or canonical correlations (CCA).
|
|
22
|
+
x_weights : (p, k) feature weights; scores are ``(X - x_mean) @ x_weights``.
|
|
23
|
+
y_weights : (q, k) annotation weights. Not unique when q > r (Result 3e);
|
|
24
|
+
the minimum-norm solution is returned.
|
|
25
|
+
group_scores : (M, k) group means of the feature-side scores, t̄.
|
|
26
|
+
y_loadings : (q, k) covariances of the annotations with the feature-side
|
|
27
|
+
scores, ``Ỹᵀ D t̄ / N``. Unique, and a fixed function of ``group_scores``.
|
|
28
|
+
x_mean : (p,) feature means used for centring.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
strength: np.ndarray
|
|
32
|
+
x_weights: np.ndarray
|
|
33
|
+
y_weights: np.ndarray
|
|
34
|
+
group_scores: np.ndarray
|
|
35
|
+
y_loadings: np.ndarray
|
|
36
|
+
x_mean: np.ndarray
|
|
37
|
+
|
|
38
|
+
def scores(self, X):
|
|
39
|
+
"""Feature-side scores of individuals, ``(N, k)``."""
|
|
40
|
+
return (np.asarray(X, float) - self.x_mean) @ self.x_weights
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _fix_signs(*arrays, ref):
|
|
44
|
+
"""Flip each component so that its largest annotation loading is positive."""
|
|
45
|
+
signs = np.sign(ref[np.argmax(np.abs(ref), axis=0), np.arange(ref.shape[1])])
|
|
46
|
+
signs[signs == 0] = 1
|
|
47
|
+
return [a * signs for a in arrays]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _rank_cutoff(s):
|
|
51
|
+
return s > s.max(initial=0) * max(s.shape[0], 1) * np.finfo(float).eps * 10
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def pls(X, groups, Y, n_components=None, weights=None):
|
|
55
|
+
"""PLS correlation (PLS-SVD) of individual features with group-level annotations.
|
|
56
|
+
|
|
57
|
+
The weights are the singular vectors of ``XᵀY = X̄ᵀ D Ỹ`` (Result 2), so they
|
|
58
|
+
depend on the group means, the annotations and the group sizes only. Pass
|
|
59
|
+
``weights`` (one per group, e.g. ``np.ones(M)``) to target the population of
|
|
60
|
+
groups instead of individuals (Section 4.1). The first component equals the
|
|
61
|
+
first component of PLS regression.
|
|
62
|
+
"""
|
|
63
|
+
Y = np.asarray(Y, float)
|
|
64
|
+
groups, n = check_groups(groups, len(Y))
|
|
65
|
+
w = n.astype(float) if weights is None else np.asarray(weights, float)
|
|
66
|
+
Xbar = group_means(X, groups, len(Y))
|
|
67
|
+
x_mean = w @ Xbar / w.sum()
|
|
68
|
+
Xb, Yc = Xbar - x_mean, wcentre(Y, w)
|
|
69
|
+
|
|
70
|
+
U, s, Vt = np.linalg.svd(Xb.T @ (w[:, None] * Yc), full_matrices=False)
|
|
71
|
+
k = int(_rank_cutoff(s).sum())
|
|
72
|
+
if n_components is not None:
|
|
73
|
+
k = min(k, n_components)
|
|
74
|
+
W, V, s = U[:, :k], Vt[:k].T, s[:k]
|
|
75
|
+
T = Xb @ W
|
|
76
|
+
loadings = Yc.T @ (w[:, None] * T) / w.sum()
|
|
77
|
+
W, V, T, loadings = _fix_signs(W, V, T, loadings, ref=loadings)
|
|
78
|
+
return Components(s, W, V, T, loadings, x_mean)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _cca_spaces(X, groups, Y, w):
|
|
82
|
+
"""Orthonormal bases of the (row-weighted) feature and annotation spaces of CCA.
|
|
83
|
+
|
|
84
|
+
Individual i of group m gets row weight r_m = w_m / n_m, so group m carries
|
|
85
|
+
total weight w_m; w = n gives ordinary CCA. Returns the feature basis Ux of
|
|
86
|
+
R^{1/2}(X − x̄_w) with its singular values and right vectors, the weighted
|
|
87
|
+
feature mean, P = D^{1/2} Ūx and Q = `weighted_basis`(Y, w). The annotation
|
|
88
|
+
basis in individual space has entries Q_m / sqrt(n_m) whatever the weights,
|
|
89
|
+
so the canonical correlations are the singular values of Pᵀ Q.
|
|
90
|
+
"""
|
|
91
|
+
n = np.bincount(groups, minlength=len(Y)).astype(float)
|
|
92
|
+
r = w / n
|
|
93
|
+
x_mean = w @ group_means(X, groups, len(Y)) / w.sum()
|
|
94
|
+
Ux, sx, Vxt = np.linalg.svd(np.sqrt(r)[groups, None] * (X - x_mean), full_matrices=False)
|
|
95
|
+
keep = _rank_cutoff(sx)
|
|
96
|
+
Ux, sx, Vxt = Ux[:, keep], sx[keep], Vxt[keep]
|
|
97
|
+
P = np.sqrt(n)[:, None] * group_means(Ux, groups, len(Y))
|
|
98
|
+
return Ux, sx, Vxt, x_mean, P, weighted_basis(Y, w)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def cca(X, groups, Y, n_components=None, weights=None):
|
|
102
|
+
"""Canonical correlation analysis of individual features with group-level annotations.
|
|
103
|
+
|
|
104
|
+
Canonical correlations are the cosines of the principal angles between the
|
|
105
|
+
column spaces of X and of the inherited annotations ``Y[groups]``. The
|
|
106
|
+
annotation space is built from the group-level table, so the fit never
|
|
107
|
+
forms the N × q matrix. If the annotations have rank M - 1, the result is
|
|
108
|
+
the same for every annotation table of that rank and equals `lda` (Result 3c).
|
|
109
|
+
|
|
110
|
+
Ordinary CCA weights groups by size. ``weights`` (one per group) gives
|
|
111
|
+
row-weighted CCA instead: each individual of group m is weighted by
|
|
112
|
+
w_m / n_m, so that group m carries total weight w_m in every mean,
|
|
113
|
+
variance and covariance, on both sides. Feature and annotation scores are
|
|
114
|
+
scaled to unit weighted variance; ``y_loadings`` are weighted covariances,
|
|
115
|
+
Ỹᵀ W t̄ / Σw.
|
|
116
|
+
"""
|
|
117
|
+
Y = np.asarray(Y, float)
|
|
118
|
+
groups, n = check_groups(groups, len(Y))
|
|
119
|
+
X = np.asarray(X, float)
|
|
120
|
+
w = n.astype(float) if weights is None else np.asarray(weights, float)
|
|
121
|
+
if w.shape != n.shape or np.any(w <= 0):
|
|
122
|
+
raise ValueError(f"weights must be {len(n)} positive numbers, one per group")
|
|
123
|
+
total = w.sum()
|
|
124
|
+
|
|
125
|
+
Ux, sx, Vxt, x_mean, P, Q = _cca_spaces(X, groups, Y, w)
|
|
126
|
+
A, rho, Bt = np.linalg.svd(P.T @ Q, full_matrices=False)
|
|
127
|
+
|
|
128
|
+
k = len(rho) if n_components is None else min(len(rho), n_components)
|
|
129
|
+
A, B, rho = A[:, :k], Bt[:k].T, np.clip(rho[:k], 0, 1)
|
|
130
|
+
x_weights = Vxt.T @ (A / sx[:, None]) * np.sqrt(total)
|
|
131
|
+
# Ux A holds R^{1/2} t / sqrt(total); undo the row weights within each group
|
|
132
|
+
T = group_means(Ux @ A, groups, len(Y)) / np.sqrt(w / n)[:, None] * np.sqrt(total)
|
|
133
|
+
Yc = wcentre(Y, w)
|
|
134
|
+
# minimum-norm annotation weights b with W^{1/2} Ỹ b = Q B (unit-variance annotation scores)
|
|
135
|
+
y_weights = np.linalg.pinv(np.sqrt(w)[:, None] * Yc) @ Q @ B * np.sqrt(total)
|
|
136
|
+
loadings = Yc.T @ (w[:, None] * T) / total
|
|
137
|
+
x_weights, y_weights, T, loadings = _fix_signs(x_weights, y_weights, T, loadings, ref=loadings)
|
|
138
|
+
return Components(rho, x_weights, y_weights, T, loadings, x_mean)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def lda(X, groups, n_components=None):
|
|
142
|
+
"""Linear discriminant analysis of individuals by group, as CCA with group indicators.
|
|
143
|
+
|
|
144
|
+
The squared canonical correlations are the between-group shares η² of the
|
|
145
|
+
discriminant scores. With p large relative to M or N, groups separate in
|
|
146
|
+
sample even when they do not differ; estimate η² on held-out individuals.
|
|
147
|
+
"""
|
|
148
|
+
groups, n = check_groups(groups)
|
|
149
|
+
return cca(X, groups, np.eye(len(n)), n_components)
|
groupunit/scores.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Between-group share of scores and the decomposition of their correlations (Results 1 and 3a)."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from .core import check_groups, group_means, weighted_corr, weighted_r2
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def between_share(t, groups):
|
|
10
|
+
"""Between-group share η² of the variance of a score (Results 1 and 3a).
|
|
11
|
+
|
|
12
|
+
``t`` is a score vector ``(N,)`` or a matrix of scores ``(N, k)``; returns
|
|
13
|
+
a float or one value per column.
|
|
14
|
+
"""
|
|
15
|
+
groups, n = check_groups(groups)
|
|
16
|
+
t = np.asarray(t, float)
|
|
17
|
+
t = t - t.mean(0)
|
|
18
|
+
tbar = group_means(t, groups)
|
|
19
|
+
n_ = n.reshape((-1,) + (1,) * (t.ndim - 1))
|
|
20
|
+
eta2 = (n_ * tbar**2).sum(0) / (t**2).sum(0)
|
|
21
|
+
return float(eta2) if t.ndim == 1 else eta2
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def feature_between_share(X, groups):
|
|
25
|
+
"""Between-group share of the feature space as a whole, tr S_B / tr S_T (Section 5)."""
|
|
26
|
+
groups, n = check_groups(groups)
|
|
27
|
+
X = np.asarray(X, float)
|
|
28
|
+
Xc = X - X.mean(0)
|
|
29
|
+
Xbar = group_means(Xc, groups)
|
|
30
|
+
return float((n[:, None] * Xbar**2).sum() / (Xc**2).sum())
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class ScoreDecomposition:
|
|
35
|
+
"""How a score relates to the annotations, split into group separation and group-level fit.
|
|
36
|
+
|
|
37
|
+
Attributes
|
|
38
|
+
----------
|
|
39
|
+
eta2 : between-group share of the score's variance.
|
|
40
|
+
group_corr : (q,) size-weighted correlation of the score's group means with each annotation, r_n.
|
|
41
|
+
corr : (q,) individual-level correlation with each annotation, ``sqrt(eta2) * group_corr`` (Result 1).
|
|
42
|
+
group_r2 : size-weighted R² of the group means on all annotations, R²_n.
|
|
43
|
+
max_corr2 : largest squared correlation of the score with any combination of
|
|
44
|
+
annotations, ``eta2 * group_r2`` (Result 3a); what CCA maximises.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
eta2: float
|
|
48
|
+
group_corr: np.ndarray
|
|
49
|
+
corr: np.ndarray
|
|
50
|
+
group_r2: float
|
|
51
|
+
max_corr2: float
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def decompose_score(t, groups, Y):
|
|
55
|
+
"""Decompose the relation of one score ``t`` (N,) with the annotation table ``Y`` (M, q).
|
|
56
|
+
|
|
57
|
+
Correlations computed over individuals equal the group-level correlations
|
|
58
|
+
attenuated by η, and rest on M group means, not on N individuals.
|
|
59
|
+
"""
|
|
60
|
+
groups, n = check_groups(groups, len(Y))
|
|
61
|
+
t = np.asarray(t, float)
|
|
62
|
+
if t.ndim != 1:
|
|
63
|
+
raise ValueError("decompose_score takes a single score vector")
|
|
64
|
+
eta2 = between_share(t, groups)
|
|
65
|
+
tbar = group_means(t - t.mean(), groups)
|
|
66
|
+
group_corr = np.atleast_1d(weighted_corr(tbar, np.asarray(Y, float), n))
|
|
67
|
+
group_r2 = weighted_r2(tbar, Y, n)
|
|
68
|
+
return ScoreDecomposition(
|
|
69
|
+
eta2=eta2,
|
|
70
|
+
group_corr=group_corr,
|
|
71
|
+
corr=np.sqrt(eta2) * group_corr,
|
|
72
|
+
group_r2=group_r2,
|
|
73
|
+
max_corr2=eta2 * group_r2,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def group_scores(t, groups, M=None):
|
|
78
|
+
"""Group means of a score centred over individuals: the only part of it the annotations see."""
|
|
79
|
+
t = np.asarray(t, float)
|
|
80
|
+
return group_means(t - t.mean(0), groups, M)
|
groupunit/similarity.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Comparison of group similarity matrices: typicality versus pattern (Results 4a-4c)."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from .inference import p_value, draw_permutations
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class TypicalityPattern:
|
|
11
|
+
"""Additive split of a similarity matrix, s_ij = μ + a_i + a_j + e_ij, over off-diagonal entries.
|
|
12
|
+
|
|
13
|
+
Attributes
|
|
14
|
+
----------
|
|
15
|
+
mean : μ.
|
|
16
|
+
typicality : (M,) group effects a_i, how similar each group is to the set as a whole.
|
|
17
|
+
pattern : (M, M) residuals e_ij, which groups resemble each other beyond
|
|
18
|
+
their typicality; zero on the diagonal.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
mean: float
|
|
22
|
+
typicality: np.ndarray
|
|
23
|
+
pattern: np.ndarray
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def typicality_pattern(S):
|
|
27
|
+
"""Least-squares fit of the additive model to the off-diagonal entries of ``S``."""
|
|
28
|
+
S = np.array(S, float)
|
|
29
|
+
M = len(S)
|
|
30
|
+
if S.shape != (M, M) or not np.allclose(S, S.T):
|
|
31
|
+
raise ValueError("S must be a symmetric square matrix")
|
|
32
|
+
if M < 3:
|
|
33
|
+
raise ValueError("need at least three groups")
|
|
34
|
+
np.fill_diagonal(S, 0)
|
|
35
|
+
rho = S.sum(1)
|
|
36
|
+
T = rho.sum()
|
|
37
|
+
a = rho / (M - 2) - T / (M * (M - 2))
|
|
38
|
+
E = S - (rho[:, None] + rho[None, :]) / (M - 2) + T / ((M - 1) * (M - 2))
|
|
39
|
+
np.fill_diagonal(E, 0)
|
|
40
|
+
return TypicalityPattern(mean=T / (M * (M - 1)), typicality=a, pattern=E)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class SimilarityDecomposition:
|
|
45
|
+
"""The Mantel correlation of two similarity matrices split into typicality and pattern (Result 4a).
|
|
46
|
+
|
|
47
|
+
Attributes
|
|
48
|
+
----------
|
|
49
|
+
mantel : r_M, the correlation of the two matrices over the M(M − 1)/2 pairs.
|
|
50
|
+
typicality_share : (2,) λ² and λ'², the share of each matrix's variation
|
|
51
|
+
over pairs that is due to typicality, (M − 2) Σ a_i² / Σ_{i<j} (s_ij − μ)².
|
|
52
|
+
r_typicality : r_a, the correlation of the two sets of group effects across groups.
|
|
53
|
+
r_pattern : r_e, the correlation of the raw (unstandardised) residuals across pairs.
|
|
54
|
+
typicality_part : sqrt(λ² λ'²) r_a, the part of r_M carried by typicality.
|
|
55
|
+
pattern_part : sqrt((1 − λ²)(1 − λ'²)) r_e, the part carried by pattern.
|
|
56
|
+
The two parts sum exactly to ``mantel``.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
mantel: float
|
|
60
|
+
typicality_share: np.ndarray
|
|
61
|
+
r_typicality: float
|
|
62
|
+
r_pattern: float
|
|
63
|
+
typicality_part: float
|
|
64
|
+
pattern_part: float
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def similarity_decomposition(S1, S2):
|
|
68
|
+
"""What a Mantel correlation is made of: shared typicality and shared pattern (Result 4a).
|
|
69
|
+
|
|
70
|
+
With s_ij = μ + a_i + a_j + e_ij fitted to each matrix (`typicality_pattern`),
|
|
71
|
+
|
|
72
|
+
r_M = sqrt(λ² λ'²) r_a + sqrt((1 − λ²)(1 − λ'²)) r_e,
|
|
73
|
+
|
|
74
|
+
exactly. A positive Mantel correlation can therefore come entirely from
|
|
75
|
+
groups that are unusual in both tables (the first term) without any pair
|
|
76
|
+
of groups being specifically alike (the second). The claim that "groups
|
|
77
|
+
with similar annotations have similar features" concerns r_e. This
|
|
78
|
+
function only describes; `compare_similarity` tests the parts, with the
|
|
79
|
+
pattern on standardised residuals.
|
|
80
|
+
"""
|
|
81
|
+
S1, S2 = np.asarray(S1, float), np.asarray(S2, float)
|
|
82
|
+
if S1.shape != S2.shape:
|
|
83
|
+
raise ValueError(f"the matrices differ in shape: {S1.shape} and {S2.shape}")
|
|
84
|
+
M = len(S1)
|
|
85
|
+
iu = np.triu_indices(M, 1)
|
|
86
|
+
parts = [typicality_pattern(S) for S in (S1, S2)]
|
|
87
|
+
# over pairs, effects and residuals are orthogonal (residual row sums are zero), so
|
|
88
|
+
# Σ (s_ij − μ)(s'_ij − μ') = (M − 2) Σ a_i a'_i + Σ e_ij e'_ij
|
|
89
|
+
typ_ss = np.array([(M - 2) * (d.typicality**2).sum() for d in parts])
|
|
90
|
+
pat_ss = np.array([(d.pattern[iu] ** 2).sum() for d in parts])
|
|
91
|
+
if np.any(typ_ss + pat_ss == 0):
|
|
92
|
+
raise ValueError("a matrix is constant over its off-diagonal entries; its correlation is undefined")
|
|
93
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
94
|
+
r_a = (parts[0].typicality @ parts[1].typicality) * (M - 2) / np.sqrt(typ_ss.prod())
|
|
95
|
+
r_e = (parts[0].pattern[iu] @ parts[1].pattern[iu]) / np.sqrt(pat_ss.prod())
|
|
96
|
+
share = typ_ss / (typ_ss + pat_ss)
|
|
97
|
+
typ_part = np.sqrt(share.prod()) * np.nan_to_num(r_a) # a part with no variation contributes 0
|
|
98
|
+
pat_part = np.sqrt((1 - share).prod()) * np.nan_to_num(r_e)
|
|
99
|
+
return SimilarityDecomposition(
|
|
100
|
+
mantel=float(np.corrcoef(S1[iu], S2[iu])[0, 1]),
|
|
101
|
+
typicality_share=share,
|
|
102
|
+
r_typicality=float(r_a),
|
|
103
|
+
r_pattern=float(r_e),
|
|
104
|
+
typicality_part=float(typ_part),
|
|
105
|
+
pattern_part=float(pat_part),
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def distance_similarity(profiles):
|
|
110
|
+
"""Negative squared Euclidean distances between group profiles, (M, M).
|
|
111
|
+
|
|
112
|
+
For this similarity the additive model is exact: typicality is
|
|
113
|
+
−M/(M−2) times each group's centred squared distance from the centroid, and
|
|
114
|
+
the pattern is twice the U-centred matrix of inner products of the centred
|
|
115
|
+
profiles. Correlation and
|
|
116
|
+
cosine similarities divide by each group's norm, which turns shared
|
|
117
|
+
typicality into apparent resemblance, so their pattern test is liberal
|
|
118
|
+
when typicality is shared.
|
|
119
|
+
"""
|
|
120
|
+
F = np.asarray(profiles, float)
|
|
121
|
+
F = F - F.mean(0)
|
|
122
|
+
G = F @ F.T
|
|
123
|
+
d = np.diag(G)
|
|
124
|
+
return 2 * G - d[:, None] - d[None, :]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def standardised_pattern(E):
|
|
128
|
+
"""Pattern residuals divided by the residual scale of both groups, e_ij / (σ_i σ_j).
|
|
129
|
+
|
|
130
|
+
Atypical groups have larger residuals; when two tables share typicality
|
|
131
|
+
they share this scale, and permuting groups breaks it, which makes the raw
|
|
132
|
+
pattern test liberal. Standardising removes the shared scale.
|
|
133
|
+
"""
|
|
134
|
+
E = np.asarray(E, float)
|
|
135
|
+
sd = np.sqrt((E**2).sum(1) / (len(E) - 1))
|
|
136
|
+
return E / np.outer(sd, sd)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@dataclass(frozen=True)
|
|
140
|
+
class Correlation:
|
|
141
|
+
r: float
|
|
142
|
+
p: float
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass(frozen=True)
|
|
146
|
+
class SimilarityComparison:
|
|
147
|
+
"""Mantel correlation of two similarity matrices and its two parts, each with a group-permutation p-value."""
|
|
148
|
+
|
|
149
|
+
mantel: Correlation
|
|
150
|
+
typicality: Correlation
|
|
151
|
+
pattern: Correlation
|
|
152
|
+
|
|
153
|
+
def __str__(self):
|
|
154
|
+
return "\n".join(f"{name:<11} r = {c.r:+.3f} p = {c.p:.4f}"
|
|
155
|
+
for name, c in vars(self).items())
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def compare_similarity(S1, S2, n_perm=5000, rng=None, alternative="greater", strata=None,
|
|
159
|
+
standardise=True):
|
|
160
|
+
"""Mantel test, and separate tests of shared typicality and shared pattern.
|
|
161
|
+
|
|
162
|
+
Groups are permuted jointly over the rows and columns of ``S2``. A positive
|
|
163
|
+
Mantel correlation alone does not show that groups with similar annotations
|
|
164
|
+
have similar features; that claim concerns the pattern. Run the same
|
|
165
|
+
comparison on a pair expected to share a pattern as a positive control.
|
|
166
|
+
``alternative`` is "greater" or "two-sided".
|
|
167
|
+
|
|
168
|
+
With ``standardise`` (the default) the pattern test correlates
|
|
169
|
+
`standardised_pattern` residuals, which keeps it calibrated when the tables
|
|
170
|
+
share typicality. That holds for distance-based similarities (see
|
|
171
|
+
`distance_similarity`); for correlation or cosine similarities the pattern
|
|
172
|
+
test stays somewhat liberal under shared typicality, so confirm a
|
|
173
|
+
significant pattern with distances.
|
|
174
|
+
"""
|
|
175
|
+
S1, S2 = np.asarray(S1, float), np.asarray(S2, float)
|
|
176
|
+
M = len(S1)
|
|
177
|
+
iu = np.triu_indices(M, 1)
|
|
178
|
+
d1, d2 = typicality_pattern(S1), typicality_pattern(S2)
|
|
179
|
+
E1, E2 = d1.pattern, d2.pattern
|
|
180
|
+
if standardise:
|
|
181
|
+
E1, E2 = standardised_pattern(E1), standardised_pattern(E2)
|
|
182
|
+
|
|
183
|
+
def stats(perm):
|
|
184
|
+
# the decomposition (and the standardisation) is permutation-equivariant,
|
|
185
|
+
# so permuting its parts equals decomposing the permuted matrix
|
|
186
|
+
mantel = np.corrcoef(S1[iu], S2[np.ix_(perm, perm)][iu])[0, 1]
|
|
187
|
+
typ = np.corrcoef(d1.typicality, d2.typicality[perm])[0, 1]
|
|
188
|
+
pat = np.corrcoef(E1[iu], E2[np.ix_(perm, perm)][iu])[0, 1]
|
|
189
|
+
return np.array([mantel, typ, pat])
|
|
190
|
+
|
|
191
|
+
observed = stats(np.arange(M))
|
|
192
|
+
null = np.array([stats(perm) for perm in draw_permutations(M, n_perm, rng, strata)])
|
|
193
|
+
if alternative == "two-sided":
|
|
194
|
+
p = p_value(np.abs(observed), np.abs(null))
|
|
195
|
+
elif alternative == "greater":
|
|
196
|
+
p = p_value(observed, null)
|
|
197
|
+
else:
|
|
198
|
+
raise ValueError("alternative must be 'greater' or 'two-sided'")
|
|
199
|
+
return SimilarityComparison(*(Correlation(float(r), float(q)) for r, q in zip(observed, p)))
|
groupunit/simulate.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Simulated designs with group-level annotations (Section 6.1)."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def lognormal_sizes(M, mean_size, sigma=0.6, minimum=2, rng=None):
|
|
6
|
+
"""Unequal group sizes drawn from a log-normal distribution; larger ``sigma`` means more imbalance."""
|
|
7
|
+
rng = np.random.default_rng(rng)
|
|
8
|
+
sizes = np.round(np.exp(rng.normal(np.log(mean_size), sigma, M))).astype(int)
|
|
9
|
+
return np.maximum(sizes, minimum)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def simulate(n, p, Y=None, q=None, beta=0.0, tau2=1.0, sigma2_w=1.0, rng=None):
|
|
13
|
+
"""Simulate individuals' features: x_i = μ_m(i) + ε_i, with μ_m = βᵀỹ_m + u_m.
|
|
14
|
+
|
|
15
|
+
Parameters
|
|
16
|
+
----------
|
|
17
|
+
n : group sizes, (M,).
|
|
18
|
+
p : number of features.
|
|
19
|
+
Y : annotation table (M, q); drawn as standard normal with ``q`` columns if None.
|
|
20
|
+
beta : the true relation. A (q, p) matrix, or a number used as the scale of a
|
|
21
|
+
random standard-normal β; 0 gives the null.
|
|
22
|
+
tau2 : variance of the group-level heterogeneity u_m.
|
|
23
|
+
sigma2_w : variance of the within-group noise ε_i.
|
|
24
|
+
|
|
25
|
+
Returns
|
|
26
|
+
-------
|
|
27
|
+
X, groups, Y
|
|
28
|
+
Features (N, p), group codes (N,) and the annotation table (M, q).
|
|
29
|
+
"""
|
|
30
|
+
rng = np.random.default_rng(rng)
|
|
31
|
+
n = np.asarray(n, int)
|
|
32
|
+
M = len(n)
|
|
33
|
+
if Y is None:
|
|
34
|
+
if q is None:
|
|
35
|
+
raise ValueError("give either Y or q")
|
|
36
|
+
Y = rng.standard_normal((M, q))
|
|
37
|
+
Y = np.asarray(Y, float)
|
|
38
|
+
B = np.asarray(beta, float)
|
|
39
|
+
if B.ndim == 0:
|
|
40
|
+
B = B * rng.standard_normal((Y.shape[1], p))
|
|
41
|
+
mu = Y @ B + np.sqrt(tau2) * rng.standard_normal((M, p))
|
|
42
|
+
groups = np.repeat(np.arange(M), n)
|
|
43
|
+
X = mu[groups] + np.sqrt(sigma2_w) * rng.standard_normal((len(groups), p))
|
|
44
|
+
return X, groups, Y
|
groupunit/validation.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Leave-one-group-out validation against a mean baseline (Section 4.5).
|
|
2
|
+
|
|
3
|
+
A claim that a relation holds for groups not yet studied is a prediction. It
|
|
4
|
+
is validated by predicting each group from the others, with every selection
|
|
5
|
+
step inside the loop, and comparing with predicting the mean of the others.
|
|
6
|
+
"""
|
|
7
|
+
import copy
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def linear_model(Y_train, t_train, w_train, Y_test):
|
|
14
|
+
"""Weighted least squares of a group-level target on the annotations, with an intercept.
|
|
15
|
+
|
|
16
|
+
Uses the minimum-norm solution when the annotations outnumber the training
|
|
17
|
+
groups; such a fit interpolates and will usually predict badly.
|
|
18
|
+
"""
|
|
19
|
+
Z = np.column_stack([np.ones(len(Y_train)), Y_train])
|
|
20
|
+
sw = np.sqrt(w_train)
|
|
21
|
+
coef, *_ = np.linalg.lstsq(sw[:, None] * Z, sw.reshape((-1,) + (1,) * (t_train.ndim - 1)) * t_train,
|
|
22
|
+
rcond=None)
|
|
23
|
+
return np.concatenate([[1.0], Y_test]) @ coef
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def pca_regression(k, standardise=False):
|
|
27
|
+
"""A model that reduces the annotations to k principal components fitted on the training groups only.
|
|
28
|
+
|
|
29
|
+
An example of nesting a selection step inside validation: the components
|
|
30
|
+
are recomputed in every fold, never from the held-out group.
|
|
31
|
+
"""
|
|
32
|
+
def model(Y_train, t_train, w_train, Y_test):
|
|
33
|
+
mean = w_train @ Y_train / w_train.sum()
|
|
34
|
+
Yc = Y_train - mean
|
|
35
|
+
scale = np.ones(Yc.shape[1])
|
|
36
|
+
if standardise:
|
|
37
|
+
sd = np.sqrt(w_train @ Yc**2 / w_train.sum())
|
|
38
|
+
scale = np.where(sd > 0, sd, 1.0)
|
|
39
|
+
_, _, Vt = np.linalg.svd(np.sqrt(w_train)[:, None] * (Yc / scale), full_matrices=False)
|
|
40
|
+
V = Vt[:k].T
|
|
41
|
+
return linear_model((Yc / scale) @ V, t_train, w_train, ((Y_test - mean) / scale) @ V)
|
|
42
|
+
return model
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def estimator_model(estimator):
|
|
46
|
+
"""Wrap a scikit-learn style regressor (``fit``/``predict``) as a model for `leave_one_group_out`.
|
|
47
|
+
|
|
48
|
+
The estimator is copied and refitted in every fold, so a pipeline that
|
|
49
|
+
standardises or reduces the annotations does so on the training groups only.
|
|
50
|
+
Unequal weights are passed as ``sample_weight``, which the estimator must
|
|
51
|
+
accept. A Pipeline does not, so use equal weights with pipelines.
|
|
52
|
+
"""
|
|
53
|
+
def model(Y_train, t_train, w_train, Y_test):
|
|
54
|
+
fitted = copy.deepcopy(estimator)
|
|
55
|
+
if np.allclose(w_train, w_train[0]):
|
|
56
|
+
fitted.fit(Y_train, t_train)
|
|
57
|
+
else:
|
|
58
|
+
fitted.fit(Y_train, t_train, sample_weight=w_train)
|
|
59
|
+
return fitted.predict(Y_test[None, :])[0]
|
|
60
|
+
return model
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class LOGOResult:
|
|
65
|
+
"""Leave-one-group-out predictions and out-of-sample R².
|
|
66
|
+
|
|
67
|
+
Attributes
|
|
68
|
+
----------
|
|
69
|
+
predictions : prediction of each group from the other groups, (M,) or (M, k).
|
|
70
|
+
baseline : weighted mean of the other groups, same shape.
|
|
71
|
+
r2 : 1 - Σw(t - prediction)² / Σw(t - baseline)²; negative if the model
|
|
72
|
+
predicts worse than the mean of the other groups.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
predictions: np.ndarray
|
|
76
|
+
baseline: np.ndarray
|
|
77
|
+
r2: float | np.ndarray
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def leave_one_group_out(target, Y, weights=None, model=linear_model):
|
|
81
|
+
"""Predict each group's ``target`` from its annotations, fitting on the other groups.
|
|
82
|
+
|
|
83
|
+
``target`` is group-level, (M,) or (M, k): for example group means of a
|
|
84
|
+
component or of features. ``weights`` default to equal (the population of
|
|
85
|
+
groups); pass group sizes to weight by individuals. ``model`` is either a
|
|
86
|
+
function ``model(Y_train, t_train, w_train, Y_test)`` returning the
|
|
87
|
+
prediction for the held-out group, or a scikit-learn style regressor (see
|
|
88
|
+
`estimator_model`). Either way it must contain every data-dependent choice.
|
|
89
|
+
"""
|
|
90
|
+
if hasattr(model, "fit") and hasattr(model, "predict"):
|
|
91
|
+
model = estimator_model(model)
|
|
92
|
+
target = np.asarray(target, float)
|
|
93
|
+
Y = np.asarray(Y, float).reshape(len(target), -1)
|
|
94
|
+
M = len(target)
|
|
95
|
+
w = np.ones(M) if weights is None else np.asarray(weights, float)
|
|
96
|
+
|
|
97
|
+
predictions = np.empty_like(target)
|
|
98
|
+
baseline = np.empty_like(target)
|
|
99
|
+
for m in range(M):
|
|
100
|
+
train = np.arange(M) != m
|
|
101
|
+
predictions[m] = model(Y[train], target[train], w[train], Y[m])
|
|
102
|
+
baseline[m] = w[train] @ target[train] / w[train].sum()
|
|
103
|
+
|
|
104
|
+
w_ = w.reshape((-1,) + (1,) * (target.ndim - 1))
|
|
105
|
+
r2 = 1 - (w_ * (target - predictions) ** 2).sum(0) / (w_ * (target - baseline) ** 2).sum(0)
|
|
106
|
+
return LOGOResult(predictions, baseline, float(r2) if target.ndim == 1 else r2)
|
groupunit/weights.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Weighting groups: variance components, optimal weights and effective numbers of groups (Section 4.1, Appendix B.7).
|
|
2
|
+
|
|
3
|
+
A group mean deviates from what the annotations predict through sampling
|
|
4
|
+
error, with variance σ²_w / n_m, and through group-level heterogeneity, with
|
|
5
|
+
variance τ². Their balance decides whether size weights are efficient.
|
|
6
|
+
"""
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from .core import check_groups, group_means
|
|
12
|
+
from .diagnostics import effective_number
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class VarianceComponents:
|
|
17
|
+
"""Within-group variance σ²_w and between-group heterogeneity τ² of one score."""
|
|
18
|
+
|
|
19
|
+
sigma2_w: float
|
|
20
|
+
tau2: float
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def variance_components(t, groups, Y=None):
|
|
24
|
+
"""Estimate σ²_w and τ² for a score ``t`` (N,), such as a component or a single feature.
|
|
25
|
+
|
|
26
|
+
σ²_w is the pooled within-group variance. τ² is a moment estimate from the
|
|
27
|
+
residuals of an equally weighted regression of the group means on the
|
|
28
|
+
annotations ``Y`` (on an intercept alone if ``Y`` is None), with the expected
|
|
29
|
+
sampling-error part removed; it is truncated at zero.
|
|
30
|
+
"""
|
|
31
|
+
t = np.asarray(t, float)
|
|
32
|
+
M = None if Y is None else len(Y)
|
|
33
|
+
groups, n = check_groups(groups, M)
|
|
34
|
+
M = len(n)
|
|
35
|
+
tbar = group_means(t, groups, M)
|
|
36
|
+
sigma2_w = float(((t - tbar[groups]) ** 2).sum() / (len(t) - M))
|
|
37
|
+
|
|
38
|
+
Z = np.ones((M, 1)) if Y is None else np.column_stack([np.ones(M), np.asarray(Y, float)])
|
|
39
|
+
H = Z @ np.linalg.pinv(Z)
|
|
40
|
+
df = M - np.linalg.matrix_rank(Z)
|
|
41
|
+
if df <= 0:
|
|
42
|
+
raise ValueError("the annotations fit the group means exactly (saturated); τ² cannot be "
|
|
43
|
+
"estimated from their residuals. Reduce the annotations or pass Y=None.")
|
|
44
|
+
resid = tbar - H @ tbar
|
|
45
|
+
# E[RSS] = Σ (1 - h_mm)(τ² + σ²_w / n_m), with Σ (1 - h_mm) = df
|
|
46
|
+
leverage_free = 1 - np.diag(H)
|
|
47
|
+
tau2 = (resid @ resid - sigma2_w * (leverage_free / n).sum()) / df
|
|
48
|
+
return VarianceComponents(sigma2_w=sigma2_w, tau2=float(max(tau2, 0.0)))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def optimal_weights(n, tau2, sigma2_w):
|
|
52
|
+
"""Most precise group weights, ∝ 1 / (τ² + σ²_w / n_m), normalised to sum to one."""
|
|
53
|
+
w = 1 / (tau2 + sigma2_w / np.asarray(n, float))
|
|
54
|
+
return w / w.sum()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def exchangeable_weights(n, tau2, sigma2_w):
|
|
58
|
+
"""Group weights 1 / sqrt(τ² + σ²_w / n_m) for permutation tests, normalised to sum to one.
|
|
59
|
+
|
|
60
|
+
With these weights every group's term in a weighted cross-product has the
|
|
61
|
+
same variance under the null, so reassigning annotation rows among groups
|
|
62
|
+
is a valid test whichever groups carry atypical profiles (see
|
|
63
|
+
`groupunit.inference.pairing_ratio`). They differ from `optimal_weights`,
|
|
64
|
+
which are the square of these and are the most precise for estimation.
|
|
65
|
+
"""
|
|
66
|
+
w = 1 / np.sqrt(tau2 + sigma2_w / np.asarray(n, float))
|
|
67
|
+
return w / w.sum()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def pooled_variance_components(X, groups):
|
|
71
|
+
"""σ²_w and τ² averaged over the columns of ``X``, for weights shared by all features.
|
|
72
|
+
|
|
73
|
+
Each column's τ² is estimated around its grand mean (no annotations), which
|
|
74
|
+
is what the null hypothesis of no association implies.
|
|
75
|
+
"""
|
|
76
|
+
X = np.asarray(X, float).reshape(len(groups), -1)
|
|
77
|
+
parts = [variance_components(col, groups) for col in X.T]
|
|
78
|
+
return VarianceComponents(sigma2_w=float(np.mean([c.sigma2_w for c in parts])),
|
|
79
|
+
tau2=float(np.mean([c.tau2 for c in parts])))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def effective_groups(w, n=None, tau2=None, sigma2_w=None):
|
|
83
|
+
"""Effective number of groups for weights ``w``.
|
|
84
|
+
|
|
85
|
+
Without variance components this is Kish's formula, (Σw)² / Σw², which
|
|
86
|
+
assumes every group mean is equally noisy. With ``n``, ``tau2`` and
|
|
87
|
+
``sigma2_w`` it is the model-based value
|
|
88
|
+
τ²(Σw)² / Σ w²(τ² + σ²_w / n), never larger than Kish's.
|
|
89
|
+
"""
|
|
90
|
+
w = np.asarray(w, float)
|
|
91
|
+
if tau2 is None and sigma2_w is None:
|
|
92
|
+
return float(effective_number(w))
|
|
93
|
+
if n is None or tau2 is None or sigma2_w is None:
|
|
94
|
+
raise ValueError("the model-based value needs n, tau2 and sigma2_w")
|
|
95
|
+
v = tau2 + sigma2_w / np.asarray(n, float)
|
|
96
|
+
return float(tau2 * w.sum() ** 2 / (w**2 * v).sum())
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def max_effective_groups(n, tau2, sigma2_w):
|
|
100
|
+
"""Largest achievable effective number of groups, Σ τ² / (τ² + σ²_w / n_m) <= M."""
|
|
101
|
+
n = np.asarray(n, float)
|
|
102
|
+
return float((tau2 / (tau2 + sigma2_w / n)).sum())
|