GOTClust 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.
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.4
2
+ Name: GOTClust
3
+ Version: 0.1.0
4
+ Summary: Grassmann-Optimal-Transport Clustering for Single-Cell Data
5
+ Home-page: https://github.com/gotclust/gotclust
6
+ Author: GOTClust Developers
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/ZengFLab/gotclust
9
+ Project-URL: Documentation, https://github.com/ZengFLab/gotclust#readme
10
+ Project-URL: Repository, https://github.com/ZengFLab/gotclust
11
+ Project-URL: Issues, https://github.com/ZengFLab/gotclust/issues
12
+ Keywords: single-cell,clustering,grassmann-manifold,optimal-transport,single-cell-rna-seq,computational-biology
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
23
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
24
+ Classifier: Operating System :: OS Independent
25
+ Requires-Python: >=3.8
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: numpy>=1.20
29
+ Requires-Dist: scipy>=1.6
30
+ Requires-Dist: scikit-learn>=0.24
31
+ Requires-Dist: grassmann-ot>=0.3.0
32
+ Provides-Extra: gpu
33
+ Requires-Dist: torch>=1.9; extra == "gpu"
34
+ Provides-Extra: faiss
35
+ Requires-Dist: faiss-cpu>=1.7; extra == "faiss"
36
+ Provides-Extra: dev
37
+ Requires-Dist: pytest>=7.0; extra == "dev"
38
+ Requires-Dist: matplotlib>=3.3; extra == "dev"
39
+ Requires-Dist: seaborn>=0.11; extra == "dev"
40
+ Requires-Dist: scanpy>=1.8; extra == "dev"
41
+ Dynamic: license-file
42
+
43
+ # GOTClust
44
+
45
+ **Grassmann-Optimal-Transport Clustering for Single-Cell Data**
46
+
47
+ A subspace-aware clustering framework that represents each cell by a local
48
+ principal subspace (capturing local transcriptional regulatory structure),
49
+ then clusters these subspaces on the Grassmann manifold.
50
+
51
+ ---
52
+
53
+ ## Why GOTClust?
54
+
55
+ | Aspect | Vector-space methods (Leiden, KMeans) | GOTClust |
56
+ |---|---|---|
57
+ | Object being clustered | Cell vector (expression values) | Local **subspace** (covariance structure) |
58
+ | Distance | Euclidean / cosine | **Grassmann projection distance** |
59
+ | Rotations | Sensitive | **Invariant** |
60
+ | Batch robustness | Low | **High** (rotation-invariant) |
61
+ | Biological interpretation | "Cells look similar" | **"Regulatory programs look similar"** |
62
+
63
+ GOTClust provides two algorithms:
64
+
65
+ - **GSC** — Grassmann Spectral Clustering
66
+ - **GWC** — Grassmann Wasserstein Clustering (Frechet-mean barycenters)
67
+
68
+ ---
69
+
70
+ ## Installation
71
+
72
+ ```bash
73
+ pip install GOTClust
74
+ ```
75
+
76
+ With GPU acceleration (via the underlying `grassmann-ot` backends):
77
+
78
+ ```bash
79
+ pip install GOTClust[gpu]
80
+ ```
81
+
82
+ ---
83
+
84
+ ## Quick start
85
+
86
+ ```python
87
+ import numpy as np
88
+ from gotclust import grassmann_sc
89
+
90
+ # H: expression / composition matrix, shape (n_genes, n_cells)
91
+ H = np.random.randn(50, 300)
92
+
93
+ # ---- Grassmann Spectral Clustering (recommended) ----
94
+ labels, info = grassmann_sc(
95
+ H, n_clusters=4, method="spectral",
96
+ k=30, p=3, backend="pca", affinity="local", random_state=42,
97
+ )
98
+
99
+ # ---- Grassmann Wasserstein Clustering ----
100
+ labels, info = grassmann_sc(
101
+ H, n_clusters=4, method="wasserstein",
102
+ k=30, p=3, backend="pca", n_iter=50, init="kmeans++", random_state=42,
103
+ )
104
+ ```
105
+
106
+ ### Returned `info`
107
+
108
+ | Key | Shape | Description |
109
+ |---|---|---|
110
+ | `U_list` | `list[(r,p)]` | Per-cell Grassmann points |
111
+ | `C` | `(n,n)` | Pairwise Grassmann cost matrix |
112
+ | `affinity` | `(n,n)` | Affinity matrix (GSC only) |
113
+ | `centroids` | `list[(r,p)]` | Cluster barycenters (GWC only) |
114
+ | `inertia` | `list[float]` | Inertia history (GWC only) |
115
+
116
+ ---
117
+
118
+ ## Algorithm reference
119
+
120
+ ### `grassmann_sc(H, n_clusters, method, **kwargs)`
121
+
122
+ Unified entry point.
123
+
124
+ - `method="spectral"` → forwards to `grassmann_spectral_clustering`
125
+ - `method="wasserstein"` → forwards to `grassmann_wasserstein_clustering`
126
+
127
+ ### `grassmann_spectral_clustering(...)`
128
+
129
+ Pipeline:
130
+ 1. `cells_to_grassmann` → local subspaces `U_i`
131
+ 2. `grassmann_cost_matrix` → cost matrix `C`
132
+ 3. `grassmann_affinity` → affinity matrix `A` (Zelnik-Perona local scaling)
133
+ 4. `sklearn.SpectralClustering(affinity="precomputed")`
134
+
135
+ ### `grassmann_wasserstein_clustering(...)`
136
+
137
+ Lloyd-style alternating optimization:
138
+ - **E-step** — assign each cell to the nearest cluster center
139
+ (Grassmann projection distance)
140
+ - **M-step** — update each center to the Frechet mean of its members
141
+
142
+ ### `grassmann_frechet_mean(V_list, weights, p)`
143
+
144
+ Closed-form Grassmann barycenter: eigen-decomposition of
145
+ `Σ w_j V_j V_j^T`, take top-`p` eigenvectors.
146
+
147
+ ### `grassmann_affinity(C, method, sigma)`
148
+
149
+ Build an affinity matrix from a Grassmann cost matrix.
150
+ `method` ∈ `{"local", "global", "knn"}`.
151
+
152
+ ---
153
+
154
+ ## Parameters
155
+
156
+ | Parameter | Default | Meaning |
157
+ |---|---|---|
158
+ | `k` | 30 | Neighborhood size for local subspace construction |
159
+ | `p` | 3 | Subspace dimension |
160
+ | `backend` | `"pca"` | Subspace construction backend (`loop`/`pca`/`batched`/`faiss`/`subsampling`) |
161
+ | `affinity` | `"local"` | Affinity construction (`local`/`global`/`knn`) |
162
+ | `n_iter` | 50 | Lloyd iterations (GWC) |
163
+ | `init` | `"kmeans++"` | Centroid initialization (GWC) |
164
+
165
+ ---
166
+
167
+ ## Citation
168
+
169
+ *Coming soon.*
170
+
171
+ ---
172
+
173
+ ## License
174
+
175
+ MIT
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.cfg
5
+ setup.py
6
+ GOTClust.egg-info/PKG-INFO
7
+ GOTClust.egg-info/SOURCES.txt
8
+ GOTClust.egg-info/dependency_links.txt
9
+ GOTClust.egg-info/requires.txt
10
+ GOTClust.egg-info/top_level.txt
11
+ gotclust/__init__.py
12
+ gotclust/_version.py
13
+ gotclust/core.py
@@ -0,0 +1,16 @@
1
+ numpy>=1.20
2
+ scipy>=1.6
3
+ scikit-learn>=0.24
4
+ grassmann-ot>=0.3.0
5
+
6
+ [dev]
7
+ pytest>=7.0
8
+ matplotlib>=3.3
9
+ seaborn>=0.11
10
+ scanpy>=1.8
11
+
12
+ [faiss]
13
+ faiss-cpu>=1.7
14
+
15
+ [gpu]
16
+ torch>=1.9
@@ -0,0 +1 @@
1
+ gotclust
gotclust-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GOTClust Developers
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,175 @@
1
+ Metadata-Version: 2.4
2
+ Name: GOTClust
3
+ Version: 0.1.0
4
+ Summary: Grassmann-Optimal-Transport Clustering for Single-Cell Data
5
+ Home-page: https://github.com/gotclust/gotclust
6
+ Author: GOTClust Developers
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/ZengFLab/gotclust
9
+ Project-URL: Documentation, https://github.com/ZengFLab/gotclust#readme
10
+ Project-URL: Repository, https://github.com/ZengFLab/gotclust
11
+ Project-URL: Issues, https://github.com/ZengFLab/gotclust/issues
12
+ Keywords: single-cell,clustering,grassmann-manifold,optimal-transport,single-cell-rna-seq,computational-biology
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
23
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
24
+ Classifier: Operating System :: OS Independent
25
+ Requires-Python: >=3.8
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: numpy>=1.20
29
+ Requires-Dist: scipy>=1.6
30
+ Requires-Dist: scikit-learn>=0.24
31
+ Requires-Dist: grassmann-ot>=0.3.0
32
+ Provides-Extra: gpu
33
+ Requires-Dist: torch>=1.9; extra == "gpu"
34
+ Provides-Extra: faiss
35
+ Requires-Dist: faiss-cpu>=1.7; extra == "faiss"
36
+ Provides-Extra: dev
37
+ Requires-Dist: pytest>=7.0; extra == "dev"
38
+ Requires-Dist: matplotlib>=3.3; extra == "dev"
39
+ Requires-Dist: seaborn>=0.11; extra == "dev"
40
+ Requires-Dist: scanpy>=1.8; extra == "dev"
41
+ Dynamic: license-file
42
+
43
+ # GOTClust
44
+
45
+ **Grassmann-Optimal-Transport Clustering for Single-Cell Data**
46
+
47
+ A subspace-aware clustering framework that represents each cell by a local
48
+ principal subspace (capturing local transcriptional regulatory structure),
49
+ then clusters these subspaces on the Grassmann manifold.
50
+
51
+ ---
52
+
53
+ ## Why GOTClust?
54
+
55
+ | Aspect | Vector-space methods (Leiden, KMeans) | GOTClust |
56
+ |---|---|---|
57
+ | Object being clustered | Cell vector (expression values) | Local **subspace** (covariance structure) |
58
+ | Distance | Euclidean / cosine | **Grassmann projection distance** |
59
+ | Rotations | Sensitive | **Invariant** |
60
+ | Batch robustness | Low | **High** (rotation-invariant) |
61
+ | Biological interpretation | "Cells look similar" | **"Regulatory programs look similar"** |
62
+
63
+ GOTClust provides two algorithms:
64
+
65
+ - **GSC** — Grassmann Spectral Clustering
66
+ - **GWC** — Grassmann Wasserstein Clustering (Frechet-mean barycenters)
67
+
68
+ ---
69
+
70
+ ## Installation
71
+
72
+ ```bash
73
+ pip install GOTClust
74
+ ```
75
+
76
+ With GPU acceleration (via the underlying `grassmann-ot` backends):
77
+
78
+ ```bash
79
+ pip install GOTClust[gpu]
80
+ ```
81
+
82
+ ---
83
+
84
+ ## Quick start
85
+
86
+ ```python
87
+ import numpy as np
88
+ from gotclust import grassmann_sc
89
+
90
+ # H: expression / composition matrix, shape (n_genes, n_cells)
91
+ H = np.random.randn(50, 300)
92
+
93
+ # ---- Grassmann Spectral Clustering (recommended) ----
94
+ labels, info = grassmann_sc(
95
+ H, n_clusters=4, method="spectral",
96
+ k=30, p=3, backend="pca", affinity="local", random_state=42,
97
+ )
98
+
99
+ # ---- Grassmann Wasserstein Clustering ----
100
+ labels, info = grassmann_sc(
101
+ H, n_clusters=4, method="wasserstein",
102
+ k=30, p=3, backend="pca", n_iter=50, init="kmeans++", random_state=42,
103
+ )
104
+ ```
105
+
106
+ ### Returned `info`
107
+
108
+ | Key | Shape | Description |
109
+ |---|---|---|
110
+ | `U_list` | `list[(r,p)]` | Per-cell Grassmann points |
111
+ | `C` | `(n,n)` | Pairwise Grassmann cost matrix |
112
+ | `affinity` | `(n,n)` | Affinity matrix (GSC only) |
113
+ | `centroids` | `list[(r,p)]` | Cluster barycenters (GWC only) |
114
+ | `inertia` | `list[float]` | Inertia history (GWC only) |
115
+
116
+ ---
117
+
118
+ ## Algorithm reference
119
+
120
+ ### `grassmann_sc(H, n_clusters, method, **kwargs)`
121
+
122
+ Unified entry point.
123
+
124
+ - `method="spectral"` → forwards to `grassmann_spectral_clustering`
125
+ - `method="wasserstein"` → forwards to `grassmann_wasserstein_clustering`
126
+
127
+ ### `grassmann_spectral_clustering(...)`
128
+
129
+ Pipeline:
130
+ 1. `cells_to_grassmann` → local subspaces `U_i`
131
+ 2. `grassmann_cost_matrix` → cost matrix `C`
132
+ 3. `grassmann_affinity` → affinity matrix `A` (Zelnik-Perona local scaling)
133
+ 4. `sklearn.SpectralClustering(affinity="precomputed")`
134
+
135
+ ### `grassmann_wasserstein_clustering(...)`
136
+
137
+ Lloyd-style alternating optimization:
138
+ - **E-step** — assign each cell to the nearest cluster center
139
+ (Grassmann projection distance)
140
+ - **M-step** — update each center to the Frechet mean of its members
141
+
142
+ ### `grassmann_frechet_mean(V_list, weights, p)`
143
+
144
+ Closed-form Grassmann barycenter: eigen-decomposition of
145
+ `Σ w_j V_j V_j^T`, take top-`p` eigenvectors.
146
+
147
+ ### `grassmann_affinity(C, method, sigma)`
148
+
149
+ Build an affinity matrix from a Grassmann cost matrix.
150
+ `method` ∈ `{"local", "global", "knn"}`.
151
+
152
+ ---
153
+
154
+ ## Parameters
155
+
156
+ | Parameter | Default | Meaning |
157
+ |---|---|---|
158
+ | `k` | 30 | Neighborhood size for local subspace construction |
159
+ | `p` | 3 | Subspace dimension |
160
+ | `backend` | `"pca"` | Subspace construction backend (`loop`/`pca`/`batched`/`faiss`/`subsampling`) |
161
+ | `affinity` | `"local"` | Affinity construction (`local`/`global`/`knn`) |
162
+ | `n_iter` | 50 | Lloyd iterations (GWC) |
163
+ | `init` | `"kmeans++"` | Centroid initialization (GWC) |
164
+
165
+ ---
166
+
167
+ ## Citation
168
+
169
+ *Coming soon.*
170
+
171
+ ---
172
+
173
+ ## License
174
+
175
+ MIT
@@ -0,0 +1,133 @@
1
+ # GOTClust
2
+
3
+ **Grassmann-Optimal-Transport Clustering for Single-Cell Data**
4
+
5
+ A subspace-aware clustering framework that represents each cell by a local
6
+ principal subspace (capturing local transcriptional regulatory structure),
7
+ then clusters these subspaces on the Grassmann manifold.
8
+
9
+ ---
10
+
11
+ ## Why GOTClust?
12
+
13
+ | Aspect | Vector-space methods (Leiden, KMeans) | GOTClust |
14
+ |---|---|---|
15
+ | Object being clustered | Cell vector (expression values) | Local **subspace** (covariance structure) |
16
+ | Distance | Euclidean / cosine | **Grassmann projection distance** |
17
+ | Rotations | Sensitive | **Invariant** |
18
+ | Batch robustness | Low | **High** (rotation-invariant) |
19
+ | Biological interpretation | "Cells look similar" | **"Regulatory programs look similar"** |
20
+
21
+ GOTClust provides two algorithms:
22
+
23
+ - **GSC** — Grassmann Spectral Clustering
24
+ - **GWC** — Grassmann Wasserstein Clustering (Frechet-mean barycenters)
25
+
26
+ ---
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install GOTClust
32
+ ```
33
+
34
+ With GPU acceleration (via the underlying `grassmann-ot` backends):
35
+
36
+ ```bash
37
+ pip install GOTClust[gpu]
38
+ ```
39
+
40
+ ---
41
+
42
+ ## Quick start
43
+
44
+ ```python
45
+ import numpy as np
46
+ from gotclust import grassmann_sc
47
+
48
+ # H: expression / composition matrix, shape (n_genes, n_cells)
49
+ H = np.random.randn(50, 300)
50
+
51
+ # ---- Grassmann Spectral Clustering (recommended) ----
52
+ labels, info = grassmann_sc(
53
+ H, n_clusters=4, method="spectral",
54
+ k=30, p=3, backend="pca", affinity="local", random_state=42,
55
+ )
56
+
57
+ # ---- Grassmann Wasserstein Clustering ----
58
+ labels, info = grassmann_sc(
59
+ H, n_clusters=4, method="wasserstein",
60
+ k=30, p=3, backend="pca", n_iter=50, init="kmeans++", random_state=42,
61
+ )
62
+ ```
63
+
64
+ ### Returned `info`
65
+
66
+ | Key | Shape | Description |
67
+ |---|---|---|
68
+ | `U_list` | `list[(r,p)]` | Per-cell Grassmann points |
69
+ | `C` | `(n,n)` | Pairwise Grassmann cost matrix |
70
+ | `affinity` | `(n,n)` | Affinity matrix (GSC only) |
71
+ | `centroids` | `list[(r,p)]` | Cluster barycenters (GWC only) |
72
+ | `inertia` | `list[float]` | Inertia history (GWC only) |
73
+
74
+ ---
75
+
76
+ ## Algorithm reference
77
+
78
+ ### `grassmann_sc(H, n_clusters, method, **kwargs)`
79
+
80
+ Unified entry point.
81
+
82
+ - `method="spectral"` → forwards to `grassmann_spectral_clustering`
83
+ - `method="wasserstein"` → forwards to `grassmann_wasserstein_clustering`
84
+
85
+ ### `grassmann_spectral_clustering(...)`
86
+
87
+ Pipeline:
88
+ 1. `cells_to_grassmann` → local subspaces `U_i`
89
+ 2. `grassmann_cost_matrix` → cost matrix `C`
90
+ 3. `grassmann_affinity` → affinity matrix `A` (Zelnik-Perona local scaling)
91
+ 4. `sklearn.SpectralClustering(affinity="precomputed")`
92
+
93
+ ### `grassmann_wasserstein_clustering(...)`
94
+
95
+ Lloyd-style alternating optimization:
96
+ - **E-step** — assign each cell to the nearest cluster center
97
+ (Grassmann projection distance)
98
+ - **M-step** — update each center to the Frechet mean of its members
99
+
100
+ ### `grassmann_frechet_mean(V_list, weights, p)`
101
+
102
+ Closed-form Grassmann barycenter: eigen-decomposition of
103
+ `Σ w_j V_j V_j^T`, take top-`p` eigenvectors.
104
+
105
+ ### `grassmann_affinity(C, method, sigma)`
106
+
107
+ Build an affinity matrix from a Grassmann cost matrix.
108
+ `method` ∈ `{"local", "global", "knn"}`.
109
+
110
+ ---
111
+
112
+ ## Parameters
113
+
114
+ | Parameter | Default | Meaning |
115
+ |---|---|---|
116
+ | `k` | 30 | Neighborhood size for local subspace construction |
117
+ | `p` | 3 | Subspace dimension |
118
+ | `backend` | `"pca"` | Subspace construction backend (`loop`/`pca`/`batched`/`faiss`/`subsampling`) |
119
+ | `affinity` | `"local"` | Affinity construction (`local`/`global`/`knn`) |
120
+ | `n_iter` | 50 | Lloyd iterations (GWC) |
121
+ | `init` | `"kmeans++"` | Centroid initialization (GWC) |
122
+
123
+ ---
124
+
125
+ ## Citation
126
+
127
+ *Coming soon.*
128
+
129
+ ---
130
+
131
+ ## License
132
+
133
+ MIT
@@ -0,0 +1,38 @@
1
+ """
2
+ GOTClust: Grassmann-Optimal-Transport Clustering for Single-Cell Data.
3
+
4
+ A subspace-aware clustering framework that represents each cell by a local
5
+ principal subspace (capturing local transcriptional regulatory structure),
6
+ then clusters these subspaces on the Grassmann manifold.
7
+
8
+ Two algorithms are provided:
9
+
10
+ * GSC - Grassmann Spectral Clustering
11
+ * GWC - Grassmann Wasserstein Clustering (Frechet-mean barycenters)
12
+
13
+ Key properties versus vector-space methods (Leiden, KMeans):
14
+ - The object being clustered is a SUBSPACE, not a vector.
15
+ - The distance is rotation-invariant (Grassmann projection distance).
16
+ - The framework is naturally robust to batch-induced rotations.
17
+
18
+ Dependencies: grassmann-ot, numpy, scipy, scikit-learn, torch (optional).
19
+ """
20
+
21
+ from ._version import __version__
22
+
23
+ from .core import (
24
+ grassmann_frechet_mean,
25
+ grassmann_affinity,
26
+ grassmann_spectral_clustering,
27
+ grassmann_wasserstein_clustering,
28
+ grassmann_sc,
29
+ )
30
+
31
+ __all__ = [
32
+ "__version__",
33
+ "grassmann_frechet_mean",
34
+ "grassmann_affinity",
35
+ "grassmann_spectral_clustering",
36
+ "grassmann_wasserstein_clustering",
37
+ "grassmann_sc",
38
+ ]
@@ -0,0 +1,3 @@
1
+ """GOTClust version."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,356 @@
1
+ """
2
+ Core Grassmann-SC algorithms.
3
+
4
+ This module contains the two clustering algorithms of GOTClust:
5
+
6
+ (a) Grassmann Spectral Clustering (GSC)
7
+ U_i -> Grassmann cost matrix C -> affinity A -> SpectralClustering
8
+ Uses local-scale Gaussian affinity (Zelnik-Perona rule), robust to
9
+ the non-Euclidean geometry of the Grassmann manifold.
10
+
11
+ (b) Grassmann Wasserstein Clustering (GWC)
12
+ K-means style on Grassmann, with cluster centers being Frechet means
13
+ (barycenters) and assignment by projection distance.
14
+
15
+ Plus the shared primitives:
16
+ - grassmann_frechet_mean : Grassmann barycenter (closed form)
17
+ - grassmann_affinity : cost matrix -> affinity matrix
18
+ """
19
+
20
+ import numpy as np
21
+ from scipy.linalg import eigh
22
+
23
+ from grassmann_ot import cells_to_grassmann, grassmann_cost_matrix
24
+
25
+
26
+ # ============================================================
27
+ # Grassmann Frechet Mean (barycenter)
28
+ # ============================================================
29
+ def grassmann_frechet_mean(V_list, weights, p):
30
+ """
31
+ Weighted Frechet mean on the Grassmann manifold.
32
+
33
+ Given subspaces V_j in St(r, p) with weights w_j,
34
+ find the barycenter W* minimizing:
35
+ sum_j w_j * ||W W^T - V_j V_j^T||_F^2
36
+
37
+ Closed form: eigen-decomposition of sum_j w_j V_j V_j^T,
38
+ take top-p eigenvectors.
39
+
40
+ Parameters
41
+ ----------
42
+ V_list : list of ndarray, each (r, p)
43
+ weights : ndarray, shape (len(V_list),), non-negative, sum to 1
44
+ p : int, subspace dimension
45
+
46
+ Returns
47
+ -------
48
+ W : ndarray, shape (r, p), column-orthonormal
49
+ """
50
+ r = V_list[0].shape[0]
51
+ G = np.zeros((r, r), dtype=np.float64)
52
+ for Vj, wj in zip(V_list, weights):
53
+ G += wj * (Vj @ Vj.T)
54
+ eigvals, eigvecs = eigh(G)
55
+ order = np.argsort(eigvals)[::-1]
56
+ W = eigvecs[:, order[:p]]
57
+ return W.astype(np.float64)
58
+
59
+
60
+ # ============================================================
61
+ # Affinity matrix construction
62
+ # ============================================================
63
+ def grassmann_affinity(C, method="local", sigma=None):
64
+ """
65
+ Build an affinity matrix from a Grassmann cost matrix.
66
+
67
+ Parameters
68
+ ----------
69
+ C : ndarray, shape (n, n)
70
+ Pairwise Grassmann cost (C[i,j] = p - ||U_i^T U_j||_F^2).
71
+ Smaller = more similar.
72
+ method : str
73
+ 'local' : Zelnik-Perona local scaling (recommended)
74
+ 'global' : single global Gaussian bandwidth
75
+ 'knn' : kNN mutual graph (binary/row-normalized)
76
+ sigma : float or None
77
+ Global bandwidth. Ignored for method='local'.
78
+ For 'knn', used as the number of neighbors (int).
79
+
80
+ Returns
81
+ -------
82
+ A : ndarray, shape (n, n), symmetric, non-negative
83
+ """
84
+ n = C.shape[0]
85
+
86
+ if method == "local":
87
+ # Zelnik-Perona: sigma_ij = sigma_i * sigma_j
88
+ # sigma_i = median of distances from point i
89
+ sigma_i = np.array([np.median(C[i, C[i] > 1e-12])
90
+ if np.any(C[i] > 1e-12) else 1.0
91
+ for i in range(n)])
92
+ # A_ij = exp( - C_ij^2 / (sigma_i * sigma_j) )
93
+ A = np.zeros_like(C)
94
+ for i in range(n):
95
+ A[i] = np.exp(-(C[i] ** 2) / (sigma_i[i] * sigma_i + 1e-12))
96
+ A = (A + A.T) / 2.0
97
+ return A
98
+
99
+ elif method == "global":
100
+ if sigma is None:
101
+ sigma = np.median(C[C > 0]) if np.any(C > 0) else 1.0
102
+ A = np.exp(-(C ** 2) / (sigma ** 2))
103
+ return (A + A.T) / 2.0
104
+
105
+ elif method == "knn":
106
+ k = int(sigma) if sigma is not None else 15
107
+ k = min(k, n - 1)
108
+ # row-wise kNN
109
+ A = np.zeros_like(C)
110
+ for i in range(n):
111
+ idx = np.argsort(C[i])[1:k + 1] # exclude self
112
+ A[i, idx] = 1.0
113
+ # symmetrize (mutual kNN)
114
+ A = (A + A.T > 0).astype(np.float64)
115
+ np.fill_diagonal(A, 1.0)
116
+ return A
117
+
118
+ else:
119
+ raise ValueError(f"Unknown affinity method: {method!r}")
120
+
121
+
122
+ # ============================================================
123
+ # (a) Grassmann Spectral Clustering
124
+ # ============================================================
125
+ def grassmann_spectral_clustering(H, n_clusters, k=30, p=3, backend="pca",
126
+ affinity="local", sigma=None,
127
+ random_state=42, n_neighbors_graph=15,
128
+ verbose=True, **sklearn_kwargs):
129
+ """
130
+ Grassmann Spectral Clustering (GSC).
131
+
132
+ Pipeline:
133
+ 1) cells_to_grassmann(H) -> list of local subspaces U_i in St(r,p)
134
+ 2) grassmann_cost_matrix(U) -> C (n,n)
135
+ 3) grassmann_affinity(C) -> A
136
+ 4) sklearn SpectralClustering(affinity='precomputed')
137
+
138
+ Parameters
139
+ ----------
140
+ H : ndarray, shape (r, n_cells)
141
+ Expression / composition matrix (one cell per column).
142
+ n_clusters : int
143
+ Number of clusters.
144
+ k : int
145
+ Neighborhood size for local subspace construction.
146
+ p : int
147
+ Subspace dimension.
148
+ backend : str
149
+ Backend for cells_to_grassmann
150
+ (loop/pca/batched/faiss/subsampling).
151
+ affinity : str
152
+ Affinity construction method (local/global/knn).
153
+ sigma : float or None
154
+ Parameter for affinity.
155
+ random_state : int
156
+ verbose : bool
157
+ Print progress messages.
158
+ sklearn_kwargs : dict
159
+ Extra kwargs forwarded to sklearn SpectralClustering.
160
+
161
+ Returns
162
+ -------
163
+ labels : ndarray, shape (n_cells,)
164
+ info : dict with keys
165
+ 'U_list' : list of (r,p) subspaces
166
+ 'C' : (n,n) cost matrix
167
+ 'affinity' : (n,n) affinity matrix
168
+ """
169
+ from sklearn.cluster import SpectralClustering
170
+
171
+ if verbose:
172
+ print(f"[GSC] Step 1/4: constructing Grassmann points "
173
+ f"(backend={backend}, k={k}, p={p})")
174
+ U_list = cells_to_grassmann(H, k=k, p=p, backend=backend, metric="cosine")
175
+ n = len(U_list)
176
+ r = U_list[0].shape[0]
177
+ if verbose:
178
+ print(f" n={n}, r={r}, p={p}, subspaces shape={U_list[0].shape}")
179
+
180
+ if verbose:
181
+ print("[GSC] Step 2/4: computing Grassmann cost matrix C")
182
+ C = grassmann_cost_matrix(U_list, p=p)
183
+ if verbose:
184
+ print(f" C range=[{C.min():.4f}, {C.max():.4f}], "
185
+ f"median={np.median(C):.4f}")
186
+
187
+ if verbose:
188
+ print(f"[GSC] Step 3/4: building affinity matrix (method={affinity})")
189
+ A = grassmann_affinity(C, method=affinity, sigma=sigma)
190
+
191
+ A = (A + A.T) / 2.0
192
+ np.fill_diagonal(A, 1.0)
193
+
194
+ if verbose:
195
+ print(f"[GSC] Step 4/4: SpectralClustering(n_clusters={n_clusters})")
196
+ sc = SpectralClustering(
197
+ n_clusters=n_clusters,
198
+ affinity="precomputed",
199
+ random_state=random_state,
200
+ **sklearn_kwargs
201
+ )
202
+ labels = sc.fit_predict(A)
203
+ if verbose:
204
+ print(f" cluster sizes: "
205
+ f"{np.bincount(labels, minlength=n_clusters)}")
206
+
207
+ info = {"U_list": U_list, "C": C, "affinity": A}
208
+ return labels, info
209
+
210
+
211
+ # ============================================================
212
+ # (b) Grassmann Wasserstein Clustering
213
+ # ============================================================
214
+ def grassmann_wasserstein_clustering(H, n_clusters, k=30, p=3, backend="pca",
215
+ n_iter=50, init="kmeans++",
216
+ random_state=42, verbose=True):
217
+ """
218
+ Grassmann Wasserstein Clustering (GWC).
219
+
220
+ Lloyd-style alternating optimization:
221
+ E-step: assign each cell to the nearest cluster center
222
+ (by Grassmann projection distance).
223
+ M-step: update each center to the Frechet mean of its members.
224
+
225
+ The "Wasserstein" name reflects the use of the Grassmann
226
+ geodesic/projection metric and Frechet barycenters, analogous
227
+ to Wasserstein barycentric updates.
228
+
229
+ Parameters
230
+ ----------
231
+ H : ndarray, shape (r, n_cells)
232
+ n_clusters : int
233
+ k, p, backend : subspace construction params
234
+ n_iter : int
235
+ Number of Lloyd iterations.
236
+ init : str
237
+ 'random' : randomly pick n_clusters cells as seeds
238
+ 'kmeans++' : kmeans++ style seeding on Grassmann distances
239
+ verbose : bool
240
+ Print progress messages.
241
+
242
+ Returns
243
+ -------
244
+ labels : ndarray, shape (n_cells,)
245
+ centroids : list of ndarray, each (r, p)
246
+ info : dict with U_list, C, inertia history
247
+ """
248
+ rng = np.random.RandomState(random_state)
249
+
250
+ if verbose:
251
+ print(f"[GWC] Step 1/4: constructing Grassmann points "
252
+ f"(backend={backend}, k={k}, p={p})")
253
+ U_list = cells_to_grassmann(H, k=k, p=p, backend=backend, metric="cosine")
254
+ n = len(U_list)
255
+ r = U_list[0].shape[0]
256
+ if verbose:
257
+ print(f" n={n}, r={r}, p={p}")
258
+
259
+ # ---- initialization ----
260
+ if verbose:
261
+ print(f"[GWC] Step 2/4: initializing {n_clusters} centroids ({init})")
262
+ if init == "random":
263
+ seeds = rng.choice(n, size=n_clusters, replace=False)
264
+ centroids = [U_list[s].copy() for s in seeds]
265
+ elif init == "kmeans++":
266
+ seeds = [rng.randint(0, n)]
267
+ centroids = [U_list[seeds[0]].copy()]
268
+ dist_sq = np.full(n, np.inf)
269
+ for _ in range(1, n_clusters):
270
+ for i in range(n):
271
+ # distance to closest existing center
272
+ d = min(p - np.sum((U_list[i].T @ centroids[c]) ** 2)
273
+ for c in range(len(centroids)))
274
+ dist_sq[i] = min(dist_sq[i], d)
275
+ probs = np.clip(dist_sq, 0, None)
276
+ probs = probs / (probs.sum() + 1e-12)
277
+ nxt = int(rng.choice(n, p=probs))
278
+ seeds.append(nxt)
279
+ centroids.append(U_list[nxt].copy())
280
+ else:
281
+ raise ValueError(f"Unknown init: {init!r}")
282
+
283
+ # ---- Lloyd iterations ----
284
+ if verbose:
285
+ print(f"[GWC] Step 3/4: Lloyd iterations (n_iter={n_iter})")
286
+ labels = np.zeros(n, dtype=int)
287
+ inertia_hist = []
288
+
289
+ for it in range(n_iter):
290
+ # E-step
291
+ for i in range(n):
292
+ best_c, best_d = -1, np.inf
293
+ for c in range(n_clusters):
294
+ prod = U_list[i].T @ centroids[c]
295
+ d = p - float(np.sum(prod ** 2)) # Grassmann distance
296
+ if d < best_d:
297
+ best_d, best_c = d, c
298
+ labels[i] = best_c
299
+
300
+ # M-step
301
+ for c in range(n_clusters):
302
+ idx_c = np.where(labels == c)[0]
303
+ if len(idx_c) == 0:
304
+ # empty cluster: reinitialize to a random cell
305
+ centroids[c] = U_list[rng.randint(0, n)].copy()
306
+ continue
307
+ w = np.ones(len(idx_c)) / len(idx_c)
308
+ centroids[c] = grassmann_frechet_mean(
309
+ [U_list[i] for i in idx_c], w, p)
310
+
311
+ inertia = 0.0
312
+ for i in range(n):
313
+ prod = U_list[i].T @ centroids[labels[i]]
314
+ inertia += p - float(np.sum(prod ** 2))
315
+ inertia_hist.append(inertia)
316
+ if verbose and (it % 10 == 0 or it == n_iter - 1):
317
+ sizes = np.bincount(labels, minlength=n_clusters)
318
+ print(f" iter {it+1:3d}: inertia={inertia:.2f}, "
319
+ f"sizes={sizes.tolist()}")
320
+
321
+ info = {"U_list": U_list, "centroids": centroids,
322
+ "inertia": inertia_hist}
323
+ return labels, centroids, info
324
+
325
+
326
+ # ============================================================
327
+ # Unified entry point
328
+ # ============================================================
329
+ def grassmann_sc(H, n_clusters, method="spectral", verbose=True, **kwargs):
330
+ """
331
+ Unified interface for Grassmann-SC.
332
+
333
+ Parameters
334
+ ----------
335
+ H : ndarray, shape (r, n_cells)
336
+ n_clusters : int
337
+ method : 'spectral' or 'wasserstein'
338
+ verbose : bool
339
+ Print progress messages.
340
+ **kwargs : forwarded to the chosen method
341
+
342
+ Returns
343
+ -------
344
+ labels : ndarray
345
+ info : dict
346
+ """
347
+ if method == "spectral":
348
+ return grassmann_spectral_clustering(
349
+ H, n_clusters, verbose=verbose, **kwargs)
350
+ elif method == "wasserstein":
351
+ labels, centroids, info = grassmann_wasserstein_clustering(
352
+ H, n_clusters, verbose=verbose, **kwargs)
353
+ return labels, info
354
+ else:
355
+ raise ValueError(f"Unknown method: {method!r}. "
356
+ f"Choose 'spectral' or 'wasserstein'.")
@@ -0,0 +1,67 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "GOTClust"
7
+ version = "0.1.0"
8
+ description = "Grassmann-Optimal-Transport Clustering for Single-Cell Data"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = {text = "MIT"}
12
+ authors = [
13
+ {name = "GOTClust Developers"}
14
+ ]
15
+ keywords = [
16
+ "single-cell",
17
+ "clustering",
18
+ "grassmann-manifold",
19
+ "optimal-transport",
20
+ "single-cell-rna-seq",
21
+ "computational-biology",
22
+ ]
23
+ classifiers = [
24
+ "Development Status :: 4 - Beta",
25
+ "Intended Audience :: Science/Research",
26
+ "Intended Audience :: Developers",
27
+ "License :: OSI Approved :: MIT License",
28
+ "Programming Language :: Python :: 3",
29
+ "Programming Language :: Python :: 3.8",
30
+ "Programming Language :: Python :: 3.9",
31
+ "Programming Language :: Python :: 3.10",
32
+ "Programming Language :: Python :: 3.11",
33
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
34
+ "Topic :: Scientific/Engineering :: Mathematics",
35
+ "Operating System :: OS Independent",
36
+ ]
37
+
38
+ dependencies = [
39
+ "numpy>=1.20",
40
+ "scipy>=1.6",
41
+ "scikit-learn>=0.24",
42
+ "grassmann-ot>=0.3.0",
43
+ ]
44
+
45
+ [project.optional-dependencies]
46
+ gpu = [
47
+ "torch>=1.9",
48
+ ]
49
+ faiss = [
50
+ "faiss-cpu>=1.7",
51
+ ]
52
+ dev = [
53
+ "pytest>=7.0",
54
+ "matplotlib>=3.3",
55
+ "seaborn>=0.11",
56
+ "scanpy>=1.8",
57
+ ]
58
+
59
+ [project.urls]
60
+ Homepage = "https://github.com/ZengFLab/gotclust"
61
+ Documentation = "https://github.com/ZengFLab/gotclust#readme"
62
+ Repository = "https://github.com/ZengFLab/gotclust"
63
+ Issues = "https://github.com/ZengFLab/gotclust/issues"
64
+
65
+ [tool.setuptools.packages.find]
66
+ include = ["gotclust*"]
67
+ exclude = ["tests*", "examples*"]
@@ -0,0 +1,56 @@
1
+ [metadata]
2
+ name = GOTClust
3
+ version = 0.1.0
4
+ description = Grassmann-Optimal-Transport Clustering for Single-Cell Data
5
+ long_description = file: README.md
6
+ long_description_content_type = text/markdown
7
+ author = GOTClust Developers
8
+ license = MIT
9
+ url = https://github.com/gotclust/gotclust
10
+ project_urls =
11
+ Documentation = https://github.com/gotclust/gotclust#readme
12
+ Repository = https://github.com/gotclust/gotclust
13
+ Issues = https://github.com/gotclust/gotclust/issues
14
+ classifiers =
15
+ Development Status :: 4 - Beta
16
+ Intended Audience :: Science/Research
17
+ Intended Audience :: Developers
18
+ License :: OSI Approved :: MIT License
19
+ Programming Language :: Python :: 3
20
+ Programming Language :: Python :: 3.8
21
+ Programming Language :: Python :: 3.9
22
+ Programming Language :: Python :: 3.10
23
+ Programming Language :: Python :: 3.11
24
+ Topic :: Scientific/Engineering :: Bio-Informatics
25
+ Topic :: Scientific/Engineering :: Mathematics
26
+ Operating System :: OS Independent
27
+
28
+ [options]
29
+ packages = find:
30
+ install_requires =
31
+ numpy>=1.20
32
+ scipy>=1.6
33
+ scikit-learn>=0.24
34
+ grassmann-ot>=0.3.0
35
+ python_requires = >=3.8
36
+
37
+ [options.extras_require]
38
+ gpu =
39
+ torch>=1.9
40
+ faiss =
41
+ faiss-cpu>=1.7
42
+ dev =
43
+ pytest>=7.0
44
+ matplotlib>=3.3
45
+ seaborn>=0.11
46
+ scanpy>=1.8
47
+
48
+ [options.packages.find]
49
+ exclude =
50
+ tests
51
+ examples
52
+
53
+ [egg_info]
54
+ tag_build =
55
+ tag_date = 0
56
+
@@ -0,0 +1,13 @@
1
+ """Setup script for GOTClust.
2
+
3
+ This file exists to provide a build fallback for environments whose
4
+ setuptools version does not fully support PEP 621 metadata in
5
+ pyproject.toml. It simply defers to pyproject.toml / setup.cfg via
6
+ setuptools.
7
+ """
8
+
9
+ from setuptools import setup, find_packages
10
+
11
+ setup(
12
+ packages=find_packages(exclude=["tests", "examples"]),
13
+ )