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/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""groupunit: analysis of individual-level features with group-level annotations.
|
|
2
|
+
|
|
3
|
+
Companion software to Kmecl, "The group is the unit: limits of correlation,
|
|
4
|
+
PLS and CCA with group-level variables". See `groupunit.core` for the
|
|
5
|
+
notation and array conventions shared by all modules.
|
|
6
|
+
"""
|
|
7
|
+
from .core import (
|
|
8
|
+
annotation_rank,
|
|
9
|
+
encode_groups,
|
|
10
|
+
group_means,
|
|
11
|
+
group_sizes,
|
|
12
|
+
scatter_matrices,
|
|
13
|
+
wcentre,
|
|
14
|
+
weighted_basis,
|
|
15
|
+
weighted_corr,
|
|
16
|
+
weighted_r2,
|
|
17
|
+
)
|
|
18
|
+
from .design import describe, r2_null, reduce_annotations, single_group_annotations
|
|
19
|
+
from .diagnostics import (
|
|
20
|
+
congruence,
|
|
21
|
+
contributions,
|
|
22
|
+
effective_number,
|
|
23
|
+
group_shares,
|
|
24
|
+
leave_out,
|
|
25
|
+
lens,
|
|
26
|
+
lens_congruence_null,
|
|
27
|
+
lens_null,
|
|
28
|
+
participation_ratio,
|
|
29
|
+
)
|
|
30
|
+
from .inference import (
|
|
31
|
+
cca_test,
|
|
32
|
+
correlation_test,
|
|
33
|
+
estimator_test,
|
|
34
|
+
pairing_ratio,
|
|
35
|
+
pairing_terms,
|
|
36
|
+
permutation_test,
|
|
37
|
+
pls_test,
|
|
38
|
+
size_check,
|
|
39
|
+
)
|
|
40
|
+
from .methods import cca, lda, pls
|
|
41
|
+
from .scores import between_share, decompose_score, feature_between_share, group_scores
|
|
42
|
+
from .similarity import (
|
|
43
|
+
compare_similarity,
|
|
44
|
+
distance_similarity,
|
|
45
|
+
similarity_decomposition,
|
|
46
|
+
standardised_pattern,
|
|
47
|
+
typicality_pattern,
|
|
48
|
+
)
|
|
49
|
+
from .simulate import lognormal_sizes, simulate
|
|
50
|
+
from .validation import estimator_model, leave_one_group_out, linear_model, pca_regression
|
|
51
|
+
from .weights import (
|
|
52
|
+
effective_groups,
|
|
53
|
+
exchangeable_weights,
|
|
54
|
+
max_effective_groups,
|
|
55
|
+
optimal_weights,
|
|
56
|
+
pooled_variance_components,
|
|
57
|
+
variance_components,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
__version__ = "0.2.0"
|
groupunit/core.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Basic quantities: group codes, group means, weighted centring and weighted fits.
|
|
2
|
+
|
|
3
|
+
Conventions used throughout the package (Section 2 of the paper):
|
|
4
|
+
|
|
5
|
+
X (N, p) features of individuals
|
|
6
|
+
groups (N,) integer group codes 0..M-1 (see `encode_groups`)
|
|
7
|
+
Y (M, q) annotation table, one row per group (the paper's Ỹ)
|
|
8
|
+
n (M,) group sizes
|
|
9
|
+
w (M,) group weights; size weights w = n unless stated otherwise
|
|
10
|
+
tbar (M,) or (M, k) group means of one or more scores
|
|
11
|
+
|
|
12
|
+
Functions centre their inputs themselves (X over individuals, group-level
|
|
13
|
+
quantities with the group weights), so raw values can be passed.
|
|
14
|
+
"""
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def encode_groups(labels, order=None):
|
|
19
|
+
"""Turn arbitrary group labels into integer codes 0..M-1.
|
|
20
|
+
|
|
21
|
+
Returns ``(codes, names)``, where ``names[m]`` is the label of group m.
|
|
22
|
+
Pass ``order`` (the labels in the row order of your annotation table) so
|
|
23
|
+
that code m refers to row m of that table.
|
|
24
|
+
"""
|
|
25
|
+
labels = np.asarray(labels)
|
|
26
|
+
if order is None:
|
|
27
|
+
names, codes = np.unique(labels, return_inverse=True)
|
|
28
|
+
return codes, names
|
|
29
|
+
names = np.asarray(order)
|
|
30
|
+
index = {label: m for m, label in enumerate(names.tolist())}
|
|
31
|
+
try:
|
|
32
|
+
codes = np.array([index[label] for label in labels.tolist()], dtype=int)
|
|
33
|
+
except KeyError as err:
|
|
34
|
+
raise ValueError(f"label {err.args[0]!r} is not in `order`") from None
|
|
35
|
+
return codes, names
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def check_groups(groups, M=None):
|
|
39
|
+
"""Validate integer group codes and return ``(groups, n)``.
|
|
40
|
+
|
|
41
|
+
``M`` is the number of groups (rows of the annotation table); every group
|
|
42
|
+
must contain at least one individual.
|
|
43
|
+
"""
|
|
44
|
+
groups = np.asarray(groups)
|
|
45
|
+
if groups.ndim != 1 or not np.issubdtype(groups.dtype, np.integer):
|
|
46
|
+
raise ValueError("groups must be a 1-D array of integer codes; use encode_groups() for labels")
|
|
47
|
+
if groups.size == 0 or groups.min() < 0:
|
|
48
|
+
raise ValueError("group codes must be non-negative integers")
|
|
49
|
+
M = groups.max() + 1 if M is None else M
|
|
50
|
+
if groups.max() >= M:
|
|
51
|
+
raise ValueError(f"group code {groups.max()} is out of range for {M} groups")
|
|
52
|
+
n = np.bincount(groups, minlength=M)
|
|
53
|
+
if (n == 0).any():
|
|
54
|
+
raise ValueError(f"groups {np.flatnonzero(n == 0).tolist()} have no individuals")
|
|
55
|
+
return groups, n
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def group_sizes(groups, M=None):
|
|
59
|
+
"""Number of individuals in each group, ``n``."""
|
|
60
|
+
return check_groups(groups, M)[1]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def group_means(X, groups, M=None):
|
|
64
|
+
"""Group means of a vector or of the columns of a matrix: ``(M,)`` or ``(M, p)``."""
|
|
65
|
+
groups, n = check_groups(groups, M)
|
|
66
|
+
X = np.asarray(X, float)
|
|
67
|
+
sums = np.zeros((len(n),) + X.shape[1:])
|
|
68
|
+
np.add.at(sums, groups, X)
|
|
69
|
+
return sums / n.reshape((-1,) + (1,) * (X.ndim - 1))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def wcentre(A, w):
|
|
73
|
+
"""Centre the rows of ``A`` (vector or matrix) on their ``w``-weighted mean."""
|
|
74
|
+
A = np.asarray(A, float)
|
|
75
|
+
w = np.asarray(w, float)
|
|
76
|
+
return A - np.tensordot(w, A, axes=1) / w.sum()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def weighted_corr(a, b, w):
|
|
80
|
+
"""Weighted correlation across groups, r_w(a, b) (Section 2.1).
|
|
81
|
+
|
|
82
|
+
``a`` and ``b`` are vectors or matrices with one row per group. Returns a
|
|
83
|
+
float for two vectors, otherwise the matrix of correlations between the
|
|
84
|
+
columns of ``a`` (rows of the result) and those of ``b``.
|
|
85
|
+
"""
|
|
86
|
+
w = np.asarray(w, float)
|
|
87
|
+
a, b = wcentre(a, w), wcentre(b, w)
|
|
88
|
+
a2, b2 = a.reshape(len(a), -1), b.reshape(len(b), -1)
|
|
89
|
+
cov = a2.T @ (w[:, None] * b2)
|
|
90
|
+
sd_a = np.sqrt(w @ a2**2)
|
|
91
|
+
sd_b = np.sqrt(w @ b2**2)
|
|
92
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
93
|
+
r = cov / np.outer(sd_a, sd_b)
|
|
94
|
+
if a.ndim == 1 and b.ndim == 1:
|
|
95
|
+
return float(r[0, 0])
|
|
96
|
+
if a.ndim == 1:
|
|
97
|
+
return r[0]
|
|
98
|
+
if b.ndim == 1:
|
|
99
|
+
return r[:, 0]
|
|
100
|
+
return r
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def weighted_basis(A, w):
|
|
104
|
+
"""Orthonormal basis of the column space of ``diag(sqrt(w)) @ wcentre(A, w)``.
|
|
105
|
+
|
|
106
|
+
Its number of columns is the rank of the weighted-centred table, which for
|
|
107
|
+
an annotation table is r (Section 2.1).
|
|
108
|
+
"""
|
|
109
|
+
A = np.asarray(A, float)
|
|
110
|
+
A = A.reshape(len(A), -1)
|
|
111
|
+
w = np.asarray(w, float)
|
|
112
|
+
Z = np.sqrt(w)[:, None] * wcentre(A, w)
|
|
113
|
+
U, s, _ = np.linalg.svd(Z, full_matrices=False)
|
|
114
|
+
tol = s.max() * max(Z.shape) * np.finfo(float).eps
|
|
115
|
+
return U[:, s > tol]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def annotation_rank(Y, w):
|
|
119
|
+
"""Rank r of the annotation table after weighted centring; r <= min(q, M - 1)."""
|
|
120
|
+
return weighted_basis(Y, w).shape[1]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def weighted_r2(tbar, Y, w):
|
|
124
|
+
"""R²_w of a weighted regression of group means on the annotations (Result 3a).
|
|
125
|
+
|
|
126
|
+
Returns a float for a vector ``tbar``, or one value per column of a matrix.
|
|
127
|
+
"""
|
|
128
|
+
w = np.asarray(w, float)
|
|
129
|
+
tbar = np.asarray(tbar, float)
|
|
130
|
+
z = np.sqrt(w).reshape((-1,) + (1,) * (tbar.ndim - 1)) * wcentre(tbar, w)
|
|
131
|
+
Q = weighted_basis(Y, w)
|
|
132
|
+
explained = ((Q.T @ z) ** 2).sum(0)
|
|
133
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
134
|
+
r2 = explained / (z**2).sum(0)
|
|
135
|
+
return float(r2) if tbar.ndim == 1 else r2
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def scatter_matrices(X, groups):
|
|
139
|
+
"""Total, between-group and within-group sums of squares and cross-products.
|
|
140
|
+
|
|
141
|
+
Returns ``(S_T, S_B, S_W)`` with ``S_T = S_B + S_W`` (Section 2.1).
|
|
142
|
+
"""
|
|
143
|
+
groups, n = check_groups(groups)
|
|
144
|
+
X = np.asarray(X, float)
|
|
145
|
+
Xc = X - X.mean(0)
|
|
146
|
+
Xbar = group_means(Xc, groups)
|
|
147
|
+
E = Xc - Xbar[groups]
|
|
148
|
+
return Xc.T @ Xc, Xbar.T @ (n[:, None] * Xbar), E.T @ E
|
groupunit/design.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""What a design can show before any analysis: counts, ranks and regimes (Result 3b, the regimes of Section 3.3, Box 1)."""
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
from scipy import stats
|
|
6
|
+
|
|
7
|
+
from .core import annotation_rank, check_groups, group_means, wcentre
|
|
8
|
+
from .diagnostics import effective_number
|
|
9
|
+
from .inference import pairing_terms
|
|
10
|
+
from .scores import feature_between_share
|
|
11
|
+
from .weights import pooled_variance_components
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# a departure of the pairing ratio from 1 that `describe` reports; a trigger to check, not a safe range
|
|
15
|
+
PAIRING_TOLERANCE = (0.95, 1.05)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class DesignSummary:
|
|
20
|
+
"""Counts and ratios that bound what a design with group-level annotations can show.
|
|
21
|
+
|
|
22
|
+
Attributes
|
|
23
|
+
----------
|
|
24
|
+
N, M, q : numbers of individuals, groups and annotations.
|
|
25
|
+
r : rank of the size-weighted centred annotation table.
|
|
26
|
+
kappa : annotation ratio r / (M - 1); 1 means saturated.
|
|
27
|
+
kish_groups : Kish effective number of groups under size weights.
|
|
28
|
+
max_components : number of non-trivial PLS or CCA components, min(rank X̄, r).
|
|
29
|
+
pairing_ratio : `groupunit.inference.pairing_ratio` for size weights, with
|
|
30
|
+
variance components pooled over the features if they were given, and
|
|
31
|
+
group means taken as equally variable otherwise. Above 1, size-weighted
|
|
32
|
+
permutation tests lean liberal; below 1, conservative. No range of the
|
|
33
|
+
ratio is safe for every design: the same ratio does more harm with more
|
|
34
|
+
groups (Result 5d), so check a test's level with
|
|
35
|
+
`groupunit.inference.size_check`.
|
|
36
|
+
pairing_group : the group with the largest term of the ratio
|
|
37
|
+
(`groupunit.inference.pairing_terms`), the one most responsible for
|
|
38
|
+
an excess above 1.
|
|
39
|
+
feature_between_share : tr S_B / tr S_T, if features were given.
|
|
40
|
+
single_group : indices of annotations that single out one group (Section 3.1).
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
N: int
|
|
44
|
+
M: int
|
|
45
|
+
q: int
|
|
46
|
+
r: int
|
|
47
|
+
kappa: float
|
|
48
|
+
kish_groups: float
|
|
49
|
+
max_components: int
|
|
50
|
+
pairing_ratio: float
|
|
51
|
+
pairing_group: int = 0
|
|
52
|
+
feature_between_share: float | None = None
|
|
53
|
+
single_group: list = field(default_factory=list)
|
|
54
|
+
annotation_names: list | None = None
|
|
55
|
+
|
|
56
|
+
def __str__(self):
|
|
57
|
+
lines = [
|
|
58
|
+
f"individuals N = {self.N}, groups M = {self.M}, annotations q = {self.q}",
|
|
59
|
+
f"annotation rank r = {self.r}, annotation ratio kappa = r/(M-1) = {self.kappa:.2f}",
|
|
60
|
+
f"effective number of groups under size weights (Kish) = {self.kish_groups:.1f}",
|
|
61
|
+
f"at most {self.max_components} non-trivial PLS/CCA components",
|
|
62
|
+
]
|
|
63
|
+
if self.feature_between_share is not None:
|
|
64
|
+
lines.append(f"between-group share of the features = {self.feature_between_share:.3f}")
|
|
65
|
+
if self.kappa >= 1:
|
|
66
|
+
lines.append("SATURATED: CCA equals discriminant analysis of group labels and cannot "
|
|
67
|
+
"respond to the annotation values; reduce the annotations first.")
|
|
68
|
+
elif self.kappa >= 0.8:
|
|
69
|
+
lines.append("NEAR-SATURATED: the null mean of R² is close to 1, and PLS loadings "
|
|
70
|
+
"are dominated by the lens; consider reducing the annotations.")
|
|
71
|
+
lines.append(f"pairing ratio of sizes with annotation profiles = {self.pairing_ratio:.2f} "
|
|
72
|
+
f"(largest term: group {self.pairing_group})")
|
|
73
|
+
# no fixed range of the ratio is safe: the same ratio does more harm with more groups
|
|
74
|
+
# (Result 5d), so the summary never declares a design safe and points to size_check
|
|
75
|
+
if self.pairing_ratio > PAIRING_TOLERANCE[1]:
|
|
76
|
+
lines.append("UNUSUAL PAIRING: large groups carry atypical profiles, so size-weighted group "
|
|
77
|
+
"permutation tests (weights='size', cca_test, estimator_test) lean liberal here, "
|
|
78
|
+
"more so with more groups; keep the default exchangeable weights.")
|
|
79
|
+
elif self.pairing_ratio < PAIRING_TOLERANCE[0]:
|
|
80
|
+
lines.append("UNUSUAL PAIRING: size-weighted group permutation tests lean conservative here; "
|
|
81
|
+
"the default exchangeable weights recover power.")
|
|
82
|
+
lines.append("A ratio near 1 does not guarantee the level of a test; check the test you run "
|
|
83
|
+
"with size_check().")
|
|
84
|
+
if self.single_group:
|
|
85
|
+
names = self.annotation_names or list(range(self.q))
|
|
86
|
+
flagged = ", ".join(str(names[j]) for j in self.single_group)
|
|
87
|
+
lines.append(f"annotations that single out one group: {flagged}")
|
|
88
|
+
return "\n".join(lines)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def single_group_annotations(Y, atol=1e-12):
|
|
92
|
+
"""Indices of annotation columns in which exactly one group differs from all others.
|
|
93
|
+
|
|
94
|
+
Such an annotation correlates with any score exactly as that group's mean
|
|
95
|
+
does, so it describes one group rather than a relation.
|
|
96
|
+
"""
|
|
97
|
+
Y = np.asarray(Y, float)
|
|
98
|
+
flagged = []
|
|
99
|
+
for j, col in enumerate(Y.T):
|
|
100
|
+
values, counts = np.unique(col, return_counts=True)
|
|
101
|
+
mode = values[np.argmax(counts)]
|
|
102
|
+
if np.sum(~np.isclose(col, mode, rtol=0, atol=atol)) == 1:
|
|
103
|
+
flagged.append(j)
|
|
104
|
+
return flagged
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def describe(groups, Y, X=None, annotation_names=None):
|
|
108
|
+
"""Summarise a design: N, M, q, r, kappa, effective groups and flagged annotations (Box 1, items 1-4)."""
|
|
109
|
+
Y = np.asarray(Y, float)
|
|
110
|
+
groups, n = check_groups(groups, len(Y))
|
|
111
|
+
M, q = Y.shape
|
|
112
|
+
r = annotation_rank(Y, n)
|
|
113
|
+
max_components = r
|
|
114
|
+
share = None
|
|
115
|
+
terms = pairing_terms(Y, n)
|
|
116
|
+
if X is not None:
|
|
117
|
+
X = np.asarray(X, float)
|
|
118
|
+
Xbar = group_means(X - X.mean(0), groups, M)
|
|
119
|
+
max_components = min(r, annotation_rank(Xbar, n))
|
|
120
|
+
share = feature_between_share(X, groups)
|
|
121
|
+
vc = pooled_variance_components(X, groups)
|
|
122
|
+
terms = pairing_terms(Y, n, tau2=vc.tau2, sigma2_w=vc.sigma2_w)
|
|
123
|
+
return DesignSummary(
|
|
124
|
+
N=len(groups), M=M, q=q, r=r, kappa=r / (M - 1),
|
|
125
|
+
kish_groups=effective_number(n),
|
|
126
|
+
max_components=max_components,
|
|
127
|
+
pairing_ratio=terms.ratio,
|
|
128
|
+
pairing_group=terms.largest,
|
|
129
|
+
feature_between_share=share,
|
|
130
|
+
single_group=single_group_annotations(Y),
|
|
131
|
+
annotation_names=None if annotation_names is None else list(annotation_names),
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def r2_null(r, M):
|
|
136
|
+
"""Null distribution of the group-level R² of any score on r annotations (Result 3b).
|
|
137
|
+
|
|
138
|
+
Beta(r/2, (M-1-r)/2), with mean r/(M-1). Returns a frozen ``scipy.stats``
|
|
139
|
+
distribution. At r = M - 1 the distribution collapses to 1 for every score.
|
|
140
|
+
|
|
141
|
+
It assumes the weighted group means point in a random direction, which
|
|
142
|
+
`groupunit.weights.optimal_weights` achieve. With size weights and unequal
|
|
143
|
+
group sizes the largest groups dominate both the score and the
|
|
144
|
+
annotations, and the null R² is larger, about r / M_eff for small r
|
|
145
|
+
(Kish's number); treat this distribution as a lower bound there.
|
|
146
|
+
"""
|
|
147
|
+
if not 0 < r < M - 1:
|
|
148
|
+
raise ValueError(f"need 0 < r < M - 1; at r = M - 1 every score has R² = 1 (r={r}, M={M})")
|
|
149
|
+
return stats.beta(r / 2, (M - 1 - r) / 2)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def reduce_annotations(Y, w, k, standardise=False):
|
|
153
|
+
"""First k weighted principal components of the annotation table (Box 1, item 3).
|
|
154
|
+
|
|
155
|
+
Reducing the annotations in advance moves a design out of the saturated
|
|
156
|
+
regime. Returns ``(scores, explained)``: the (M, k) component scores and the
|
|
157
|
+
share of the weighted annotation variance each one holds. Inside a
|
|
158
|
+
permutation test or cross-validation, call this on the training groups only.
|
|
159
|
+
"""
|
|
160
|
+
Y = np.asarray(Y, float)
|
|
161
|
+
w = np.asarray(w, float)
|
|
162
|
+
Yc = wcentre(Y, w)
|
|
163
|
+
if standardise:
|
|
164
|
+
sd = np.sqrt(w @ Yc**2 / w.sum())
|
|
165
|
+
Yc = Yc / np.where(sd > 0, sd, 1.0)
|
|
166
|
+
_, s, Vt = np.linalg.svd(np.sqrt(w)[:, None] * Yc, full_matrices=False)
|
|
167
|
+
explained = s**2 / (s**2).sum()
|
|
168
|
+
return Yc @ Vt[:k].T, explained[:k]
|
groupunit/diagnostics.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Diagnostics computable from group means, annotations and group sizes (Section 5).
|
|
2
|
+
|
|
3
|
+
All functions here work on group-level inputs, so they also apply to
|
|
4
|
+
published results: digitised group means of a component, the annotation
|
|
5
|
+
table and the group sizes are enough.
|
|
6
|
+
"""
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from .core import wcentre
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def effective_number(w, axis=0):
|
|
15
|
+
"""(Σ|w|)² / Σw²: the number of equal weights with the same concentration (Sections 4.1 and 5).
|
|
16
|
+
|
|
17
|
+
With group sizes it is Kish's effective number of groups, with eigenvalues
|
|
18
|
+
the participation ratio, and with group shares the effective number of
|
|
19
|
+
groups behind a component.
|
|
20
|
+
"""
|
|
21
|
+
w = np.abs(np.asarray(w, float))
|
|
22
|
+
return w.sum(axis) ** 2 / (w**2).sum(axis)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def participation_ratio(A):
|
|
26
|
+
"""Participation ratio ν of a symmetric matrix, or of a vector of its eigenvalues."""
|
|
27
|
+
A = np.asarray(A, float)
|
|
28
|
+
eigenvalues = np.linalg.eigvalsh(A) if A.ndim == 2 else A
|
|
29
|
+
return float(effective_number(np.clip(eigenvalues, 0, None)))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def congruence(a, b):
|
|
33
|
+
"""Tucker's congruence coefficient, the cosine between loading vectors (Section 5).
|
|
34
|
+
|
|
35
|
+
For two vectors returns a float; for matrices, the congruences between
|
|
36
|
+
their columns.
|
|
37
|
+
"""
|
|
38
|
+
a, b = np.asarray(a, float), np.asarray(b, float)
|
|
39
|
+
a2 = a.reshape(len(a), -1)
|
|
40
|
+
b2 = b.reshape(len(b), -1)
|
|
41
|
+
c = (a2 / np.linalg.norm(a2, axis=0)).T @ (b2 / np.linalg.norm(b2, axis=0))
|
|
42
|
+
if a.ndim == 1 and b.ndim == 1:
|
|
43
|
+
return float(c[0, 0])
|
|
44
|
+
return c[0] if a.ndim == 1 else c[:, 0] if b.ndim == 1 else c
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def contributions(tbar, Y, w):
|
|
48
|
+
"""Group × annotation contribution matrix with entries w_m t̄_m ỹ_mj (the identity, Section 2.2).
|
|
49
|
+
|
|
50
|
+
Column sums are the (unnormalised) annotation loadings of the component.
|
|
51
|
+
"""
|
|
52
|
+
tbar = wcentre(np.asarray(tbar, float), w)
|
|
53
|
+
if tbar.ndim != 1:
|
|
54
|
+
raise ValueError("contributions takes the group means of a single component")
|
|
55
|
+
return (np.asarray(w, float) * tbar)[:, None] * wcentre(Y, w)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class GroupShares:
|
|
60
|
+
"""Additive group shares of a component's annotation loading.
|
|
61
|
+
|
|
62
|
+
Shapes are (M,) for one component, (M, k) for k components.
|
|
63
|
+
|
|
64
|
+
Attributes
|
|
65
|
+
----------
|
|
66
|
+
loading : ℓ = Σ_m w_m t̄_m ỹ_m, shape (q,) or (q, k).
|
|
67
|
+
terms : s_m, each group's term projected onto the unit loading; sums to ‖ℓ‖.
|
|
68
|
+
share : s_m / Σ s; sums to one, and equals the groups' Shapley values for ‖ℓ‖².
|
|
69
|
+
Negative for groups working against the component.
|
|
70
|
+
abs_share : |s_m| / Σ|s|, never negative.
|
|
71
|
+
m_eff : effective number of groups behind the component (descriptive).
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
loading: np.ndarray
|
|
75
|
+
terms: np.ndarray
|
|
76
|
+
share: np.ndarray
|
|
77
|
+
abs_share: np.ndarray
|
|
78
|
+
m_eff: float | np.ndarray
|
|
79
|
+
|
|
80
|
+
def top(self, k=3):
|
|
81
|
+
"""Indices of the k groups with the largest absolute shares (first component if several)."""
|
|
82
|
+
a = self.abs_share if self.abs_share.ndim == 1 else self.abs_share[:, 0]
|
|
83
|
+
return np.argsort(-a)[:k]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def group_shares(tbar, Y, w):
|
|
87
|
+
"""Group shares of the annotation loading of one or more components (Section 5, Appendix B.8).
|
|
88
|
+
|
|
89
|
+
``tbar`` holds each group's mean score, (M,) or (M, k); ``w`` are the group
|
|
90
|
+
weights used by the analysis (group sizes for analyses of individuals).
|
|
91
|
+
Both ``tbar`` and ``Y`` are centred with ``w``, which shares require.
|
|
92
|
+
"""
|
|
93
|
+
w = np.asarray(w, float)
|
|
94
|
+
tbar = np.asarray(tbar, float)
|
|
95
|
+
T = wcentre(tbar.reshape(len(tbar), -1), w)
|
|
96
|
+
Yc = wcentre(Y, w)
|
|
97
|
+
wT = w[:, None] * T
|
|
98
|
+
loading = Yc.T @ wT
|
|
99
|
+
unit = loading / np.linalg.norm(loading, axis=0)
|
|
100
|
+
terms = wT * (Yc @ unit)
|
|
101
|
+
share = terms / terms.sum(0)
|
|
102
|
+
abs_share = np.abs(terms) / np.abs(terms).sum(0)
|
|
103
|
+
m_eff = effective_number(terms)
|
|
104
|
+
if tbar.ndim == 1:
|
|
105
|
+
return GroupShares(loading[:, 0], terms[:, 0], share[:, 0], abs_share[:, 0], float(m_eff[0]))
|
|
106
|
+
return GroupShares(loading, terms, share, abs_share, m_eff)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True)
|
|
110
|
+
class LeaveOut:
|
|
111
|
+
"""A component's loading with some groups' terms removed, the component held fixed.
|
|
112
|
+
|
|
113
|
+
Attributes
|
|
114
|
+
----------
|
|
115
|
+
dropped : indices of the removed groups.
|
|
116
|
+
loading : (q,) the loading recomputed over the remaining groups.
|
|
117
|
+
congruence : Tucker's congruence of the remaining loading with the full one.
|
|
118
|
+
norm_ratio : ‖remaining loading‖ / ‖full loading‖.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
dropped: np.ndarray
|
|
122
|
+
loading: np.ndarray
|
|
123
|
+
congruence: float
|
|
124
|
+
norm_ratio: float
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def leave_out(tbar, Y, w, drop):
|
|
128
|
+
"""A component's loading without groups ``drop``, the component held fixed (Section 5, Appendix B.8).
|
|
129
|
+
|
|
130
|
+
The other groups' means are kept unchanged, and the loading is the one the
|
|
131
|
+
data without the dropped groups would give, re-centred over the remaining
|
|
132
|
+
groups. With group terms u_m (see `contributions`), dropping one group gives
|
|
133
|
+
|
|
134
|
+
ℓ₋m = ℓ − u_m · W / (W − w_m),
|
|
135
|
+
|
|
136
|
+
so a group removes more than its own term, because the centroid moves away
|
|
137
|
+
from it, and the loading reverses if the group's share exceeds (W − w_m) / W.
|
|
138
|
+
For several groups S, ℓ₋S = ℓ − Σ_S u_m − (Σ_S w_m t̄_m)(Σ_S w_m ỹ_m) / (W − W_S).
|
|
139
|
+
To refit instead, rerun the method without those groups. Choose ``drop``
|
|
140
|
+
with `GroupShares.top`.
|
|
141
|
+
"""
|
|
142
|
+
w = np.asarray(w, float)
|
|
143
|
+
t = wcentre(np.asarray(tbar, float), w)
|
|
144
|
+
Yc = wcentre(Y, w)
|
|
145
|
+
terms = (w * t)[:, None] * Yc
|
|
146
|
+
full = terms.sum(0)
|
|
147
|
+
S = np.atleast_1d(np.asarray(drop, int))
|
|
148
|
+
W_rest = w.sum() - w[S].sum()
|
|
149
|
+
rest = full - terms[S].sum(0) - (w[S] @ t[S]) * (w[S] @ Yc[S]) / W_rest
|
|
150
|
+
return LeaveOut(
|
|
151
|
+
dropped=S,
|
|
152
|
+
loading=rest,
|
|
153
|
+
congruence=congruence(rest, full),
|
|
154
|
+
norm_ratio=float(np.linalg.norm(rest) / np.linalg.norm(full)),
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _group_mean_cov(n, tau2, sigma2_w):
|
|
159
|
+
"""Diagonal of K, the covariance of random group means (identity if no components given)."""
|
|
160
|
+
n = np.asarray(n, float)
|
|
161
|
+
if tau2 is None and sigma2_w is None:
|
|
162
|
+
return np.ones_like(n)
|
|
163
|
+
if tau2 is None or sigma2_w is None:
|
|
164
|
+
raise ValueError("give both tau2 and sigma2_w, or neither")
|
|
165
|
+
return tau2 + sigma2_w / n
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@dataclass(frozen=True)
|
|
169
|
+
class Lens:
|
|
170
|
+
"""The lens Λ = Ỹᵀ W K W Ỹ through which loadings see random group means (Result 2b).
|
|
171
|
+
|
|
172
|
+
Attributes
|
|
173
|
+
----------
|
|
174
|
+
matrix : (q, q) the lens matrix.
|
|
175
|
+
eigenvalues : (q,) in decreasing order.
|
|
176
|
+
eigenvectors : (q, q) matching columns; the leading ones are where loadings concentrate.
|
|
177
|
+
nu : participation ratio, the effective number of annotation directions.
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
matrix: np.ndarray
|
|
181
|
+
eigenvalues: np.ndarray
|
|
182
|
+
eigenvectors: np.ndarray
|
|
183
|
+
nu: float
|
|
184
|
+
|
|
185
|
+
@property
|
|
186
|
+
def cumulative_share(self):
|
|
187
|
+
"""Cumulative share of the lens held by its leading directions."""
|
|
188
|
+
return np.cumsum(self.eigenvalues) / self.eigenvalues.sum()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def lens(Y, n, weights=None, tau2=None, sigma2_w=None):
|
|
192
|
+
"""The lens of a design, from the annotation table and group sizes (Result 2b).
|
|
193
|
+
|
|
194
|
+
By default group means are taken as independent with equal variance (K = I),
|
|
195
|
+
which gives Λ = Ỹᵀ D² Ỹ for size weights. Pass ``tau2`` and ``sigma2_w``
|
|
196
|
+
(see `groupunit.weights.variance_components`) to use K = τ²I + σ²_w D⁻¹.
|
|
197
|
+
``weights`` are the group weights of the analysis (default: group sizes).
|
|
198
|
+
"""
|
|
199
|
+
n = np.asarray(n, float)
|
|
200
|
+
w = n if weights is None else np.asarray(weights, float)
|
|
201
|
+
Yc = wcentre(Y, w)
|
|
202
|
+
k = _group_mean_cov(n, tau2, sigma2_w)
|
|
203
|
+
WY = w[:, None] * Yc
|
|
204
|
+
L = WY.T @ (k[:, None] * WY)
|
|
205
|
+
eigenvalues, eigenvectors = np.linalg.eigh(L)
|
|
206
|
+
order = np.argsort(eigenvalues)[::-1]
|
|
207
|
+
eigenvalues = np.clip(eigenvalues[order], 0, None)
|
|
208
|
+
return Lens(L, eigenvalues, eigenvectors[:, order], participation_ratio(eigenvalues))
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def lens_null(Y, n, n_draws=5000, weights=None, tau2=None, sigma2_w=None, rng=None, p=None):
|
|
212
|
+
"""Unit-length loadings produced by random group means through the lens, (n_draws, q).
|
|
213
|
+
|
|
214
|
+
These are the loadings a design yields with no information from the
|
|
215
|
+
features; compare published loadings against them (Result 2b, Section 5).
|
|
216
|
+
|
|
217
|
+
With ``p=None`` each draw is one random score, which is the right null for
|
|
218
|
+
a score fixed before the annotations were used (a single feature, a PCA
|
|
219
|
+
or LDA component). For a PLS component pass the number of features ``p``:
|
|
220
|
+
each draw is then an M × p matrix of random group means, PLS is refitted,
|
|
221
|
+
and the annotation loading of its first component is kept. PLS selects the
|
|
222
|
+
best of p directions, so this null concentrates on the leading direction
|
|
223
|
+
of the lens more than the single-score null does, and as p grows it
|
|
224
|
+
approaches that direction (Result 2b). With correlated features, pass
|
|
225
|
+
their effective number of dimensions (for example the participation ratio
|
|
226
|
+
of their between-group covariance) rather than their count. Signs are
|
|
227
|
+
arbitrary; compare with `congruence`, which ignores them.
|
|
228
|
+
"""
|
|
229
|
+
rng = np.random.default_rng(rng)
|
|
230
|
+
n = np.asarray(n, float)
|
|
231
|
+
w = n if weights is None else np.asarray(weights, float)
|
|
232
|
+
Yc = wcentre(Y, w)
|
|
233
|
+
sd = np.sqrt(_group_mean_cov(n, tau2, sigma2_w))
|
|
234
|
+
if p is None:
|
|
235
|
+
T = wcentre(rng.standard_normal((len(n), n_draws)) * sd[:, None], w)
|
|
236
|
+
L = Yc.T @ (w[:, None] * T)
|
|
237
|
+
return (L / np.linalg.norm(L, axis=0)).T
|
|
238
|
+
if int(p) != p or p < 1:
|
|
239
|
+
raise ValueError(f"p must be a positive integer, not {p!r}")
|
|
240
|
+
WY = w[:, None] * Yc
|
|
241
|
+
out = np.empty((n_draws, Yc.shape[1]))
|
|
242
|
+
for start in range(0, n_draws, 256): # chunks keep memory at 256 · M · p
|
|
243
|
+
k = min(256, n_draws - start)
|
|
244
|
+
T = rng.standard_normal((k, len(n), int(p))) * sd[None, :, None]
|
|
245
|
+
out[start:start + k] = _first_pls_loading(T, WY, w)
|
|
246
|
+
return out
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _first_pls_loading(T, WY, w):
|
|
250
|
+
"""Unit annotation loading of the first PLS component of random group means T, (k, q).
|
|
251
|
+
|
|
252
|
+
T is (k, M, p), one set of group means per draw; WY is W Ỹ with Ỹ centred
|
|
253
|
+
by ``w``. The loading is Ỹᵀ W t̄₁ for the first component, proportional to
|
|
254
|
+
the leading left singular vector of Ỹᵀ W X̄ (Result 2b); centring of T is
|
|
255
|
+
irrelevant because 1ᵀ W Ỹ = 0.
|
|
256
|
+
"""
|
|
257
|
+
C = np.einsum("mq,kmp->kqp", WY, T) # Ỹᵀ W X̄ for every draw
|
|
258
|
+
_, vectors = np.linalg.eigh(C @ C.transpose(0, 2, 1))
|
|
259
|
+
return vectors[:, :, -1]
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def lens_congruence_null(loading, Y, n, n_draws=5000, weights=None, tau2=None, sigma2_w=None, rng=None,
|
|
263
|
+
p=None):
|
|
264
|
+
"""Absolute congruence of a loading with random-group-mean loadings, (n_draws,).
|
|
265
|
+
|
|
266
|
+
A loading, or the agreement between two analyses of the same groups, is
|
|
267
|
+
informative only to the extent that it exceeds this baseline. Pass ``p``
|
|
268
|
+
for a PLS loading, so that the null refits PLS on p random features
|
|
269
|
+
(see `lens_null`).
|
|
270
|
+
"""
|
|
271
|
+
null = lens_null(Y, n, n_draws, weights, tau2, sigma2_w, rng, p)
|
|
272
|
+
loading = np.asarray(loading, float)
|
|
273
|
+
return np.abs(null @ (loading / np.linalg.norm(loading)))
|