groupunit 0.2.0__tar.gz → 0.3.0__tar.gz
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-0.2.0/src/groupunit.egg-info → groupunit-0.3.0}/PKG-INFO +6 -6
- {groupunit-0.2.0 → groupunit-0.3.0}/README.md +5 -5
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit/__init__.py +69 -1
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit/core.py +29 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit/design.py +22 -16
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit/diagnostics.py +65 -25
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit/inference.py +209 -93
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit/methods.py +13 -12
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit/scores.py +2 -1
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit/similarity.py +26 -17
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit/simulate.py +1 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit/validation.py +9 -5
- groupunit-0.3.0/src/groupunit/weights.py +238 -0
- {groupunit-0.2.0 → groupunit-0.3.0/src/groupunit.egg-info}/PKG-INFO +6 -6
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit.egg-info/SOURCES.txt +3 -1
- groupunit-0.3.0/tests/test_bracket.py +78 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/tests/test_diagnostics.py +1 -1
- {groupunit-0.2.0 → groupunit-0.3.0}/tests/test_pairing_size_lens.py +22 -2
- groupunit-0.2.0/tests/test_results_2_4_5.py → groupunit-0.3.0/tests/test_results_2_4_c.py +9 -9
- groupunit-0.3.0/tests/test_review_fixes.py +137 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/tests/test_similarity.py +1 -1
- groupunit-0.3.0/tests/test_weights.py +110 -0
- groupunit-0.2.0/src/groupunit/weights.py +0 -102
- groupunit-0.2.0/tests/test_weights.py +0 -37
- {groupunit-0.2.0 → groupunit-0.3.0}/LICENSE +0 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/pyproject.toml +0 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/setup.cfg +0 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit.egg-info/dependency_links.txt +0 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit.egg-info/requires.txt +0 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/src/groupunit.egg-info/top_level.txt +0 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/tests/test_identities.py +0 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/tests/test_inference.py +0 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/tests/test_sklearn.py +0 -0
- {groupunit-0.2.0 → groupunit-0.3.0}/tests/test_validation.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: groupunit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Correlation, PLS, CCA and similarity analyses when annotations exist only for groups
|
|
5
5
|
Author-email: Tim Kmecl <tim.kmecl.tk@gmail.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -36,7 +36,7 @@ drug experience reports and each drug's receptor profile, brain regions and
|
|
|
36
36
|
parcel-level atlas maps, patients and characteristics of their hospital.
|
|
37
37
|
|
|
38
38
|
It accompanies Kmecl, *The group is the unit: limits of correlation, PLS and
|
|
39
|
-
CCA with group-level variables* (methods paper, Appendix
|
|
39
|
+
CCA with group-level variables* (methods paper, Appendix F). The package
|
|
40
40
|
computes the quantities the paper derives, and the diagnostics, tests and
|
|
41
41
|
validation it recommends. Every test resamples groups, never individuals.
|
|
42
42
|
|
|
@@ -64,7 +64,7 @@ print(gu.describe(groups, Y, X)) # N, M, r, kappa = r/(M-1), effective
|
|
|
64
64
|
|
|
65
65
|
Y3, _ = gu.reduce_annotations(Y, n, 3) # reduce in advance if kappa is near 1
|
|
66
66
|
test = gu.pls_test(X, groups, Y3, n_perm=5000, rng=0) # refitted under group permutation
|
|
67
|
-
shares = gu.group_shares(test.fit.group_scores, Y3, n) # which groups
|
|
67
|
+
shares = gu.group_shares(test.fit.group_scores, Y3, n) # which groups each component depends on
|
|
68
68
|
print(test.p_value, shares.m_eff, gu.pairing_ratio(Y3, n))
|
|
69
69
|
```
|
|
70
70
|
|
|
@@ -94,9 +94,9 @@ Markdown directly:
|
|
|
94
94
|
| `scores` | Results 1, 3a | between-group share η², `decompose_score` |
|
|
95
95
|
| `methods` | §3.2–3.3 | `pls`, `cca` (optionally row-weighted), `lda`, computed through the group means |
|
|
96
96
|
| `diagnostics` | §5, Result 2b | group shares, effective numbers, the lens and its null, `leave_out` |
|
|
97
|
-
| `weights` | §4.1 | variance components, optimal and exchangeable weights, effective groups
|
|
98
|
-
| `similarity` |
|
|
99
|
-
| `inference` | §4.2–4.5,
|
|
97
|
+
| `weights` | §4.1 | variance components, per-group variances, optimal and exchangeable weights, effective groups |
|
|
98
|
+
| `similarity` | App. C, Results C1–C3 | typicality and pattern, `similarity_decomposition`, `compare_similarity`, `distance_similarity` |
|
|
99
|
+
| `inference` | §4.2–4.5, Results 4a–4d | `correlation_test`, `pls_test`, `cca_test`, `estimator_test`, `permutation_test`, `pairing_ratio`, `pairing_terms`, `size_check` (`level_check`) |
|
|
100
100
|
| `validation` | §4.5 | `leave_one_group_out`, `pca_regression`, scikit-learn models |
|
|
101
101
|
| `simulate` | §6.1 | `simulate`, `lognormal_sizes` |
|
|
102
102
|
|
|
@@ -6,7 +6,7 @@ drug experience reports and each drug's receptor profile, brain regions and
|
|
|
6
6
|
parcel-level atlas maps, patients and characteristics of their hospital.
|
|
7
7
|
|
|
8
8
|
It accompanies Kmecl, *The group is the unit: limits of correlation, PLS and
|
|
9
|
-
CCA with group-level variables* (methods paper, Appendix
|
|
9
|
+
CCA with group-level variables* (methods paper, Appendix F). The package
|
|
10
10
|
computes the quantities the paper derives, and the diagnostics, tests and
|
|
11
11
|
validation it recommends. Every test resamples groups, never individuals.
|
|
12
12
|
|
|
@@ -34,7 +34,7 @@ print(gu.describe(groups, Y, X)) # N, M, r, kappa = r/(M-1), effective
|
|
|
34
34
|
|
|
35
35
|
Y3, _ = gu.reduce_annotations(Y, n, 3) # reduce in advance if kappa is near 1
|
|
36
36
|
test = gu.pls_test(X, groups, Y3, n_perm=5000, rng=0) # refitted under group permutation
|
|
37
|
-
shares = gu.group_shares(test.fit.group_scores, Y3, n) # which groups
|
|
37
|
+
shares = gu.group_shares(test.fit.group_scores, Y3, n) # which groups each component depends on
|
|
38
38
|
print(test.p_value, shares.m_eff, gu.pairing_ratio(Y3, n))
|
|
39
39
|
```
|
|
40
40
|
|
|
@@ -64,9 +64,9 @@ Markdown directly:
|
|
|
64
64
|
| `scores` | Results 1, 3a | between-group share η², `decompose_score` |
|
|
65
65
|
| `methods` | §3.2–3.3 | `pls`, `cca` (optionally row-weighted), `lda`, computed through the group means |
|
|
66
66
|
| `diagnostics` | §5, Result 2b | group shares, effective numbers, the lens and its null, `leave_out` |
|
|
67
|
-
| `weights` | §4.1 | variance components, optimal and exchangeable weights, effective groups
|
|
68
|
-
| `similarity` |
|
|
69
|
-
| `inference` | §4.2–4.5,
|
|
67
|
+
| `weights` | §4.1 | variance components, per-group variances, optimal and exchangeable weights, effective groups |
|
|
68
|
+
| `similarity` | App. C, Results C1–C3 | typicality and pattern, `similarity_decomposition`, `compare_similarity`, `distance_similarity` |
|
|
69
|
+
| `inference` | §4.2–4.5, Results 4a–4d | `correlation_test`, `pls_test`, `cca_test`, `estimator_test`, `permutation_test`, `pairing_ratio`, `pairing_terms`, `size_check` (`level_check`) |
|
|
70
70
|
| `validation` | §4.5 | `leave_one_group_out`, `pca_regression`, scikit-learn models |
|
|
71
71
|
| `simulate` | §6.1 | `simulate`, `lognormal_sizes` |
|
|
72
72
|
|
|
@@ -6,9 +6,11 @@ notation and array conventions shared by all modules.
|
|
|
6
6
|
"""
|
|
7
7
|
from .core import (
|
|
8
8
|
annotation_rank,
|
|
9
|
+
annotation_table,
|
|
9
10
|
encode_groups,
|
|
10
11
|
group_means,
|
|
11
12
|
group_sizes,
|
|
13
|
+
group_weights,
|
|
12
14
|
scatter_matrices,
|
|
13
15
|
wcentre,
|
|
14
16
|
weighted_basis,
|
|
@@ -31,6 +33,7 @@ from .inference import (
|
|
|
31
33
|
cca_test,
|
|
32
34
|
correlation_test,
|
|
33
35
|
estimator_test,
|
|
36
|
+
level_check,
|
|
34
37
|
pairing_ratio,
|
|
35
38
|
pairing_terms,
|
|
36
39
|
permutation_test,
|
|
@@ -51,10 +54,75 @@ from .validation import estimator_model, leave_one_group_out, linear_model, pca_
|
|
|
51
54
|
from .weights import (
|
|
52
55
|
effective_groups,
|
|
53
56
|
exchangeable_weights,
|
|
57
|
+
group_variances,
|
|
54
58
|
max_effective_groups,
|
|
55
59
|
optimal_weights,
|
|
56
60
|
pooled_variance_components,
|
|
61
|
+
tau2_upper,
|
|
57
62
|
variance_components,
|
|
58
63
|
)
|
|
59
64
|
|
|
60
|
-
|
|
65
|
+
# the public interface; result classes and permutation helpers are imported from their modules
|
|
66
|
+
__all__ = [
|
|
67
|
+
"annotation_rank",
|
|
68
|
+
"annotation_table",
|
|
69
|
+
"between_share",
|
|
70
|
+
"cca",
|
|
71
|
+
"cca_test",
|
|
72
|
+
"compare_similarity",
|
|
73
|
+
"congruence",
|
|
74
|
+
"contributions",
|
|
75
|
+
"correlation_test",
|
|
76
|
+
"decompose_score",
|
|
77
|
+
"describe",
|
|
78
|
+
"distance_similarity",
|
|
79
|
+
"effective_groups",
|
|
80
|
+
"effective_number",
|
|
81
|
+
"encode_groups",
|
|
82
|
+
"estimator_model",
|
|
83
|
+
"estimator_test",
|
|
84
|
+
"exchangeable_weights",
|
|
85
|
+
"feature_between_share",
|
|
86
|
+
"group_means",
|
|
87
|
+
"group_scores",
|
|
88
|
+
"group_shares",
|
|
89
|
+
"group_sizes",
|
|
90
|
+
"group_variances",
|
|
91
|
+
"group_weights",
|
|
92
|
+
"lda",
|
|
93
|
+
"leave_one_group_out",
|
|
94
|
+
"leave_out",
|
|
95
|
+
"lens",
|
|
96
|
+
"lens_congruence_null",
|
|
97
|
+
"lens_null",
|
|
98
|
+
"level_check",
|
|
99
|
+
"linear_model",
|
|
100
|
+
"lognormal_sizes",
|
|
101
|
+
"max_effective_groups",
|
|
102
|
+
"optimal_weights",
|
|
103
|
+
"pairing_ratio",
|
|
104
|
+
"pairing_terms",
|
|
105
|
+
"participation_ratio",
|
|
106
|
+
"pca_regression",
|
|
107
|
+
"permutation_test",
|
|
108
|
+
"pls",
|
|
109
|
+
"pls_test",
|
|
110
|
+
"pooled_variance_components",
|
|
111
|
+
"r2_null",
|
|
112
|
+
"reduce_annotations",
|
|
113
|
+
"scatter_matrices",
|
|
114
|
+
"similarity_decomposition",
|
|
115
|
+
"simulate",
|
|
116
|
+
"single_group_annotations",
|
|
117
|
+
"size_check",
|
|
118
|
+
"standardised_pattern",
|
|
119
|
+
"tau2_upper",
|
|
120
|
+
"typicality_pattern",
|
|
121
|
+
"variance_components",
|
|
122
|
+
"wcentre",
|
|
123
|
+
"weighted_basis",
|
|
124
|
+
"weighted_corr",
|
|
125
|
+
"weighted_r2",
|
|
126
|
+
]
|
|
127
|
+
|
|
128
|
+
__version__ = "0.3.0"
|
|
@@ -69,6 +69,35 @@ def group_means(X, groups, M=None):
|
|
|
69
69
|
return sums / n.reshape((-1,) + (1,) * (X.ndim - 1))
|
|
70
70
|
|
|
71
71
|
|
|
72
|
+
def group_weights(weights, n):
|
|
73
|
+
"""Resolve a ``weights`` argument to one weight per group, ``(M,)`` floats.
|
|
74
|
+
|
|
75
|
+
``None`` or ``"size"`` gives the group sizes ``n``, the weighting of an
|
|
76
|
+
analysis over individuals (Section 4.1). An array is used as given and
|
|
77
|
+
must hold one finite, non-negative weight per group with a positive sum.
|
|
78
|
+
The tests also accept ``"exchangeable"`` and ``"exchangeable-per-group"``,
|
|
79
|
+
which need the data; see
|
|
80
|
+
`groupunit.inference.permutation_weights`.
|
|
81
|
+
"""
|
|
82
|
+
n = np.asarray(n, float)
|
|
83
|
+
if weights is None or (isinstance(weights, str) and weights == "size"):
|
|
84
|
+
return n
|
|
85
|
+
if isinstance(weights, str):
|
|
86
|
+
raise ValueError(f"weights must be 'size', None or an array of {len(n)} group weights, not {weights!r}; "
|
|
87
|
+
"for exchangeable weights use exchangeable_weights(), group_variances() or permutation_weights()")
|
|
88
|
+
w = np.asarray(weights, float)
|
|
89
|
+
if w.shape != n.shape or not np.all(np.isfinite(w)) or np.any(w < 0) or w.sum() <= 0:
|
|
90
|
+
raise ValueError(f"weights must be {len(n)} finite, non-negative numbers with a positive sum, "
|
|
91
|
+
"one per group")
|
|
92
|
+
return w
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def annotation_table(Y):
|
|
96
|
+
"""The annotation table as an (M, q) float array; a single annotation (M,) becomes one column."""
|
|
97
|
+
Y = np.asarray(Y, float)
|
|
98
|
+
return Y.reshape(len(Y), -1)
|
|
99
|
+
|
|
100
|
+
|
|
72
101
|
def wcentre(A, w):
|
|
73
102
|
"""Centre the rows of ``A`` (vector or matrix) on their ``w``-weighted mean."""
|
|
74
103
|
A = np.asarray(A, float)
|
|
@@ -4,7 +4,7 @@ from dataclasses import dataclass, field
|
|
|
4
4
|
import numpy as np
|
|
5
5
|
from scipy import stats
|
|
6
6
|
|
|
7
|
-
from .core import annotation_rank, check_groups, group_means, wcentre
|
|
7
|
+
from .core import annotation_rank, annotation_table, check_groups, group_means, wcentre
|
|
8
8
|
from .diagnostics import effective_number
|
|
9
9
|
from .inference import pairing_terms
|
|
10
10
|
from .scores import feature_between_share
|
|
@@ -31,7 +31,7 @@ class DesignSummary:
|
|
|
31
31
|
group means taken as equally variable otherwise. Above 1, size-weighted
|
|
32
32
|
permutation tests lean liberal; below 1, conservative. No range of the
|
|
33
33
|
ratio is safe for every design: the same ratio does more harm with more
|
|
34
|
-
groups (Result
|
|
34
|
+
groups (Result 4c), so check a test's level with
|
|
35
35
|
`groupunit.inference.size_check`.
|
|
36
36
|
pairing_group : the group with the largest term of the ratio
|
|
37
37
|
(`groupunit.inference.pairing_terms`), the one most responsible for
|
|
@@ -71,9 +71,9 @@ class DesignSummary:
|
|
|
71
71
|
lines.append(f"pairing ratio of sizes with annotation profiles = {self.pairing_ratio:.2f} "
|
|
72
72
|
f"(largest term: group {self.pairing_group})")
|
|
73
73
|
# no fixed range of the ratio is safe: the same ratio does more harm with more groups
|
|
74
|
-
# (Result
|
|
74
|
+
# (Result 4c), so the summary never declares a design safe and points to size_check
|
|
75
75
|
if self.pairing_ratio > PAIRING_TOLERANCE[1]:
|
|
76
|
-
lines.append("UNUSUAL PAIRING: large groups
|
|
76
|
+
lines.append("UNUSUAL PAIRING: large groups have atypical profiles, so size-weighted group "
|
|
77
77
|
"permutation tests (weights='size', cca_test, estimator_test) lean liberal here, "
|
|
78
78
|
"more so with more groups; keep the default exchangeable weights.")
|
|
79
79
|
elif self.pairing_ratio < PAIRING_TOLERANCE[0]:
|
|
@@ -92,7 +92,7 @@ def single_group_annotations(Y, atol=1e-12):
|
|
|
92
92
|
"""Indices of annotation columns in which exactly one group differs from all others.
|
|
93
93
|
|
|
94
94
|
Such an annotation correlates with any score exactly as that group's mean
|
|
95
|
-
does, so it
|
|
95
|
+
does, so it measures only how far that group lies from the others.
|
|
96
96
|
"""
|
|
97
97
|
Y = np.asarray(Y, float)
|
|
98
98
|
flagged = []
|
|
@@ -105,21 +105,23 @@ def single_group_annotations(Y, atol=1e-12):
|
|
|
105
105
|
|
|
106
106
|
|
|
107
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
|
|
109
|
-
Y =
|
|
108
|
+
"""Summarise a design: N, M, q, r, kappa, effective groups and flagged annotations (Box 1, items 2-4)."""
|
|
109
|
+
Y = annotation_table(Y)
|
|
110
110
|
groups, n = check_groups(groups, len(Y))
|
|
111
111
|
M, q = Y.shape
|
|
112
112
|
r = annotation_rank(Y, n)
|
|
113
113
|
max_components = r
|
|
114
114
|
share = None
|
|
115
|
-
|
|
115
|
+
tau2 = sigma2_w = None # group means taken as equally variable without features
|
|
116
116
|
if X is not None:
|
|
117
117
|
X = np.asarray(X, float)
|
|
118
118
|
Xbar = group_means(X - X.mean(0), groups, M)
|
|
119
119
|
max_components = min(r, annotation_rank(Xbar, n))
|
|
120
120
|
share = feature_between_share(X, groups)
|
|
121
|
-
|
|
122
|
-
|
|
121
|
+
if len(groups) > M: # σ²_w needs at least one group with two individuals
|
|
122
|
+
vc = pooled_variance_components(X, groups)
|
|
123
|
+
tau2, sigma2_w = vc.tau2, vc.sigma2_w
|
|
124
|
+
terms = pairing_terms(Y, n, tau2=tau2, sigma2_w=sigma2_w)
|
|
123
125
|
return DesignSummary(
|
|
124
126
|
N=len(groups), M=M, q=q, r=r, kappa=r / (M - 1),
|
|
125
127
|
kish_groups=effective_number(n),
|
|
@@ -138,11 +140,15 @@ def r2_null(r, M):
|
|
|
138
140
|
Beta(r/2, (M-1-r)/2), with mean r/(M-1). Returns a frozen ``scipy.stats``
|
|
139
141
|
distribution. At r = M - 1 the distribution collapses to 1 for every score.
|
|
140
142
|
|
|
141
|
-
It assumes the weighted group means point in a random
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
143
|
+
It assumes that the weighted group means point in a uniformly random
|
|
144
|
+
direction. For the size-weighted R²_n of a score fixed in advance, this
|
|
145
|
+
holds when sampling error dominates (τ² ≪ σ²_w / n̄) or group sizes are
|
|
146
|
+
equal, because √n_m t̄_m then has the same variance in every group; for
|
|
147
|
+
R²_w with `groupunit.weights.optimal_weights` it holds whatever the sizes.
|
|
148
|
+
Under heterogeneity, with size weights and unequal groups, the largest
|
|
149
|
+
groups dominate both the score's means and the annotations, and the null
|
|
150
|
+
mean exceeds κ by an amount that depends on the design; treat this
|
|
151
|
+
distribution as a lower bound there.
|
|
146
152
|
"""
|
|
147
153
|
if not 0 < r < M - 1:
|
|
148
154
|
raise ValueError(f"need 0 < r < M - 1; at r = M - 1 every score has R² = 1 (r={r}, M={M})")
|
|
@@ -157,7 +163,7 @@ def reduce_annotations(Y, w, k, standardise=False):
|
|
|
157
163
|
share of the weighted annotation variance each one holds. Inside a
|
|
158
164
|
permutation test or cross-validation, call this on the training groups only.
|
|
159
165
|
"""
|
|
160
|
-
Y =
|
|
166
|
+
Y = annotation_table(Y)
|
|
161
167
|
w = np.asarray(w, float)
|
|
162
168
|
Yc = wcentre(Y, w)
|
|
163
169
|
if standardise:
|
|
@@ -8,7 +8,7 @@ from dataclasses import dataclass
|
|
|
8
8
|
|
|
9
9
|
import numpy as np
|
|
10
10
|
|
|
11
|
-
from .core import wcentre
|
|
11
|
+
from .core import annotation_table, group_weights, wcentre
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
def effective_number(w, axis=0):
|
|
@@ -48,11 +48,12 @@ def contributions(tbar, Y, w):
|
|
|
48
48
|
"""Group × annotation contribution matrix with entries w_m t̄_m ỹ_mj (the identity, Section 2.2).
|
|
49
49
|
|
|
50
50
|
Column sums are the (unnormalised) annotation loadings of the component.
|
|
51
|
+
Returns (M, q); a single annotation (M,) is treated as one column.
|
|
51
52
|
"""
|
|
52
53
|
tbar = wcentre(np.asarray(tbar, float), w)
|
|
53
54
|
if tbar.ndim != 1:
|
|
54
55
|
raise ValueError("contributions takes the group means of a single component")
|
|
55
|
-
return (np.asarray(w, float) * tbar)[:, None] * wcentre(Y, w)
|
|
56
|
+
return (np.asarray(w, float) * tbar)[:, None] * wcentre(annotation_table(Y), w)
|
|
56
57
|
|
|
57
58
|
|
|
58
59
|
@dataclass(frozen=True)
|
|
@@ -84,7 +85,7 @@ class GroupShares:
|
|
|
84
85
|
|
|
85
86
|
|
|
86
87
|
def group_shares(tbar, Y, w):
|
|
87
|
-
"""Group shares of the annotation loading of one or more components (Section 5, Appendix B.
|
|
88
|
+
"""Group shares of the annotation loading of one or more components (Section 5, Appendix B.7).
|
|
88
89
|
|
|
89
90
|
``tbar`` holds each group's mean score, (M,) or (M, k); ``w`` are the group
|
|
90
91
|
weights used by the analysis (group sizes for analyses of individuals).
|
|
@@ -93,7 +94,7 @@ def group_shares(tbar, Y, w):
|
|
|
93
94
|
w = np.asarray(w, float)
|
|
94
95
|
tbar = np.asarray(tbar, float)
|
|
95
96
|
T = wcentre(tbar.reshape(len(tbar), -1), w)
|
|
96
|
-
Yc = wcentre(Y, w)
|
|
97
|
+
Yc = wcentre(annotation_table(Y), w)
|
|
97
98
|
wT = w[:, None] * T
|
|
98
99
|
loading = Yc.T @ wT
|
|
99
100
|
unit = loading / np.linalg.norm(loading, axis=0)
|
|
@@ -125,7 +126,7 @@ class LeaveOut:
|
|
|
125
126
|
|
|
126
127
|
|
|
127
128
|
def leave_out(tbar, Y, w, drop):
|
|
128
|
-
"""A component's loading without groups ``drop``, the component held fixed (Section 5, Appendix B.
|
|
129
|
+
"""A component's loading without groups ``drop``, the component held fixed (Section 5, Appendix B.7).
|
|
129
130
|
|
|
130
131
|
The other groups' means are kept unchanged, and the loading is the one the
|
|
131
132
|
data without the dropped groups would give, re-centred over the remaining
|
|
@@ -137,15 +138,27 @@ def leave_out(tbar, Y, w, drop):
|
|
|
137
138
|
from it, and the loading reverses if the group's share exceeds (W − w_m) / W.
|
|
138
139
|
For several groups S, ℓ₋S = ℓ − Σ_S u_m − (Σ_S w_m t̄_m)(Σ_S w_m ỹ_m) / (W − W_S).
|
|
139
140
|
To refit instead, rerun the method without those groups. Choose ``drop``
|
|
140
|
-
with `GroupShares.top`.
|
|
141
|
+
with `GroupShares.top`. ``drop`` is a group index, an array of indices
|
|
142
|
+
or a boolean mask over groups.
|
|
141
143
|
"""
|
|
142
144
|
w = np.asarray(w, float)
|
|
143
145
|
t = wcentre(np.asarray(tbar, float), w)
|
|
144
|
-
Yc = wcentre(Y, w)
|
|
146
|
+
Yc = wcentre(annotation_table(Y), w)
|
|
145
147
|
terms = (w * t)[:, None] * Yc
|
|
146
148
|
full = terms.sum(0)
|
|
147
|
-
|
|
149
|
+
drop = np.atleast_1d(np.asarray(drop))
|
|
150
|
+
if drop.dtype == bool:
|
|
151
|
+
if drop.shape != w.shape:
|
|
152
|
+
raise ValueError(f"a boolean drop mask needs one entry per group ({len(w)})")
|
|
153
|
+
S = np.flatnonzero(drop)
|
|
154
|
+
else:
|
|
155
|
+
S = drop.astype(int)
|
|
156
|
+
if S.size and (S.min() < -len(w) or S.max() >= len(w)):
|
|
157
|
+
raise IndexError(f"drop indices out of range for {len(w)} groups")
|
|
158
|
+
S = np.unique(S % len(w)) # each group is removed once, however it is listed
|
|
148
159
|
W_rest = w.sum() - w[S].sum()
|
|
160
|
+
if W_rest <= 0:
|
|
161
|
+
raise ValueError("dropping these groups leaves no weight; the loading is undefined")
|
|
149
162
|
rest = full - terms[S].sum(0) - (w[S] @ t[S]) * (w[S] @ Yc[S]) / W_rest
|
|
150
163
|
return LeaveOut(
|
|
151
164
|
dropped=S,
|
|
@@ -188,17 +201,18 @@ class Lens:
|
|
|
188
201
|
return np.cumsum(self.eigenvalues) / self.eigenvalues.sum()
|
|
189
202
|
|
|
190
203
|
|
|
191
|
-
def lens(Y, n, weights=None, tau2=None, sigma2_w=None):
|
|
204
|
+
def lens(Y, n, *, weights=None, tau2=None, sigma2_w=None):
|
|
192
205
|
"""The lens of a design, from the annotation table and group sizes (Result 2b).
|
|
193
206
|
|
|
194
207
|
By default group means are taken as independent with equal variance (K = I),
|
|
195
208
|
which gives Λ = Ỹᵀ D² Ỹ for size weights. Pass ``tau2`` and ``sigma2_w``
|
|
196
209
|
(see `groupunit.weights.variance_components`) to use K = τ²I + σ²_w D⁻¹.
|
|
197
|
-
``weights`` are the group weights of the analysis (
|
|
210
|
+
``weights`` are the group weights of the analysis: ``"size"`` (or ``None``, the
|
|
211
|
+
default) for group sizes, or one weight per group.
|
|
198
212
|
"""
|
|
199
213
|
n = np.asarray(n, float)
|
|
200
|
-
w =
|
|
201
|
-
Yc = wcentre(Y, w)
|
|
214
|
+
w = group_weights(weights, n)
|
|
215
|
+
Yc = wcentre(annotation_table(Y), w)
|
|
202
216
|
k = _group_mean_cov(n, tau2, sigma2_w)
|
|
203
217
|
WY = w[:, None] * Yc
|
|
204
218
|
L = WY.T @ (k[:, None] * WY)
|
|
@@ -208,7 +222,7 @@ def lens(Y, n, weights=None, tau2=None, sigma2_w=None):
|
|
|
208
222
|
return Lens(L, eigenvalues, eigenvectors[:, order], participation_ratio(eigenvalues))
|
|
209
223
|
|
|
210
224
|
|
|
211
|
-
def lens_null(Y, n, n_draws=5000, weights=None, tau2=None, sigma2_w=None, rng=None, p=None):
|
|
225
|
+
def lens_null(Y, n, n_draws=5000, *, weights=None, tau2=None, sigma2_w=None, rng=None, p=None, means=None):
|
|
212
226
|
"""Unit-length loadings produced by random group means through the lens, (n_draws, q).
|
|
213
227
|
|
|
214
228
|
These are the loadings a design yields with no information from the
|
|
@@ -221,16 +235,40 @@ def lens_null(Y, n, n_draws=5000, weights=None, tau2=None, sigma2_w=None, rng=No
|
|
|
221
235
|
and the annotation loading of its first component is kept. PLS selects the
|
|
222
236
|
best of p directions, so this null concentrates on the leading direction
|
|
223
237
|
of the lens more than the single-score null does, and as p grows it
|
|
224
|
-
approaches that direction (Result 2b).
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
238
|
+
approaches that direction (Result 2b). The null is right only when ``p``
|
|
239
|
+
is the effective number of independent directions along which the group
|
|
240
|
+
means vary, p_eff. With correlated features it lies between 1 and the
|
|
241
|
+
feature count, and with few groups it cannot be estimated reliably. In the
|
|
242
|
+
paper's simulations (Section 6) participation ratios of the between-group
|
|
243
|
+
and of the within-group covariance both missed it when group effects
|
|
244
|
+
spanned fewer dimensions than the within-group noise. Run the null at
|
|
245
|
+
``p=1`` and at the number of features, and rely only on conclusions that
|
|
246
|
+
hold at both (Section 5, Box 1).
|
|
247
|
+
|
|
248
|
+
With equal group sizes, pass the observed group means of the features as
|
|
249
|
+
``means`` (M, p) instead of ``p``. Each draw then shuffles these means among
|
|
250
|
+
groups, keeping the annotation table and sizes in place, and refits PLS.
|
|
251
|
+
This null needs no p_eff and was calibrated in every simulated design with
|
|
252
|
+
equal sizes. With unequal sizes it was not, so use the ``p`` bracket there.
|
|
253
|
+
|
|
254
|
+
Signs are arbitrary; compare with `congruence`, which ignores them.
|
|
228
255
|
"""
|
|
229
256
|
rng = np.random.default_rng(rng)
|
|
230
257
|
n = np.asarray(n, float)
|
|
231
|
-
w =
|
|
232
|
-
Yc = wcentre(Y, w)
|
|
258
|
+
w = group_weights(weights, n)
|
|
259
|
+
Yc = wcentre(annotation_table(Y), w)
|
|
233
260
|
sd = np.sqrt(_group_mean_cov(n, tau2, sigma2_w))
|
|
261
|
+
if means is not None:
|
|
262
|
+
if p is not None:
|
|
263
|
+
raise ValueError("pass either p (random group means) or means (shuffled observed means), not both")
|
|
264
|
+
Z = np.asarray(means, float).reshape(len(n), -1)
|
|
265
|
+
WY = w[:, None] * Yc
|
|
266
|
+
out = np.empty((n_draws, Yc.shape[1]))
|
|
267
|
+
for start in range(0, n_draws, 256):
|
|
268
|
+
k = min(256, n_draws - start)
|
|
269
|
+
perms = np.array([rng.permutation(len(n)) for _ in range(k)])
|
|
270
|
+
out[start:start + k] = _first_pls_loading(Z[perms], WY, w) # row m gets the means of group perms[m]
|
|
271
|
+
return out
|
|
234
272
|
if p is None:
|
|
235
273
|
T = wcentre(rng.standard_normal((len(n), n_draws)) * sd[:, None], w)
|
|
236
274
|
L = Yc.T @ (w[:, None] * T)
|
|
@@ -259,15 +297,17 @@ def _first_pls_loading(T, WY, w):
|
|
|
259
297
|
return vectors[:, :, -1]
|
|
260
298
|
|
|
261
299
|
|
|
262
|
-
def lens_congruence_null(loading, Y, n, n_draws=5000, weights=None, tau2=None, sigma2_w=None, rng=None,
|
|
263
|
-
p=None):
|
|
300
|
+
def lens_congruence_null(loading, Y, n, n_draws=5000, *, weights=None, tau2=None, sigma2_w=None, rng=None,
|
|
301
|
+
p=None, means=None):
|
|
264
302
|
"""Absolute congruence of a loading with random-group-mean loadings, (n_draws,).
|
|
265
303
|
|
|
266
304
|
A loading, or the agreement between two analyses of the same groups, is
|
|
267
|
-
informative only to the extent that it exceeds this baseline.
|
|
268
|
-
|
|
269
|
-
|
|
305
|
+
informative only to the extent that it exceeds this baseline. For a PLS
|
|
306
|
+
loading, pass ``p`` so that the null refits PLS on p random features, and
|
|
307
|
+
run it at ``p=1`` and at the number of features; with equal group sizes,
|
|
308
|
+
pass the observed group means as ``means`` instead (see `lens_null`).
|
|
270
309
|
"""
|
|
271
|
-
null = lens_null(Y, n, n_draws, weights, tau2, sigma2_w, rng, p
|
|
310
|
+
null = lens_null(Y, n, n_draws, weights=weights, tau2=tau2, sigma2_w=sigma2_w, rng=rng, p=p,
|
|
311
|
+
means=means)
|
|
272
312
|
loading = np.asarray(loading, float)
|
|
273
313
|
return np.abs(null @ (loading / np.linalg.norm(loading)))
|