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/inference.py ADDED
@@ -0,0 +1,554 @@
1
+ """Permutation tests over groups (Section 4).
2
+
3
+ The annotation profile belongs to the group, so the exchangeable units are
4
+ groups: every test here reassigns rows of the annotation table among groups,
5
+ keeping each group's individuals together. What must be refitted depends on
6
+ the design (Section 4.4):
7
+
8
+ * scores built without the annotations are held fixed - `correlation_test`;
9
+ * components that depend on the annotations are refitted in every
10
+ permutation - `pls_test`, `cca_test`;
11
+ * any other data-dependent step (annotation subsets, numbers of components,
12
+ selected cells) must go inside the statistic of `permutation_test`;
13
+ * models from other libraries (scikit-learn's PLSRegression, CCA, pipelines)
14
+ are refitted on individuals in every permutation - `estimator_test`.
15
+
16
+ Reassigning rows among groups is exact only if the groups' terms in the
17
+ statistic are exchangeable. With unequal group sizes they may not be: check
18
+ `pairing_ratio`, and use `groupunit.weights.exchangeable_weights` when it is
19
+ far from 1.
20
+ """
21
+ import copy
22
+ from dataclasses import dataclass
23
+
24
+ import numpy as np
25
+
26
+ from .core import check_groups, group_means, wcentre, weighted_basis, weighted_corr
27
+ from .methods import _cca_spaces, cca, pls
28
+ from .scores import between_share
29
+ from .simulate import simulate
30
+ from .weights import exchangeable_weights, pooled_variance_components
31
+
32
+
33
+ def permutation_weights(weights, values, groups, n):
34
+ """Resolve the ``weights`` argument of a group permutation test to one weight per group.
35
+
36
+ ``"exchangeable"`` (the default of the tests) estimates τ² and σ²_w from
37
+ ``values`` (features or scores, pooled over columns, under the null) and
38
+ returns weights ∝ 1/sqrt(τ² + σ²_w/n_m), so every group's term is equally
39
+ variable. With equal group sizes these are equal weights. ``"size"`` gives
40
+ group sizes, the weighting of an analysis over individuals. An array is
41
+ used as given.
42
+ """
43
+ if not isinstance(weights, str):
44
+ return np.asarray(weights, float)
45
+ if weights == "size":
46
+ return n.astype(float)
47
+ if weights != "exchangeable":
48
+ raise ValueError(f"weights must be 'exchangeable', 'size' or an array, not {weights!r}")
49
+ if np.all(n == n[0]):
50
+ return np.ones(len(n))
51
+ vc = pooled_variance_components(values, groups)
52
+ if not np.all(vc.tau2 + vc.sigma2_w / n > 0):
53
+ return np.ones(len(n)) # no variation to standardise: every term is already alike
54
+ return exchangeable_weights(n, vc.tau2, vc.sigma2_w)
55
+
56
+
57
+ def pairing_ratio(Y, n, weights=None, tau2=None, sigma2_w=None):
58
+ """How unusual the observed pairing of group weights with annotation profiles is.
59
+
60
+ Under the null, a weighted loading ℓ = Ỹᵀ W (x̄ − x̄_w) of independent group
61
+ means with variances v_m = τ² + σ²_w / n_m has E‖ℓ‖² = tr(Yᵀ A Y), with
62
+ A = W C V Cᵀ W and C the weighted centring. The ratio of this to its
63
+ average over reassignments of annotation rows among groups, tr(A) ·
64
+ Σ‖y_m − ȳ‖² / (M − 1), says how much larger than under permutation the
65
+ statistic is expected to be by design alone. Near 1, group permutation
66
+ tests with these weights hold their level. Above 1, atypical profiles sit
67
+ on high-variance terms (for size weights: large groups) and the tests are
68
+ liberal. Below 1, they are conservative. No range of the ratio is safe for
69
+ every design: one atypical group's share of the profile spread shrinks
70
+ like 1/M, so the same ratio implies a more variable term, and a more
71
+ liberal test, when there are more groups (Result 5d). Use the ratio as a
72
+ warning and `size_check` to check a test's level. Without variance components, group
73
+ means are taken as equally variable. Weights from
74
+ `groupunit.weights.exchangeable_weights` give a ratio close to 1.
75
+ """
76
+ Y, A = _pairing_matrix(Y, n, weights, tau2, sigma2_w)
77
+ observed = np.trace(Y.T @ A @ Y)
78
+ permuted = np.trace(A) * (Y**2).sum() / (len(Y) - 1)
79
+ return float(observed / permuted)
80
+
81
+
82
+ def _pairing_matrix(Y, n, weights, tau2, sigma2_w):
83
+ """Y centred without weights, and A = W C V Cᵀ W, the null covariance of the weighted terms."""
84
+ n = np.asarray(n, float)
85
+ Y = np.asarray(Y, float).reshape(len(n), -1)
86
+ M = len(n)
87
+ w = n if weights is None else np.asarray(weights, float)
88
+ if tau2 is None and sigma2_w is None:
89
+ v = np.ones_like(n)
90
+ elif tau2 is None or sigma2_w is None:
91
+ raise ValueError("give both tau2 and sigma2_w, or neither")
92
+ else:
93
+ v = tau2 + sigma2_w / n
94
+ WC = w[:, None] * (np.eye(M) - np.outer(np.ones(M), w) / w.sum()) # W C
95
+ # A 1 = 0, so the statistic does not depend on how Y is centred; unweighted centring
96
+ # makes the permutation average a function of Σ‖y_m‖² alone
97
+ return Y - Y.mean(0), WC @ (v[:, None] * WC.T)
98
+
99
+
100
+ @dataclass(frozen=True)
101
+ class PairingTerms:
102
+ """The pairing ratio split into one term per group (Result 5d).
103
+
104
+ Attributes
105
+ ----------
106
+ ratio : the pairing ratio ϱ, as returned by `pairing_ratio`.
107
+ terms : (M,) the excess ϱ − 1 split exactly over groups; they sum to ϱ − 1.
108
+ A large positive term marks a group whose atypical profile sits on a
109
+ highly variable term.
110
+ profile_share : (M,) f_m = ‖y_m − ȳ‖² / Σ_m ‖y_m − ȳ‖², each group's share
111
+ of the spread of the annotation profiles (unweighted mean ȳ).
112
+ variance_ratio : (M,) g_m = A_mm / (tr A / M), the null variance of group
113
+ m's weighted term relative to the average group; about w_m² v_m up to
114
+ scale. Exchangeable weights make every g_m close to 1.
115
+ largest : index of the group with the largest term.
116
+ """
117
+
118
+ ratio: float
119
+ terms: np.ndarray
120
+ profile_share: np.ndarray
121
+ variance_ratio: np.ndarray
122
+ largest: int
123
+
124
+
125
+ def pairing_terms(Y, n, weights=None, tau2=None, sigma2_w=None):
126
+ """Which groups make a group permutation test liberal or conservative (Result 5d).
127
+
128
+ Splits the excess of the `pairing_ratio` over 1 into one term per group,
129
+
130
+ ϱ_m = (M − 1) c_m / (tr(A) S_Y) − f_m, c_m = Σ_m' A_mm' y_mᵀ y_m',
131
+
132
+ with the profiles y_m centred without weights, S_Y = Σ‖y_m‖² and A as in
133
+ `pairing_ratio`. The terms sum exactly to ϱ − 1. When no group holds a
134
+ large share of the total weight, ϱ_m ≈ f_m (g_m − 1): a group pushes the
135
+ test towards liberal when its profile is unusual (large f_m) and its term
136
+ is more variable than average (g_m > 1). Under size weights these are the
137
+ large groups; under equal weights, and in similarity designs, the small
138
+ ones. Report the ratio together with its largest term.
139
+
140
+ Arguments are those of `pairing_ratio`.
141
+ """
142
+ Y, A = _pairing_matrix(Y, n, weights, tau2, sigma2_w)
143
+ M = len(Y)
144
+ S_Y = (Y**2).sum()
145
+ if S_Y == 0:
146
+ raise ValueError("all annotation profiles are equal; the pairing ratio is undefined")
147
+ trA = np.trace(A)
148
+ c = ((A @ Y) * Y).sum(1) # c_m = Σ_m' A_mm' y_mᵀ y_m'
149
+ f = (Y**2).sum(1) / S_Y
150
+ terms = (M - 1) * c / (trA * S_Y) - f
151
+ return PairingTerms(
152
+ ratio=float(1 + terms.sum()),
153
+ terms=terms,
154
+ profile_share=f,
155
+ variance_ratio=np.diag(A) / (trA / M),
156
+ largest=int(np.argmax(terms)),
157
+ )
158
+
159
+
160
+ def draw_permutations(M, n_perm, rng=None, strata=None):
161
+ """Random permutations of M groups, (n_perm, M).
162
+
163
+ With ``strata`` (one label per group, for example a drug class), groups are
164
+ permuted only within their stratum, which tests the annotations beyond that
165
+ group-level variable (Section 4.5).
166
+ """
167
+ rng = np.random.default_rng(rng)
168
+ if strata is None:
169
+ return np.array([rng.permutation(M) for _ in range(n_perm)])
170
+ strata = np.asarray(strata)
171
+ if strata.shape != (M,):
172
+ raise ValueError(f"strata needs one label per group ({M}), got shape {strata.shape}")
173
+ perms = np.tile(np.arange(M), (n_perm, 1))
174
+ for label in np.unique(strata):
175
+ idx = np.flatnonzero(strata == label)
176
+ for perm in perms:
177
+ perm[idx] = rng.permutation(idx)
178
+ return perms
179
+
180
+
181
+ def p_value(observed, null):
182
+ """Permutation p-values, (1 + #{null >= observed}) / (1 + n_perm), elementwise.
183
+
184
+ A small tolerance counts exact ties as ties: under saturation every
185
+ permutation reproduces the observed statistic up to rounding.
186
+ """
187
+ observed = np.asarray(observed, float)
188
+ null = np.asarray(null, float)
189
+ tol = 1e-10 * np.maximum(1.0, np.abs(observed))
190
+ return (1 + (null >= observed - tol).sum(0)) / (1 + len(null))
191
+
192
+
193
+ def max_t_p_value(observed, null):
194
+ """Family-wise p-values by the maximum statistic over all cells (Westfall-Young max-T).
195
+
196
+ Suited to cells that share a scale and a null spread. If one cell's null
197
+ is much wider than the others', it sets the bar for all of them; use
198
+ `min_p_value` then.
199
+ """
200
+ observed = np.asarray(observed, float)
201
+ null = np.asarray(null, float)
202
+ null_max = null.reshape(len(null), -1).max(1)
203
+ return p_value(observed, null_max.reshape((-1,) + (1,) * observed.ndim))
204
+
205
+
206
+ def min_p_value(observed, null):
207
+ """Family-wise p-values by the minimum p-value over all cells (Westfall-Young min-p).
208
+
209
+ Each cell's statistic is first turned into a p-value against that cell's
210
+ own permutation null, and the family-wise p-value of a cell is the share of
211
+ permutations whose smallest p-value over the family is at most the cell's
212
+ own. Cells with different null spreads are thereby put on one scale, so a
213
+ cell with a wide null does not take the power of the others. The observed
214
+ data count as one of the n_perm + 1 equally likely assignments, as in
215
+ `p_value`. P-values are discrete with floor 1 / (n_perm + 1), so large
216
+ families need many permutations.
217
+ """
218
+ observed = np.asarray(observed, float)
219
+ null = np.asarray(null, float)
220
+ values = np.concatenate([observed.reshape(1, -1), null.reshape(len(null), -1)]) # (n_perm + 1, cells)
221
+ B1 = len(values)
222
+ tol = 1e-10 * np.maximum(1.0, np.abs(values))
223
+ # p-value of every assignment (observed and permuted) against its own cell's distribution
224
+ ranks = np.empty_like(values)
225
+ for j in range(values.shape[1]):
226
+ ordered = np.sort(values[:, j])
227
+ ranks[:, j] = B1 - np.searchsorted(ordered, values[:, j] - tol[:, j], side="left")
228
+ p_all = ranks / B1
229
+ min_p = p_all.min(1)
230
+ family = (min_p[None, :] <= p_all[0][:, None] + 1e-12).sum(1) / B1
231
+ return family.reshape(observed.shape)
232
+
233
+
234
+ CORRECTIONS = {"max-t": max_t_p_value, "min-p": min_p_value}
235
+
236
+
237
+ def _family_wise(correction):
238
+ try:
239
+ return CORRECTIONS[correction]
240
+ except KeyError:
241
+ raise ValueError(f"correction must be one of {sorted(CORRECTIONS)}, not {correction!r}") from None
242
+
243
+
244
+ @dataclass(frozen=True)
245
+ class PermutationResult:
246
+ """Observed statistic, its permutation null, and uncorrected and family-wise p-values.
247
+
248
+ Attributes
249
+ ----------
250
+ statistic : the observed statistic, a number or an array of cells.
251
+ null : (n_perm, ...) the statistic under each reassignment of annotation rows.
252
+ p_value : uncorrected p-values, each cell against its own null.
253
+ p_fwer : family-wise p-values over all cells, by ``correction``.
254
+ correction : "max-t" or "min-p".
255
+ """
256
+
257
+ statistic: np.ndarray
258
+ null: np.ndarray
259
+ p_value: np.ndarray
260
+ p_fwer: np.ndarray
261
+ correction: str = "max-t"
262
+
263
+
264
+ def permutation_test(statistic, Y, n_perm=5000, rng=None, strata=None, correction="max-t"):
265
+ """Generic group-level permutation test.
266
+
267
+ ``statistic(Y_perm)`` receives the annotation table with its rows
268
+ reassigned among groups and returns a number or an array, larger meaning
269
+ more extreme (pass absolute values for two-sided tests). It must repeat
270
+ every fit and selection step.
271
+
272
+ For arrays, ``p_fwer`` controls family-wise error over all cells.
273
+ ``correction="max-t"`` compares each cell with the maximum over cells and
274
+ suits cells on a common scale with similar null spread. ``"min-p"`` first
275
+ turns each cell into a p-value against its own null, which suits cells
276
+ whose null spreads differ: selection statistics such as the best of many
277
+ annotations per component, or components concentrated on different
278
+ numbers of groups. Choose the correction before looking at the results.
279
+ """
280
+ family_wise = _family_wise(correction)
281
+ Y = np.asarray(Y, float)
282
+ observed = np.asarray(statistic(Y), float)
283
+ null = np.array([statistic(Y[perm]) for perm in draw_permutations(len(Y), n_perm, rng, strata)], float)
284
+ return PermutationResult(observed, null, p_value(observed, null), family_wise(observed, null), correction)
285
+
286
+
287
+ def paired_score_correlation(fitted, X, Y_individuals):
288
+ """|corr| between the paired feature and annotation scores of each component, (k,).
289
+
290
+ The default statistic of `estimator_test`, for any fitted estimator whose
291
+ ``transform(X, Y)`` returns ``(x_scores, y_scores)``, as scikit-learn's
292
+ PLSRegression, PLSCanonical, PLSSVD and CCA do.
293
+ """
294
+ x_scores, y_scores = fitted.transform(X, Y_individuals)
295
+ x_scores = x_scores - x_scores.mean(0)
296
+ y_scores = y_scores - y_scores.mean(0)
297
+ return np.abs((x_scores * y_scores).sum(0) / np.sqrt((x_scores**2).sum(0) * (y_scores**2).sum(0)))
298
+
299
+
300
+ def estimator_test(estimator, X, groups, Y, statistic=paired_score_correlation, n_perm=1000, rng=None,
301
+ strata=None, correction="max-t"):
302
+ """Group-level permutation test of a model fitted on individuals, refitted in every permutation.
303
+
304
+ ``estimator`` is any object with a scikit-learn style ``fit(X, Y)``. It is
305
+ copied and fitted on ``X`` and the inherited annotations ``Y[groups]``,
306
+ once for the real table and once per reassignment of its rows among groups.
307
+ ``statistic(fitted, X, Y_individuals)`` returns a number or an array,
308
+ larger meaning more extreme. If the model's components can come out in a
309
+ different order under permutation, as with PLS, later components are tested
310
+ conservatively. For sequential tests use `pls_test` or `cca_test`.
311
+
312
+ Iterative fits are not exact. At saturation, where every permutation
313
+ should reproduce the observed statistic, their rounding noise makes the
314
+ p-value arbitrary rather than 1. Fits on individuals weight groups by
315
+ size, so the test is liberal when large groups carry atypical profiles
316
+ (`pairing_ratio`). Check `groupunit.describe` first. ``correction`` is
317
+ passed to `permutation_test`.
318
+ """
319
+ X = np.asarray(X, float)
320
+ Y = np.asarray(Y, float)
321
+ groups, _ = check_groups(groups, len(Y))
322
+
323
+ def refit(Y_perm):
324
+ Y_individuals = Y_perm[groups]
325
+ # a fresh copy each time, so no fitted state carries over between permutations
326
+ fitted = copy.deepcopy(estimator).fit(X, Y_individuals)
327
+ return statistic(fitted, X, Y_individuals)
328
+
329
+ return permutation_test(refit, Y, n_perm, rng, strata, correction)
330
+
331
+
332
+ @dataclass(frozen=True)
333
+ class CorrelationTest:
334
+ """Correlations of fixed scores with annotations, tested over groups.
335
+
336
+ Attributes
337
+ ----------
338
+ r : (k, q) individual-level correlations, η · r_n; with custom weights,
339
+ the weighted group-level correlations r_w.
340
+ p_value : (k, q) uncorrected two-sided p-values.
341
+ p_fwer : (k, q) family-wise p-values over all k × q cells, by ``correction``.
342
+ correction : "max-t" or "min-p".
343
+ """
344
+
345
+ r: np.ndarray
346
+ p_value: np.ndarray
347
+ p_fwer: np.ndarray
348
+ correction: str = "max-t"
349
+
350
+
351
+ def correlation_test(scores, groups, Y, n_perm=5000, rng=None, strata=None, weights="exchangeable",
352
+ correction="max-t"):
353
+ """Test correlations of scores built without the annotations (Result 1, Section 4.4).
354
+
355
+ ``scores`` (N,) or (N, k) are held fixed: single features chosen in
356
+ advance, PCA components, LDA scores, or CCA factors at saturation. The
357
+ test concerns the group-level correlations, which rest on M groups.
358
+
359
+ By default groups are weighted so that their terms are exchangeable
360
+ (`permutation_weights`), which keeps the test valid when atypical profiles sit on
361
+ large or small groups. ``r`` is then the weighted group-level correlation,
362
+ and the p-values come from the weighted cross-product Σ w_m t̄_m y_m,
363
+ scaled by quantities that do not change under permutation.
364
+ ``weights="size"`` tests the size-weighted correlations instead: ``r`` is
365
+ then the individual-level correlation η · r_n. That test is liberal when
366
+ large groups carry atypical profiles (`pairing_ratio` well above 1).
367
+
368
+ ``correction`` sets the family-wise correction over the k × q cells (see
369
+ `permutation_test`). Max-T suits scores with similar null spreads. If some
370
+ scores are concentrated on a few groups (a small effective number of
371
+ groups behind them), their cells have wider nulls and min-p is the fairer
372
+ choice. Decide before looking at the results.
373
+ """
374
+ Y = np.asarray(Y, float)
375
+ groups, n = check_groups(groups, len(Y))
376
+ scores = np.asarray(scores, float).reshape(len(groups), -1)
377
+ tbar = group_means(scores - scores.mean(0), groups, len(Y))
378
+ Y2 = Y.reshape(len(Y), -1)
379
+ if isinstance(weights, str) and weights == "size":
380
+ eta = np.sqrt(np.atleast_1d(between_share(scores, groups)))
381
+ r = eta[:, None] * weighted_corr(tbar, Y2, n).reshape(len(eta), -1)
382
+
383
+ def statistic(Yp):
384
+ return np.abs(eta[:, None] * weighted_corr(tbar, Yp, n).reshape(len(eta), -1))
385
+ else:
386
+ w = permutation_weights(weights, scores, groups, n)
387
+ r = weighted_corr(tbar, Y2, w).reshape(tbar.shape[1], -1)
388
+ wt = w[:, None] * wcentre(tbar, w) # sums to zero, so Y needs no re-centring
389
+ scale = np.outer(np.sqrt((wt * wcentre(tbar, w)).sum(0)), Y2.std(0))
390
+
391
+ def statistic(Yp):
392
+ with np.errstate(divide="ignore", invalid="ignore"):
393
+ return np.abs(wt.T @ Yp / scale)
394
+
395
+ result = permutation_test(lambda Yp: np.nan_to_num(statistic(Yp)), Y2, n_perm, rng, strata, correction)
396
+ return CorrelationTest(r=r, p_value=result.p_value, p_fwer=result.p_fwer, correction=correction)
397
+
398
+
399
+ @dataclass(frozen=True)
400
+ class SequentialTest:
401
+ """Sequential permutation tests of components.
402
+
403
+ Attributes
404
+ ----------
405
+ strength : (k,) observed singular values or canonical correlations.
406
+ p_value : (k,) p-value of component c after removing components 1..c-1,
407
+ made non-decreasing so that testing stops at the first non-significant one.
408
+ fit : the fitted `Components` on the real annotations.
409
+ """
410
+
411
+ strength: np.ndarray
412
+ p_value: np.ndarray
413
+ fit: object
414
+
415
+
416
+ def pls_test(X, groups, Y, n_components=None, n_perm=5000, rng=None, weights="exchangeable", strata=None):
417
+ """Sequential group-level permutation test of PLS components (Section 4.4).
418
+
419
+ PLS weights depend on the annotations, so the model is refitted in every
420
+ permutation. For component c, the first c - 1 components are removed from
421
+ both sides before permuting (Winkler et al. 2020). Only the group means
422
+ enter, so the test is fast. Selection of annotations or of the number of
423
+ components is not repeated here; wrap the whole pipeline in
424
+ `permutation_test` if it was data-driven.
425
+
426
+ By default groups are weighted so that their terms are exchangeable
427
+ (`permutation_weights`), so ``fit`` is the PLS fit with those weights. For a
428
+ size-weighted description of the data, fit `groupunit.pls` separately.
429
+ ``weights="size"`` tests the size-weighted fit, which is liberal when
430
+ large groups carry atypical profiles (`pairing_ratio` well above 1).
431
+ """
432
+ Y = np.asarray(Y, float)
433
+ groups, n = check_groups(groups, len(Y))
434
+ w = permutation_weights(weights, X, groups, n)
435
+ fit = pls(X, groups, Y, n_components, w)
436
+ Xbar = group_means(X, groups, len(Y))
437
+ Xb = Xbar - w @ Xbar / w.sum()
438
+ Yc = wcentre(Y, w)
439
+ perms = draw_permutations(len(Y), n_perm, rng, strata)
440
+
441
+ p = np.empty(len(fit.strength))
442
+ for c, observed in enumerate(fit.strength):
443
+ Wd, Vd = fit.x_weights[:, :c], fit.y_weights[:, :c]
444
+ XtW = (Xb - Xb @ Wd @ Wd.T).T * w
445
+ Yd = Yc - Yc @ Vd @ Vd.T
446
+ null = [np.linalg.norm(XtW @ wcentre(Yd[perm], w), 2) for perm in perms]
447
+ p[c] = p_value(observed, null)
448
+ return SequentialTest(fit.strength, np.maximum.accumulate(p), fit)
449
+
450
+
451
+ @dataclass(frozen=True)
452
+ class SizeCheck:
453
+ """Estimated size of a test for one design (Result 5, Section 4.3).
454
+
455
+ Attributes
456
+ ----------
457
+ rate : share of simulated null data sets in which the test rejected.
458
+ se : its binomial standard error, sqrt(rate (1 − rate) / n_sim).
459
+ alpha : the nominal level.
460
+ p_values : (n_sim,) the smallest p-value the test returned for each data set.
461
+ """
462
+
463
+ rate: float
464
+ se: float
465
+ alpha: float
466
+ p_values: np.ndarray
467
+
468
+
469
+ def size_check(test, n, Y, tau2, sigma2_w, p=1, n_sim=200, alpha=0.05, rng=None):
470
+ """How often a test rejects for this design when features and annotations are unrelated.
471
+
472
+ The pairing ratio compares averages, while a test's level depends on the
473
+ tails of its null distribution, so a ratio near 1 does not guarantee the
474
+ level (Result 5a). This checks the level directly for the design at hand.
475
+ It keeps the group sizes ``n`` and the annotation table ``Y`` as observed,
476
+ draws features with no relation to the annotations,
477
+
478
+ x_i = u_m(i) + ε_i, u_m ~ N(0, τ² I), ε_i ~ N(0, σ²_w I),
479
+
480
+ so that each group mean has variance v_m = τ² + σ²_w / n_m, runs ``test``
481
+ on each data set and records how often it rejects at ``alpha``.
482
+
483
+ ``test(X, groups, Y, rng)`` runs the test and returns a p-value or an
484
+ array of p-values; the data set counts as a rejection if the smallest is
485
+ at most ``alpha``, so return family-wise p-values for a family of cells.
486
+ For example, for the first PLS component::
487
+
488
+ size_check(lambda X, g, Y, rng: pls_test(X, g, Y, n_components=1, n_perm=199,
489
+ rng=rng).p_value[0],
490
+ n, Y, vc.tau2, vc.sigma2_w)
491
+
492
+ with ``vc`` from `groupunit.weights.pooled_variance_components`. Estimate
493
+ τ² around the grand mean, not around the annotations, so that the check
494
+ is possible at any annotation ratio. ``p`` is the number of simulated
495
+ features: use the number the test sees, or a smaller one when only a
496
+ rough check is needed. The features are Gaussian and independent, so the
497
+ check covers the design (sizes, profiles, variance components), not
498
+ heavy tails or correlated features. With 200 data sets the standard error
499
+ at a true rate of 0.05 is about 0.015.
500
+ """
501
+ rng = np.random.default_rng(rng)
502
+ n = np.asarray(n, int)
503
+ Y = np.asarray(Y, float)
504
+ if Y.shape[0] != len(n):
505
+ raise ValueError(f"Y has {Y.shape[0]} rows but there are {len(n)} groups")
506
+ if tau2 < 0 or sigma2_w < 0 or tau2 + sigma2_w == 0:
507
+ raise ValueError("tau2 and sigma2_w must be non-negative and not both zero")
508
+ p_values = np.empty(n_sim)
509
+ for s in range(n_sim):
510
+ X, groups, _ = simulate(n, p, Y=Y, beta=0.0, tau2=tau2, sigma2_w=sigma2_w, rng=rng)
511
+ p_values[s] = np.min(test(X, groups, Y, rng))
512
+ rate = float((p_values <= alpha).mean())
513
+ return SizeCheck(rate, float(np.sqrt(rate * (1 - rate) / n_sim)), alpha, p_values)
514
+
515
+
516
+ def cca_test(X, groups, Y, n_components=None, n_perm=5000, rng=None, strata=None, weights="size"):
517
+ """Sequential group-level permutation test of canonical correlations.
518
+
519
+ Refits CCA in every permutation, removing the first c - 1 canonical
520
+ variates before testing the c-th. If the annotations have rank M - 1
521
+ (κ = 1), every permutation gives the same result and no test of the
522
+ annotations is possible (Result 3c); this raises an error.
523
+
524
+ Ordinary CCA weights groups by size (``weights="size"``, the default), so
525
+ like size-weighted PLS it is liberal when large groups carry atypical
526
+ profiles (`pairing_ratio` well above 1). ``weights="exchangeable"`` or an
527
+ array fits and tests row-weighted CCA instead (see `groupunit.cca`), in
528
+ which group m carries total weight w_m. Canonical correlations are
529
+ ratios, so whether exchangeable weights restore the level as they do for
530
+ PLS is an empirical question; check the design with `size_check`.
531
+ """
532
+ Y = np.asarray(Y, float)
533
+ groups, n = check_groups(groups, len(Y))
534
+ X = np.asarray(X, float)
535
+ w = permutation_weights(weights, X, groups, n)
536
+ Ux, sx, Vxt, x_mean, P, Q = _cca_spaces(X, groups, Y, w)
537
+ if Q.shape[1] >= len(Y) - 1:
538
+ raise ValueError("the annotations span all M - 1 between-group directions (kappa = 1): CCA equals "
539
+ "LDA for any annotation table and cannot be tested against the annotations. "
540
+ "Reduce the annotations first, e.g. with reduce_annotations().")
541
+ fit = cca(X, groups, Y, n_components, weights=w)
542
+
543
+ # canonical correlations = svd(Pᵀ Q); full SVD: deflation must keep every remaining
544
+ # direction of both spaces, not only the paired ones
545
+ A, rho, Bt = np.linalg.svd(P.T @ Q, full_matrices=True)
546
+ perms = draw_permutations(len(Y), n_perm, rng, strata)
547
+
548
+ p = np.empty(len(fit.strength))
549
+ for c, observed in enumerate(fit.strength):
550
+ Pd = P @ A[:, c:]
551
+ Yd = (Q @ Bt[c:].T) / np.sqrt(w)[:, None] # annotation table spanning the deflated space
552
+ null = [np.linalg.norm(Pd.T @ weighted_basis(Yd[perm], w), 2) for perm in perms]
553
+ p[c] = p_value(observed, null)
554
+ return SequentialTest(fit.strength, np.maximum.accumulate(p), fit)