clustrust 0.1.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.
Files changed (32) hide show
  1. clustrust-0.1.0/LICENSE +21 -0
  2. clustrust-0.1.0/PKG-INFO +196 -0
  3. clustrust-0.1.0/README.md +159 -0
  4. clustrust-0.1.0/pyproject.toml +46 -0
  5. clustrust-0.1.0/setup.cfg +4 -0
  6. clustrust-0.1.0/src/clustrust/__init__.py +0 -0
  7. clustrust-0.1.0/src/clustrust/__main__.py +3 -0
  8. clustrust-0.1.0/src/clustrust/core/__init__.py +0 -0
  9. clustrust-0.1.0/src/clustrust/core/agreement.py +17 -0
  10. clustrust-0.1.0/src/clustrust/core/algorithms.py +19 -0
  11. clustrust-0.1.0/src/clustrust/core/calibrate.py +70 -0
  12. clustrust-0.1.0/src/clustrust/core/consensus.py +51 -0
  13. clustrust-0.1.0/src/clustrust/core/defaults.py +66 -0
  14. clustrust-0.1.0/src/clustrust/core/evidence.py +116 -0
  15. clustrust-0.1.0/src/clustrust/core/indices.py +26 -0
  16. clustrust-0.1.0/src/clustrust/core/null.py +23 -0
  17. clustrust-0.1.0/src/clustrust/core/profiles.py +19 -0
  18. clustrust-0.1.0/src/clustrust/core/runner.py +28 -0
  19. clustrust-0.1.0/src/clustrust/core/stability.py +62 -0
  20. clustrust-0.1.0/src/clustrust/core/tendency.py +46 -0
  21. clustrust-0.1.0/src/clustrust/gui/__init__.py +0 -0
  22. clustrust-0.1.0/src/clustrust/gui/app.py +853 -0
  23. clustrust-0.1.0/src/clustrust/gui/tooltip.py +25 -0
  24. clustrust-0.1.0/src/clustrust/io/export.py +122 -0
  25. clustrust-0.1.0/src/clustrust/io/loaders.py +57 -0
  26. clustrust-0.1.0/src/clustrust.egg-info/PKG-INFO +196 -0
  27. clustrust-0.1.0/src/clustrust.egg-info/SOURCES.txt +30 -0
  28. clustrust-0.1.0/src/clustrust.egg-info/dependency_links.txt +1 -0
  29. clustrust-0.1.0/src/clustrust.egg-info/entry_points.txt +2 -0
  30. clustrust-0.1.0/src/clustrust.egg-info/requires.txt +13 -0
  31. clustrust-0.1.0/src/clustrust.egg-info/top_level.txt +1 -0
  32. clustrust-0.1.0/tests/test_core.py +296 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Elena Mehana, Lynn Lichaa
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.
@@ -0,0 +1,196 @@
1
+ Metadata-Version: 2.4
2
+ Name: clustrust
3
+ Version: 0.1.0
4
+ Summary: Null-calibrated desktop tool and library for judging how many clusters a dataset contains and whether they can be trusted
5
+ Author: Elena Mehana, Lynn Lichaa
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/elenamehana/clustrust
8
+ Project-URL: Repository, https://github.com/elenamehana/clustrust
9
+ Project-URL: Issues, https://github.com/elenamehana/clustrust/issues
10
+ Project-URL: Changelog, https://github.com/elenamehana/clustrust/blob/main/CHANGELOG.md
11
+ Keywords: clustering,cluster validity,stability,consensus clustering,null calibration,reproducibility
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: Microsoft :: Windows
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: numpy
26
+ Requires-Dist: pandas
27
+ Requires-Dist: scikit-learn
28
+ Requires-Dist: matplotlib
29
+ Requires-Dist: scipy
30
+ Requires-Dist: joblib
31
+ Provides-Extra: full
32
+ Requires-Dist: diptest; extra == "full"
33
+ Provides-Extra: dev
34
+ Requires-Dist: pytest; extra == "dev"
35
+ Requires-Dist: pytest-cov; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ # ClusTrust
39
+
40
+ A desktop tool and Python library that answers two questions about clustering:
41
+ **how many clusters are in my data, and can I trust them?**
42
+
43
+ Validity indices such as the silhouette always return a best number of clusters of
44
+ two or more, even for data with no groups. ClusTrust runs several algorithms over a
45
+ range of k, scores them with validity indices, tests stability by resampling, builds
46
+ a consensus clustering, and compares every score with structureless reference data.
47
+ The honest answer can therefore be **"no evidence of clusters"**.
48
+
49
+ ![No clusters found](docs/figures/noise_evidence.png)
50
+ ![Ambiguous structure](docs/figures/overlap_evidence.png)
51
+
52
+ ## Features
53
+
54
+ - **Null-calibrated scores:** silhouette, Calinski-Harabasz and Davies-Bouldin are
55
+ turned into z-scores against structureless data (Gaussian null, uniform-over-principal-components
56
+ null, or both; the default requires beating both).
57
+ - **One evidence profile per k:** calibrated indices, resampling stability, PAC and
58
+ agreement between algorithms, with a verdict: *Clear structure*, *Weak or ambiguous
59
+ structure* or *No evidence of clusters*.
60
+ - **Trust at three levels:** for the whole solution, for each cluster (Jaccard
61
+ stability) and for each point (consensus confidence).
62
+ - **No programming needed:** an offline Tkinter interface; your data stays on your computer.
63
+ - **Reproducible:** one global seed, and every session can be exported as
64
+ `session.json` plus a `replay.py` script that repeats the analysis.
65
+
66
+ Algorithms: k-means, agglomerative clustering, Gaussian mixture.
67
+ Input: CSV files (numeric columns are used).
68
+
69
+ ## Install
70
+
71
+ Requires Python 3.10 or later, with Tkinter available in your Python installation.
72
+
73
+ ```
74
+ pip install "clustrust[full]"
75
+ ```
76
+
77
+ Or from source:
78
+
79
+ ```
80
+ git clone https://github.com/elenamehana/clustrust.git
81
+ cd clustrust
82
+ pip install -e ".[full]"
83
+ ```
84
+
85
+ The `full` extra installs `diptest`, which enables the dip test in the tendency check.
86
+ Without it everything else still works.
87
+
88
+ ## Start the graphical interface
89
+
90
+ ```
91
+ python -m clustrust
92
+ ```
93
+
94
+ 1. Click **Load CSV**. Set scaling, missing-value handling, optional log(1 + x) and
95
+ optional PCA, then click **Apply to data**.
96
+ 2. Choose the algorithms, the range of k, the seed and the **Run size**:
97
+ - *quick*: 20 resamples, 20 null sets, Gaussian null. For exploring.
98
+ - *literature*: 100 resamples, 100 null sets, both nulls. Much slower
99
+ (roughly an hour on a 2-core laptop for a few hundred rows).
100
+ 3. Optional first step: **Check tendency** (Hopkins statistic and dip test).
101
+ 4. **Run evidence analysis** gives the verdict, the best-supported k and the table of
102
+ criteria for every k. Thresholds can be changed and the verdict refreshed with
103
+ **Update verdict**; **Literature defaults** restores the published values.
104
+ 5. **Run consensus** builds the final grouping with confidence per point, trust per
105
+ cluster and a profile of what each cluster looks like.
106
+ 6. **Export session** saves the settings, parameter sources, package versions,
107
+ results and a replay script.
108
+
109
+ Hover over any control for a plain-language explanation and the default with its source.
110
+
111
+ ## Quick start from Python
112
+
113
+ ```python
114
+ from clustrust.io.loaders import load_csv, prepare
115
+ from clustrust.core.evidence import evidence_profile, summarize
116
+
117
+ df = load_csv("examples/overlap_blobs/overlap_blobs.csv")
118
+ X, columns = prepare(df, scale="standard")
119
+ prof, cal = evidence_profile(X, k_range=range(2, 7), n_null=20, n_rounds=20)
120
+ print(prof.round(3))
121
+ print(summarize(prof)) # verdict, reason, best_k, passing k
122
+ ```
123
+
124
+ `evidence_profile` with no arguments uses the literature defaults (100 null sets,
125
+ 100 resamples, both nulls).
126
+
127
+ ## How the verdict works
128
+
129
+ For each k, ClusTrust checks that at least 2 of the 3 indices beat the null (z above 2),
130
+ that stability is at least 0.80 and that agreement between algorithms is at least 0.80.
131
+
132
+ - No index beats the null at any k: **No evidence of clusters**.
133
+ - Exactly one k passes, or the lowest-PAC k among the passing k is also favoured by
134
+ most indices: **Clear structure**.
135
+ - Otherwise: **Weak or ambiguous structure**, with the passing k and the index
136
+ favourites listed.
137
+
138
+ Every threshold is an adjustable default, not a validated constant. Their sources are
139
+ listed in `src/clustrust/core/defaults.py` and recorded in every `session.json`.
140
+
141
+ ## Worked examples
142
+
143
+ The `examples/` folder holds the data, the exported session and the results for each case study.
144
+ All use the literature preset (seed 42, k = 2 to 8, three algorithms).
145
+
146
+ | Example | Data | Verdict |
147
+ | --- | --- | --- |
148
+ | `wine` | 178 wines, 13 chemical measurements | Clear structure, k = 3 |
149
+ | `wholesale` | 440 customers, 6 spending variables (log-transformed) | Weak or ambiguous structure |
150
+ | `gene_expression` | 801 tumours, 500 genes, PCA to 20 components | Weak or ambiguous (k = 3 to 8 all pass) |
151
+ | `wine_shuffled` | Wine with every column permuted: structureless control | No evidence of clusters |
152
+ | `noise` | 500 points, 2 Gaussian variables, no groups | No evidence of clusters |
153
+ | `noise_uniform` | 500 points, 3 uniform variables, no groups | No evidence of clusters |
154
+ | `overlap_blobs` | 500 points, 4 overlapping true groups | Weak or ambiguous (k = 3, 4, 5 pass; best k = 4) |
155
+
156
+ Each folder has a `replay.py` (run it inside the folder to reproduce the analysis),
157
+ a `NOTES.md` where available, and a `DATA_LICENSE.md` with the source and licence.
158
+ Reference labels are used only after the analysis, to check the results
159
+ (`benchmarks/check_labels.py`).
160
+
161
+ The real datasets come from the UCI Machine Learning Repository under CC BY 4.0.
162
+ Re-create them with `python examples/make_examples.py` (needs `pip install ucimlrepo`)
163
+ `python examples/make_gene_expression.py` (needs the manually downloaded TCGA archive)
164
+ and `python examples/make_synthetic.py` (generates the three synthetic examples).
165
+
166
+ ## Benchmarks
167
+
168
+ `benchmarks/run_benchmark.py` runs a sanity check on generated data: noise, blobs and
169
+ two moons. `benchmarks/sensitivity.py` shows how the verdict changes when the
170
+ thresholds change. These are sanity checks with small samples, not validated error rates.
171
+
172
+ ## Limitations
173
+
174
+ - Three algorithms only; non-convex shapes (for example two moons) are not recovered.
175
+ - Numeric data only; the interface limits consensus to 2000 rows.
176
+ - The verdict depends on adjustable thresholds, some of which are literature values
177
+ applied by analogy.
178
+ - The evidence profile is best read as a set of plausible k with reasons, not as a
179
+ point estimate of k. When several k pass, the best-supported k is the coarsest
180
+ by PAC tie-break.
181
+ - Stability and consensus can look convincing on structureless data; only the null
182
+ calibration exposes this.
183
+
184
+ ## Tests
185
+
186
+ ```
187
+ pip install -e ".[full,dev]"
188
+ pytest
189
+ ```
190
+
191
+ Continuous integration runs the tests on Windows and Linux with Python 3.10 and 3.12.
192
+
193
+ ## License and citation
194
+
195
+ MIT License (see `LICENSE`). If you use this software, please cite it
196
+ (see `CITATION.cff`).
@@ -0,0 +1,159 @@
1
+ # ClusTrust
2
+
3
+ A desktop tool and Python library that answers two questions about clustering:
4
+ **how many clusters are in my data, and can I trust them?**
5
+
6
+ Validity indices such as the silhouette always return a best number of clusters of
7
+ two or more, even for data with no groups. ClusTrust runs several algorithms over a
8
+ range of k, scores them with validity indices, tests stability by resampling, builds
9
+ a consensus clustering, and compares every score with structureless reference data.
10
+ The honest answer can therefore be **"no evidence of clusters"**.
11
+
12
+ ![No clusters found](docs/figures/noise_evidence.png)
13
+ ![Ambiguous structure](docs/figures/overlap_evidence.png)
14
+
15
+ ## Features
16
+
17
+ - **Null-calibrated scores:** silhouette, Calinski-Harabasz and Davies-Bouldin are
18
+ turned into z-scores against structureless data (Gaussian null, uniform-over-principal-components
19
+ null, or both; the default requires beating both).
20
+ - **One evidence profile per k:** calibrated indices, resampling stability, PAC and
21
+ agreement between algorithms, with a verdict: *Clear structure*, *Weak or ambiguous
22
+ structure* or *No evidence of clusters*.
23
+ - **Trust at three levels:** for the whole solution, for each cluster (Jaccard
24
+ stability) and for each point (consensus confidence).
25
+ - **No programming needed:** an offline Tkinter interface; your data stays on your computer.
26
+ - **Reproducible:** one global seed, and every session can be exported as
27
+ `session.json` plus a `replay.py` script that repeats the analysis.
28
+
29
+ Algorithms: k-means, agglomerative clustering, Gaussian mixture.
30
+ Input: CSV files (numeric columns are used).
31
+
32
+ ## Install
33
+
34
+ Requires Python 3.10 or later, with Tkinter available in your Python installation.
35
+
36
+ ```
37
+ pip install "clustrust[full]"
38
+ ```
39
+
40
+ Or from source:
41
+
42
+ ```
43
+ git clone https://github.com/elenamehana/clustrust.git
44
+ cd clustrust
45
+ pip install -e ".[full]"
46
+ ```
47
+
48
+ The `full` extra installs `diptest`, which enables the dip test in the tendency check.
49
+ Without it everything else still works.
50
+
51
+ ## Start the graphical interface
52
+
53
+ ```
54
+ python -m clustrust
55
+ ```
56
+
57
+ 1. Click **Load CSV**. Set scaling, missing-value handling, optional log(1 + x) and
58
+ optional PCA, then click **Apply to data**.
59
+ 2. Choose the algorithms, the range of k, the seed and the **Run size**:
60
+ - *quick*: 20 resamples, 20 null sets, Gaussian null. For exploring.
61
+ - *literature*: 100 resamples, 100 null sets, both nulls. Much slower
62
+ (roughly an hour on a 2-core laptop for a few hundred rows).
63
+ 3. Optional first step: **Check tendency** (Hopkins statistic and dip test).
64
+ 4. **Run evidence analysis** gives the verdict, the best-supported k and the table of
65
+ criteria for every k. Thresholds can be changed and the verdict refreshed with
66
+ **Update verdict**; **Literature defaults** restores the published values.
67
+ 5. **Run consensus** builds the final grouping with confidence per point, trust per
68
+ cluster and a profile of what each cluster looks like.
69
+ 6. **Export session** saves the settings, parameter sources, package versions,
70
+ results and a replay script.
71
+
72
+ Hover over any control for a plain-language explanation and the default with its source.
73
+
74
+ ## Quick start from Python
75
+
76
+ ```python
77
+ from clustrust.io.loaders import load_csv, prepare
78
+ from clustrust.core.evidence import evidence_profile, summarize
79
+
80
+ df = load_csv("examples/overlap_blobs/overlap_blobs.csv")
81
+ X, columns = prepare(df, scale="standard")
82
+ prof, cal = evidence_profile(X, k_range=range(2, 7), n_null=20, n_rounds=20)
83
+ print(prof.round(3))
84
+ print(summarize(prof)) # verdict, reason, best_k, passing k
85
+ ```
86
+
87
+ `evidence_profile` with no arguments uses the literature defaults (100 null sets,
88
+ 100 resamples, both nulls).
89
+
90
+ ## How the verdict works
91
+
92
+ For each k, ClusTrust checks that at least 2 of the 3 indices beat the null (z above 2),
93
+ that stability is at least 0.80 and that agreement between algorithms is at least 0.80.
94
+
95
+ - No index beats the null at any k: **No evidence of clusters**.
96
+ - Exactly one k passes, or the lowest-PAC k among the passing k is also favoured by
97
+ most indices: **Clear structure**.
98
+ - Otherwise: **Weak or ambiguous structure**, with the passing k and the index
99
+ favourites listed.
100
+
101
+ Every threshold is an adjustable default, not a validated constant. Their sources are
102
+ listed in `src/clustrust/core/defaults.py` and recorded in every `session.json`.
103
+
104
+ ## Worked examples
105
+
106
+ The `examples/` folder holds the data, the exported session and the results for each case study.
107
+ All use the literature preset (seed 42, k = 2 to 8, three algorithms).
108
+
109
+ | Example | Data | Verdict |
110
+ | --- | --- | --- |
111
+ | `wine` | 178 wines, 13 chemical measurements | Clear structure, k = 3 |
112
+ | `wholesale` | 440 customers, 6 spending variables (log-transformed) | Weak or ambiguous structure |
113
+ | `gene_expression` | 801 tumours, 500 genes, PCA to 20 components | Weak or ambiguous (k = 3 to 8 all pass) |
114
+ | `wine_shuffled` | Wine with every column permuted: structureless control | No evidence of clusters |
115
+ | `noise` | 500 points, 2 Gaussian variables, no groups | No evidence of clusters |
116
+ | `noise_uniform` | 500 points, 3 uniform variables, no groups | No evidence of clusters |
117
+ | `overlap_blobs` | 500 points, 4 overlapping true groups | Weak or ambiguous (k = 3, 4, 5 pass; best k = 4) |
118
+
119
+ Each folder has a `replay.py` (run it inside the folder to reproduce the analysis),
120
+ a `NOTES.md` where available, and a `DATA_LICENSE.md` with the source and licence.
121
+ Reference labels are used only after the analysis, to check the results
122
+ (`benchmarks/check_labels.py`).
123
+
124
+ The real datasets come from the UCI Machine Learning Repository under CC BY 4.0.
125
+ Re-create them with `python examples/make_examples.py` (needs `pip install ucimlrepo`)
126
+ `python examples/make_gene_expression.py` (needs the manually downloaded TCGA archive)
127
+ and `python examples/make_synthetic.py` (generates the three synthetic examples).
128
+
129
+ ## Benchmarks
130
+
131
+ `benchmarks/run_benchmark.py` runs a sanity check on generated data: noise, blobs and
132
+ two moons. `benchmarks/sensitivity.py` shows how the verdict changes when the
133
+ thresholds change. These are sanity checks with small samples, not validated error rates.
134
+
135
+ ## Limitations
136
+
137
+ - Three algorithms only; non-convex shapes (for example two moons) are not recovered.
138
+ - Numeric data only; the interface limits consensus to 2000 rows.
139
+ - The verdict depends on adjustable thresholds, some of which are literature values
140
+ applied by analogy.
141
+ - The evidence profile is best read as a set of plausible k with reasons, not as a
142
+ point estimate of k. When several k pass, the best-supported k is the coarsest
143
+ by PAC tie-break.
144
+ - Stability and consensus can look convincing on structureless data; only the null
145
+ calibration exposes this.
146
+
147
+ ## Tests
148
+
149
+ ```
150
+ pip install -e ".[full,dev]"
151
+ pytest
152
+ ```
153
+
154
+ Continuous integration runs the tests on Windows and Linux with Python 3.10 and 3.12.
155
+
156
+ ## License and citation
157
+
158
+ MIT License (see `LICENSE`). If you use this software, please cite it
159
+ (see `CITATION.cff`).
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "clustrust"
7
+ version = "0.1.0"
8
+ description = "Null-calibrated desktop tool and library for judging how many clusters a dataset contains and whether they can be trusted"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [
13
+ { name = "Elena Mehana" },
14
+ { name = "Lynn Lichaa" },
15
+ ]
16
+ keywords = ["clustering", "cluster validity", "stability", "consensus clustering",
17
+ "null calibration", "reproducibility"]
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Intended Audience :: Science/Research",
21
+ "License :: OSI Approved :: MIT License",
22
+ "Operating System :: Microsoft :: Windows",
23
+ "Operating System :: POSIX :: Linux",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3.10",
26
+ "Programming Language :: Python :: 3.11",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Topic :: Scientific/Engineering :: Information Analysis",
29
+ ]
30
+ dependencies = ["numpy", "pandas", "scikit-learn", "matplotlib", "scipy", "joblib"]
31
+
32
+ [project.urls]
33
+ Homepage = "https://github.com/elenamehana/clustrust"
34
+ Repository = "https://github.com/elenamehana/clustrust"
35
+ Issues = "https://github.com/elenamehana/clustrust/issues"
36
+ Changelog = "https://github.com/elenamehana/clustrust/blob/main/CHANGELOG.md"
37
+
38
+ [project.gui-scripts]
39
+ clustrust = "clustrust.gui.app:main"
40
+
41
+ [project.optional-dependencies]
42
+ full = ["diptest"]
43
+ dev = ["pytest", "pytest-cov"]
44
+
45
+ [tool.setuptools.packages.find]
46
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,3 @@
1
+ from clustrust.gui.app import main
2
+
3
+ main()
File without changes
@@ -0,0 +1,17 @@
1
+ """Do different algorithms find the same groups?"""
2
+ from itertools import combinations
3
+ import pandas as pd
4
+ from sklearn.metrics import adjusted_rand_score
5
+
6
+ from clustrust.core.algorithms import get_labels, ALGORITHMS, SEED
7
+
8
+
9
+ def agreement(X, k: int, algorithms=ALGORITHMS, seed: int = SEED) -> pd.DataFrame:
10
+ """Adjusted Rand index between every pair of algorithms at a given k.
11
+ Near 1 = same groups. Low = the groups depend on the method."""
12
+ algos = list(algorithms)
13
+ labels = {a: get_labels(a, X, k, seed) for a in algos}
14
+ M = pd.DataFrame(1.0, index=algos, columns=algos)
15
+ for a, b in combinations(algos, 2):
16
+ M.loc[a, b] = M.loc[b, a] = adjusted_rand_score(labels[a], labels[b])
17
+ return M
@@ -0,0 +1,19 @@
1
+ """Clustering algorithms behind one common function."""
2
+ import numpy as np
3
+ from sklearn.cluster import KMeans, AgglomerativeClustering
4
+ from sklearn.mixture import GaussianMixture
5
+
6
+ SEED = 42 # one global seed used for every random step
7
+
8
+ ALGORITHMS = ("kmeans", "agglomerative", "gmm")
9
+
10
+
11
+ def get_labels(name: str, X: np.ndarray, k: int, seed: int = SEED) -> np.ndarray:
12
+ """Run one algorithm with k clusters and return the group of each row."""
13
+ if name == "kmeans":
14
+ return KMeans(n_clusters=k, n_init=10, random_state=seed).fit_predict(X)
15
+ if name == "agglomerative":
16
+ return AgglomerativeClustering(n_clusters=k).fit_predict(X)
17
+ if name == "gmm":
18
+ return GaussianMixture(n_components=k, random_state=seed).fit(X).predict(X)
19
+ raise ValueError(f"Unknown algorithm: {name}")
@@ -0,0 +1,70 @@
1
+ """Judge every index against structureless null data."""
2
+ import numpy as np
3
+ import pandas as pd
4
+ from joblib import Parallel, delayed
5
+
6
+ from clustrust.core.algorithms import ALGORITHMS, SEED
7
+ from clustrust.core.runner import sweep
8
+ from clustrust.core.null import NULLS
9
+
10
+ INDEX_COLS = ["silhouette", "calinski_harabasz", "davies_bouldin"]
11
+
12
+
13
+ def _null_scores(X, null_name, child_seed, algorithms, k_range, seed):
14
+ rng = np.random.default_rng(child_seed)
15
+ return sweep(NULLS[null_name](X, rng), algorithms, k_range, seed)
16
+
17
+
18
+ def _z_table(real: pd.DataFrame, nulls: pd.DataFrame) -> pd.DataFrame:
19
+ keys = ["algorithm", "k"]
20
+ mean = nulls.groupby(keys)[INDEX_COLS].mean().add_suffix("_null_mean").reset_index()
21
+ std = nulls.groupby(keys)[INDEX_COLS].std().add_suffix("_null_std").reset_index()
22
+ out = real.merge(mean, on=keys).merge(std, on=keys)
23
+ for c in INDEX_COLS:
24
+ z = (out[c] - out[c + "_null_mean"]) / out[c + "_null_std"].replace(0, np.nan)
25
+ out[c + "_z"] = -z if c == "davies_bouldin" else z # flipped: higher is always better
26
+ return out
27
+
28
+
29
+ def calibrated_sweep(X, algorithms=ALGORITHMS, k_range=range(2, 9), n_null: int = 20,
30
+ seed: int = SEED, null: str = "gaussian", n_jobs: int = 1) -> pd.DataFrame:
31
+ """Real scores plus a z-score for each index against structureless null datasets.
32
+
33
+ null: 'gaussian', 'pca_uniform' or 'both'. With 'both', each z-score is the smaller of the
34
+ two, so a result must beat both nulls. (The *_null_mean and *_null_std columns then
35
+ describe the first null only.) n_jobs > 1 runs the null datasets in parallel.
36
+ """
37
+ names = ["gaussian", "pca_uniform"] if null == "both" else [null]
38
+ for n in names:
39
+ if n not in NULLS:
40
+ raise ValueError(f"Unknown null model: {n}")
41
+ real = sweep(X, algorithms, k_range, seed)
42
+ children = np.random.SeedSequence(seed).spawn(n_null) # same results for any n_jobs
43
+ out = None
44
+ for name in names:
45
+ runs = Parallel(n_jobs=n_jobs)(
46
+ delayed(_null_scores)(X, name, c, algorithms, k_range, seed) for c in children)
47
+ tab = _z_table(real, pd.concat(runs))
48
+ if out is None:
49
+ out = tab
50
+ else:
51
+ for c in INDEX_COLS:
52
+ out[c + "_z"] = np.minimum(out[c + "_z"], tab[c + "_z"])
53
+ return out
54
+
55
+
56
+ def verdict(cal: pd.DataFrame, threshold: float = 2.0) -> tuple[str, str]:
57
+ """Indices-only verdict from the calibrated table (older version, kept for now)."""
58
+ zcols = [c + "_z" for c in INDEX_COLS]
59
+ by_k = cal.groupby("k")[zcols].mean()
60
+ beating = by_k > threshold
61
+ if not beating.to_numpy().any():
62
+ return ("No evidence of clusters",
63
+ f"No index beats the null data (z > {threshold}) at any k.")
64
+ best = {c: int(by_k[c].idxmax()) for c in zcols if beating[c].any()}
65
+ if len(set(best.values())) == 1:
66
+ k = next(iter(best.values()))
67
+ return ("Clear structure", f"All indices that beat the null agree on k = {k}.")
68
+ return ("Weak or ambiguous structure",
69
+ "Indices beat the null but disagree on k: "
70
+ + ", ".join(f"{c[:-2]} -> {k}" for c, k in best.items()))
@@ -0,0 +1,51 @@
1
+ """Consensus clustering: combine many resampled clusterings into one."""
2
+ import numpy as np
3
+ from scipy.cluster.hierarchy import linkage, fcluster
4
+ from scipy.spatial.distance import squareform
5
+
6
+ from clustrust.core.algorithms import get_labels, SEED
7
+ from clustrust.core.defaults import value
8
+
9
+ def consensus(name: str, X: np.ndarray, k: int, n_rounds: int = 50,
10
+ frac: float = value("subsample_fraction"), seed: int = SEED) -> tuple[np.ndarray, np.ndarray]:
11
+ """Return (consensus labels, co-association matrix).
12
+
13
+ The matrix entry (i, j) is the fraction of resamples, among those that
14
+ contained both rows, in which rows i and j were put in the same group.
15
+ """
16
+ rng = np.random.default_rng(seed)
17
+ n = len(X)
18
+ together = np.zeros((n, n))
19
+ sampled = np.zeros((n, n))
20
+ for _ in range(n_rounds):
21
+ idx = rng.choice(n, size=int(frac * n), replace=False)
22
+ labels = get_labels(name, X[idx], k, seed)
23
+ same = (labels[:, None] == labels[None, :]).astype(float)
24
+ together[np.ix_(idx, idx)] += same
25
+ sampled[np.ix_(idx, idx)] += 1
26
+
27
+ C = np.divide(together, sampled, out=np.zeros_like(together), where=sampled > 0)
28
+ np.fill_diagonal(C, 1.0)
29
+
30
+ Z = linkage(squareform(1.0 - C, checks=False), method="average")
31
+ final = fcluster(Z, t=k, criterion="maxclust") - 1
32
+ return final, C
33
+
34
+ def pac(C: np.ndarray, lo: float = 0.1, hi: float = 0.9) -> float:
35
+ """Proportion of ambiguously clustered pairs: pairs whose co-association is
36
+ strictly between lo and hi. Lower means clearer structure."""
37
+ vals = C[np.triu_indices_from(C, k=1)]
38
+ return float(np.mean((vals > lo) & (vals < hi)))
39
+
40
+
41
+ def point_confidence(C: np.ndarray, labels: np.ndarray) -> np.ndarray:
42
+ """For each point, its average co-association with the other members of its own
43
+ consensus cluster (1 = always grouped with them). NaN for one-point clusters."""
44
+ conf = np.full(len(labels), np.nan)
45
+ for c in np.unique(labels):
46
+ members = np.where(labels == c)[0]
47
+ if len(members) < 2:
48
+ continue
49
+ sub = C[np.ix_(members, members)]
50
+ conf[members] = (sub.sum(axis=1) - 1.0) / (len(members) - 1) # drop the diagonal
51
+ return conf
@@ -0,0 +1,66 @@
1
+ """Default values for every adjustable parameter, and where each one comes from.
2
+
3
+ kind: 'literature' = published rule, or the default of a widely used package
4
+ 'convention' = common statistical convention, not specific to clustering
5
+ 'ours' = our own choice, declared as such in the paper
6
+ Every value can be changed by the user. 'note' holds the reasoning behind a choice.
7
+ """
8
+ DEFAULTS = {
9
+ "hopkins_tendency": {"value": 0.75, "kind": "literature",
10
+ "source": "Lawson & Jurs 1990 (H > 0.75: clustering tendency, 90% confidence)",
11
+ "note": "The 0.75 rule assumes a uniform baseline. On Gaussian noise H was 0.78, "
12
+ "so ClusTrust also requires H to beat structureless data with the same "
13
+ "means and correlations."},
14
+ "jaccard_dissolved": {"value": 0.50, "kind": "literature",
15
+ "source": "Hennig 2008; fpc clusterboot default"},
16
+ "jaccard_stable": {"value": 0.75, "kind": "literature",
17
+ "source": "Hennig 2007; fpc documentation"},
18
+ "stability_ari": {"value": 0.80, "kind": "literature",
19
+ "source": "Steinley 2004 'good' band, applied to agreement between resamples by analogy"},
20
+ "agreement_ari": {"value": 0.80, "kind": "literature",
21
+ "source": "Steinley 2004 'good' band, applied to agreement between algorithms by analogy"},
22
+ "pac_low": {"value": 0.10, "kind": "literature", "source": "Senbabaoglu et al. 2014"},
23
+ "pac_high": {"value": 0.90, "kind": "literature", "source": "Senbabaoglu et al. 2014"},
24
+ "pac_rule": {"value": "lowest", "kind": "literature",
25
+ "source": "Senbabaoglu et al. 2014: the k with the lowest PAC is preferred"},
26
+ "min_indices": {"value": 2, "kind": "literature",
27
+ "source": "Majority rule across indices, as in NbClust (Charrad et al. 2014; verify)"},
28
+ "n_rounds": {"value": 100, "kind": "literature",
29
+ "source": "Hennig 2007; fpc clusterboot default B = 100"},
30
+ "n_null": {"value": 100, "kind": "literature",
31
+ "source": "clusGap default B = 100 (Tibshirani, Walther & Hastie 2001)"},
32
+ "null_model": {"value": "both", "kind": "ours",
33
+ "source": "Gaussian null: Senbabaoglu et al. 2014, SigClust (Liu et al. 2008); "
34
+ "uniform-over-principal-components null: Tibshirani et al. 2001",
35
+ "note": "In a pilot the Gaussian null alone flagged uniform noise as structured, so by "
36
+ "default a result must beat both nulls."},
37
+ "z_cutoff": {"value": 2.0, "kind": "convention",
38
+ "source": "Two standard deviations; no clustering-specific value exists"},
39
+ "subsample_fraction": {
40
+ "value": 0.80, "kind": "literature",
41
+ "source": "Ben-Hur, Elisseeff & Guyon 2002 (fraction not much smaller than 1); "
42
+ "Wilkerson & Hayes 2010 (ConsensusClusterPlus default pItem = 0.8)",
43
+ "note": "We use 0.8 rather than the half-of-the-data default of fpc's optional subset scheme "
44
+ "(fpc's default scheme is the bootstrap). A larger fraction keeps more points of small "
45
+ "clusters in every resample, so they are less likely to be lost by chance; the cost is "
46
+ "that resamples overlap more, so stability values are somewhat higher.",
47
+ },"jaccard_unstable": {
48
+ "value": 0.60,
49
+ "kind": "literature",
50
+ "source": "Hennig 2008 / fpc & clustrd documentation: below 0.6 should not be trusted"
51
+ },
52
+ "jaccard_highly_stable": {
53
+ "value": 0.85,
54
+ "kind": "literature",
55
+ "source": "Hennig 2008 / fpc & clustrd documentation: 0.85 or more is highly stable"
56
+ },
57
+ }
58
+
59
+ PRESETS = {
60
+ "quick": {"n_rounds": 20, "n_null": 20, "null_model": "gaussian"},
61
+ "literature": {k: DEFAULTS[k]["value"] for k in ("n_rounds", "n_null", "null_model")},
62
+ }
63
+
64
+
65
+ def value(name: str):
66
+ return DEFAULTS[name]["value"]