groupunit 0.2.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/LICENSE +21 -0
- groupunit-0.2.0/PKG-INFO +107 -0
- groupunit-0.2.0/README.md +77 -0
- groupunit-0.2.0/pyproject.toml +41 -0
- groupunit-0.2.0/setup.cfg +4 -0
- groupunit-0.2.0/src/groupunit/__init__.py +60 -0
- groupunit-0.2.0/src/groupunit/core.py +148 -0
- groupunit-0.2.0/src/groupunit/design.py +168 -0
- groupunit-0.2.0/src/groupunit/diagnostics.py +273 -0
- groupunit-0.2.0/src/groupunit/inference.py +554 -0
- groupunit-0.2.0/src/groupunit/methods.py +149 -0
- groupunit-0.2.0/src/groupunit/scores.py +80 -0
- groupunit-0.2.0/src/groupunit/similarity.py +199 -0
- groupunit-0.2.0/src/groupunit/simulate.py +44 -0
- groupunit-0.2.0/src/groupunit/validation.py +106 -0
- groupunit-0.2.0/src/groupunit/weights.py +102 -0
- groupunit-0.2.0/src/groupunit.egg-info/PKG-INFO +107 -0
- groupunit-0.2.0/src/groupunit.egg-info/SOURCES.txt +28 -0
- groupunit-0.2.0/src/groupunit.egg-info/dependency_links.txt +1 -0
- groupunit-0.2.0/src/groupunit.egg-info/requires.txt +14 -0
- groupunit-0.2.0/src/groupunit.egg-info/top_level.txt +1 -0
- groupunit-0.2.0/tests/test_diagnostics.py +123 -0
- groupunit-0.2.0/tests/test_identities.py +97 -0
- groupunit-0.2.0/tests/test_inference.py +192 -0
- groupunit-0.2.0/tests/test_pairing_size_lens.py +175 -0
- groupunit-0.2.0/tests/test_results_2_4_5.py +169 -0
- groupunit-0.2.0/tests/test_similarity.py +71 -0
- groupunit-0.2.0/tests/test_sklearn.py +66 -0
- groupunit-0.2.0/tests/test_validation.py +27 -0
- groupunit-0.2.0/tests/test_weights.py +37 -0
groupunit-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tim Kmecl
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
groupunit-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: groupunit
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Correlation, PLS, CCA and similarity analyses when annotations exist only for groups
|
|
5
|
+
Author-email: Tim Kmecl <tim.kmecl.tk@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/timkmecl/groupunit
|
|
8
|
+
Project-URL: Documentation, https://timkmecl.github.io/groupunit/
|
|
9
|
+
Project-URL: Issues, https://github.com/timkmecl/groupunit/issues
|
|
10
|
+
Keywords: group-level variables,pseudoreplication,permutation test,PLS,CCA,representational similarity
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: numpy>=1.22
|
|
19
|
+
Requires-Dist: scipy>=1.8
|
|
20
|
+
Provides-Extra: test
|
|
21
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
22
|
+
Requires-Dist: scikit-learn>=1.2; extra == "test"
|
|
23
|
+
Provides-Extra: docs
|
|
24
|
+
Requires-Dist: mkdocs-material>=9; extra == "docs"
|
|
25
|
+
Requires-Dist: mkdocstrings[python]>=0.24; extra == "docs"
|
|
26
|
+
Provides-Extra: simulations
|
|
27
|
+
Requires-Dist: pandas>=1.5; extra == "simulations"
|
|
28
|
+
Requires-Dist: tabulate>=0.9; extra == "simulations"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# groupunit
|
|
32
|
+
|
|
33
|
+
Software for designs in which detailed measurements of individuals are related
|
|
34
|
+
to variables that exist only for the groups they belong to: text features of
|
|
35
|
+
drug experience reports and each drug's receptor profile, brain regions and
|
|
36
|
+
parcel-level atlas maps, patients and characteristics of their hospital.
|
|
37
|
+
|
|
38
|
+
It accompanies Kmecl, *The group is the unit: limits of correlation, PLS and
|
|
39
|
+
CCA with group-level variables* (methods paper, Appendix D). The package
|
|
40
|
+
computes the quantities the paper derives, and the diagnostics, tests and
|
|
41
|
+
validation it recommends. Every test resamples groups, never individuals.
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install -e . # NumPy and SciPy only
|
|
47
|
+
pip install -e ".[test]" # + pytest and scikit-learn; run `pytest`
|
|
48
|
+
pip install -e ".[docs]" # + MkDocs; run `mkdocs serve`
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Requires Python 3.10+.
|
|
52
|
+
|
|
53
|
+
## Example
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import numpy as np
|
|
57
|
+
import groupunit as gu
|
|
58
|
+
|
|
59
|
+
groups, names = gu.encode_groups(report_drug, order=drug_table.index) # labels -> 0..M-1
|
|
60
|
+
Y = drug_table.to_numpy(float) # (M, q), one row per group
|
|
61
|
+
n = gu.group_sizes(groups, len(Y))
|
|
62
|
+
|
|
63
|
+
print(gu.describe(groups, Y, X)) # N, M, r, kappa = r/(M-1), effective groups, warnings
|
|
64
|
+
|
|
65
|
+
Y3, _ = gu.reduce_annotations(Y, n, 3) # reduce in advance if kappa is near 1
|
|
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 carry each component
|
|
68
|
+
print(test.p_value, shares.m_eff, gu.pairing_ratio(Y3, n))
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`examples/walkthrough.py` goes through the paper's checklist on simulated data.
|
|
72
|
+
|
|
73
|
+
## Documentation
|
|
74
|
+
|
|
75
|
+
The documentation is published at https://timkmecl.github.io/groupunit/.
|
|
76
|
+
Its source is in `docs/`; build it locally with `mkdocs serve`, or read the
|
|
77
|
+
Markdown directly:
|
|
78
|
+
|
|
79
|
+
- [Concepts](docs/concepts.md): the ideas behind the package, in a few pages.
|
|
80
|
+
- [Workflow](docs/guide.md): from data to reporting, following the paper's checklist.
|
|
81
|
+
- [Testing and validation](docs/testing.md): what to permute, what to refit, unequal group sizes.
|
|
82
|
+
- [Similarity designs](docs/similarity.md): typicality versus pattern.
|
|
83
|
+
- [Published results](docs/published.md): diagnostics from digitised group means.
|
|
84
|
+
- [Other models and scores](docs/other-models.md): scikit-learn models, scores from any method.
|
|
85
|
+
- [Simulations](docs/simulations.md): the simulation study of §6.
|
|
86
|
+
- [API reference](docs/api.md): generated from the docstrings; readable only in the built site.
|
|
87
|
+
|
|
88
|
+
## Layout
|
|
89
|
+
|
|
90
|
+
| Module | Paper | Contents |
|
|
91
|
+
| ------------- | --------------- | ------------------------------------------------------------------------- |
|
|
92
|
+
| `core` | §2 | group codes and means, weighted centring, correlation and R², annotation rank |
|
|
93
|
+
| `design` | §3.3, Box 1 | `describe`, `r2_null`, `reduce_annotations` |
|
|
94
|
+
| `scores` | Results 1, 3a | between-group share η², `decompose_score` |
|
|
95
|
+
| `methods` | §3.2–3.3 | `pls`, `cca` (optionally row-weighted), `lda`, computed through the group means |
|
|
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` | §3.4, Results 4a–4c | typicality and pattern, `similarity_decomposition`, `compare_similarity`, `distance_similarity` |
|
|
99
|
+
| `inference` | §4.2–4.5, Result 5 | `correlation_test`, `pls_test`, `cca_test`, `estimator_test`, `permutation_test`, `pairing_ratio`, `pairing_terms`, `size_check` |
|
|
100
|
+
| `validation` | §4.5 | `leave_one_group_out`, `pca_regression`, scikit-learn models |
|
|
101
|
+
| `simulate` | §6.1 | `simulate`, `lognormal_sizes` |
|
|
102
|
+
|
|
103
|
+
`simulations/` holds the simulation study of the paper. `tests/` checks the
|
|
104
|
+
identities against direct computation and pins the numbers of the paper's
|
|
105
|
+
toy figures. GitHub Actions run the tests, publish the documentation to
|
|
106
|
+
GitHub Pages and release to PyPI. AGENTS.md ("CI and releasing") lists the
|
|
107
|
+
steps.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# groupunit
|
|
2
|
+
|
|
3
|
+
Software for designs in which detailed measurements of individuals are related
|
|
4
|
+
to variables that exist only for the groups they belong to: text features of
|
|
5
|
+
drug experience reports and each drug's receptor profile, brain regions and
|
|
6
|
+
parcel-level atlas maps, patients and characteristics of their hospital.
|
|
7
|
+
|
|
8
|
+
It accompanies Kmecl, *The group is the unit: limits of correlation, PLS and
|
|
9
|
+
CCA with group-level variables* (methods paper, Appendix D). The package
|
|
10
|
+
computes the quantities the paper derives, and the diagnostics, tests and
|
|
11
|
+
validation it recommends. Every test resamples groups, never individuals.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install -e . # NumPy and SciPy only
|
|
17
|
+
pip install -e ".[test]" # + pytest and scikit-learn; run `pytest`
|
|
18
|
+
pip install -e ".[docs]" # + MkDocs; run `mkdocs serve`
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Requires Python 3.10+.
|
|
22
|
+
|
|
23
|
+
## Example
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import numpy as np
|
|
27
|
+
import groupunit as gu
|
|
28
|
+
|
|
29
|
+
groups, names = gu.encode_groups(report_drug, order=drug_table.index) # labels -> 0..M-1
|
|
30
|
+
Y = drug_table.to_numpy(float) # (M, q), one row per group
|
|
31
|
+
n = gu.group_sizes(groups, len(Y))
|
|
32
|
+
|
|
33
|
+
print(gu.describe(groups, Y, X)) # N, M, r, kappa = r/(M-1), effective groups, warnings
|
|
34
|
+
|
|
35
|
+
Y3, _ = gu.reduce_annotations(Y, n, 3) # reduce in advance if kappa is near 1
|
|
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 carry each component
|
|
38
|
+
print(test.p_value, shares.m_eff, gu.pairing_ratio(Y3, n))
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`examples/walkthrough.py` goes through the paper's checklist on simulated data.
|
|
42
|
+
|
|
43
|
+
## Documentation
|
|
44
|
+
|
|
45
|
+
The documentation is published at https://timkmecl.github.io/groupunit/.
|
|
46
|
+
Its source is in `docs/`; build it locally with `mkdocs serve`, or read the
|
|
47
|
+
Markdown directly:
|
|
48
|
+
|
|
49
|
+
- [Concepts](docs/concepts.md): the ideas behind the package, in a few pages.
|
|
50
|
+
- [Workflow](docs/guide.md): from data to reporting, following the paper's checklist.
|
|
51
|
+
- [Testing and validation](docs/testing.md): what to permute, what to refit, unequal group sizes.
|
|
52
|
+
- [Similarity designs](docs/similarity.md): typicality versus pattern.
|
|
53
|
+
- [Published results](docs/published.md): diagnostics from digitised group means.
|
|
54
|
+
- [Other models and scores](docs/other-models.md): scikit-learn models, scores from any method.
|
|
55
|
+
- [Simulations](docs/simulations.md): the simulation study of §6.
|
|
56
|
+
- [API reference](docs/api.md): generated from the docstrings; readable only in the built site.
|
|
57
|
+
|
|
58
|
+
## Layout
|
|
59
|
+
|
|
60
|
+
| Module | Paper | Contents |
|
|
61
|
+
| ------------- | --------------- | ------------------------------------------------------------------------- |
|
|
62
|
+
| `core` | §2 | group codes and means, weighted centring, correlation and R², annotation rank |
|
|
63
|
+
| `design` | §3.3, Box 1 | `describe`, `r2_null`, `reduce_annotations` |
|
|
64
|
+
| `scores` | Results 1, 3a | between-group share η², `decompose_score` |
|
|
65
|
+
| `methods` | §3.2–3.3 | `pls`, `cca` (optionally row-weighted), `lda`, computed through the group means |
|
|
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` | §3.4, Results 4a–4c | typicality and pattern, `similarity_decomposition`, `compare_similarity`, `distance_similarity` |
|
|
69
|
+
| `inference` | §4.2–4.5, Result 5 | `correlation_test`, `pls_test`, `cca_test`, `estimator_test`, `permutation_test`, `pairing_ratio`, `pairing_terms`, `size_check` |
|
|
70
|
+
| `validation` | §4.5 | `leave_one_group_out`, `pca_regression`, scikit-learn models |
|
|
71
|
+
| `simulate` | §6.1 | `simulate`, `lognormal_sizes` |
|
|
72
|
+
|
|
73
|
+
`simulations/` holds the simulation study of the paper. `tests/` checks the
|
|
74
|
+
identities against direct computation and pins the numbers of the paper's
|
|
75
|
+
toy figures. GitHub Actions run the tests, publish the documentation to
|
|
76
|
+
GitHub Pages and release to PyPI. AGENTS.md ("CI and releasing") lists the
|
|
77
|
+
steps.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"] # for the SPDX `license` field
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "groupunit"
|
|
7
|
+
dynamic = ["version"] # set in src/groupunit/__init__.py
|
|
8
|
+
description = "Correlation, PLS, CCA and similarity analyses when annotations exist only for groups"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
authors = [{ name = "Tim Kmecl", email = "tim.kmecl.tk@gmail.com" }]
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
keywords = ["group-level variables", "pseudoreplication", "permutation test", "PLS", "CCA",
|
|
15
|
+
"representational similarity"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Intended Audience :: Science/Research",
|
|
19
|
+
"Topic :: Scientific/Engineering :: Information Analysis",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
]
|
|
22
|
+
dependencies = ["numpy>=1.22", "scipy>=1.8"]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://github.com/timkmecl/groupunit"
|
|
26
|
+
Documentation = "https://timkmecl.github.io/groupunit/"
|
|
27
|
+
Issues = "https://github.com/timkmecl/groupunit/issues"
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
test = ["pytest>=7", "scikit-learn>=1.2"]
|
|
31
|
+
docs = ["mkdocs-material>=9", "mkdocstrings[python]>=0.24"]
|
|
32
|
+
simulations = ["pandas>=1.5", "tabulate>=0.9"] # also enough for figures/
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
where = ["src"]
|
|
36
|
+
|
|
37
|
+
[tool.setuptools.dynamic]
|
|
38
|
+
version = { attr = "groupunit.__version__" }
|
|
39
|
+
|
|
40
|
+
[tool.pytest.ini_options]
|
|
41
|
+
testpaths = ["tests"]
|
|
@@ -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"
|
|
@@ -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
|
|
@@ -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]
|