Metadata-Version: 2.4
Name: GOTClust
Version: 0.5.0
Summary: Grassmann-Optimal-Transport Clustering for Single-Cell Data
Home-page: https://github.com/gotclust/gotclust
Author: GOTClust Developers
License: MIT
Project-URL: Homepage, https://github.com/ZengFLab/gotclust
Project-URL: Documentation, https://github.com/ZengFLab/gotclust#readme
Project-URL: Repository, https://github.com/ZengFLab/gotclust
Project-URL: Issues, https://github.com/ZengFLab/gotclust/issues
Keywords: single-cell,clustering,grassmann-manifold,optimal-transport,single-cell-rna-seq,computational-biology
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.20
Requires-Dist: scipy>=1.6
Requires-Dist: scikit-learn>=0.24
Requires-Dist: grassmann-ot>=0.3.0
Provides-Extra: gpu
Requires-Dist: torch>=1.9; extra == "gpu"
Provides-Extra: faiss
Requires-Dist: faiss-cpu>=1.7; extra == "faiss"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: matplotlib>=3.3; extra == "dev"
Requires-Dist: seaborn>=0.11; extra == "dev"
Requires-Dist: scanpy>=1.8; extra == "dev"
Dynamic: license-file

# GOTClust

**Grassmann-Optimal-Transport Clustering for Single-Cell Data**

A subspace-aware clustering framework that represents each cell by a local
principal subspace (capturing local transcriptional regulatory structure),
then clusters these subspaces on the Grassmann manifold.

---

## Why GOTClust?

| Aspect | Vector-space methods (Leiden, KMeans) | GOTClust |
|---|---|---|
| Object being clustered | Cell vector (expression values) | Local **subspace** (covariance structure) |
| Distance | Euclidean / cosine | **Grassmann projection distance** |
| Rotations | Sensitive | **Invariant** |
| Batch robustness | Low | **High** (rotation-invariant) |
| Biological interpretation | "Cells look similar" | **"Regulatory programs look similar"** |
| Cluster count | Usually must be supplied | **Can be estimated automatically** |

GOTClust provides three algorithms:

- **GSC** — Grassmann Spectral Clustering
- **GWC** — Grassmann Wasserstein Clustering (Frechet-mean barycenters)
- **`estimate_n_clusters`** — automatic selection of the number of
  clusters (eigengap / Gap / jump / stability criteria)
- **`gotclust_embed`** — low-dimensional visualization that is aligned
  with the GWC result (soft-assignment, barycentric, or Grassmann-MDS /
  t-SNE)

---

## Installation

```bash
pip install GOTClust
```

With GPU acceleration (via the underlying `grassmann-ot` backends):

```bash
pip install GOTClust[gpu]
```

---

## Quick start

```python
import numpy as np
from gotclust import gotclust

# H: expression / composition matrix, shape (n_genes, n_cells)
H = np.random.randn(50, 300)

# ---- auto K, GWC (default) ----
labels, info = gotclust(H, p=3, k=30)

# ---- Grassmann Wasserstein Clustering (explicit) ----
labels, info = gotclust(
    H, n_clusters=4, method="wasserstein",
    k=30, p=3, backend="pca", n_iter=50, init="kmeans++", random_state=42,
)

# ---- Grassmann Spectral Clustering ----
labels, info = gotclust(
    H, n_clusters=4, method="spectral",
    k=30, p=3, backend="pca", affinity="local", random_state=42,
)

# ---- Embedding aligned with GWC (reuses the clustering run) ----
Z_soft, e_info = gotclust_embed(H, n_components=2)              # default
Z_bc,  _       = gotclust_embed(H, mode="barycentric")
Z_mds, _       = gotclust_embed(H, method="mds")
Z_tsne, _      = gotclust_embed(H, method="tsne", perplexity=30)
```

### Returned `info`

| Key | Shape | Description |
|---|---|---|
| `U_list` | `list[(r,p)]` | Per-cell Grassmann points |
| `C` | `(n,n)` | Pairwise Grassmann cost matrix |
| `affinity` | `(n,n)` | Affinity matrix (GSC only) |
| `centroids` | `list[(r,p)]` | Cluster barycenters (GWC only) |
| `inertia` | `list[float]` | Inertia history (GWC only) |
| `n_clusters_estimate` | `dict` | Full estimator output when `n_clusters='auto'` |

---

## Automatic cluster-number selection

If `n_clusters` is omitted or set to `"auto"`, GOTClust estimates the
number of clusters automatically. A **single** Grassmann cost matrix and
affinity graph are built once and reused for every candidate value of
`K`, so the overhead is dominated by the subspace construction step.

```python
from gotclust import gotclust, estimate_n_clusters

# auto-select (default: eigengap criterion)
labels, info = gotclust(H, n_clusters="auto", p=3, k=30)

# full control over the estimator
est = estimate_n_clusters(
    H, k=30, p=3, backend="pca",
    method="eigengap",          # eigengap | gap | jump | stability
    search_range=(2, 12),       # candidate K values
    criterion="max",            # max score / first_peak (gap)
    n_ref=5,                    # reference samples for the Gap statistic
    affinity_method="local",
    verbose=True,
)
print(est["n_clusters"], est["scores"])
# pass estimator options through the unified interface:
labels, info = gotclust(
    H, n_clusters=None,
    estimate_kwargs=dict(method="gap", search_range=(2, 10), n_ref=8),
)
```

### Which criterion should I use?

| Criterion | Reference | Best for | Cost |
|---|---|---|---|
| `eigengap` (default) | None | Well-separated components; the standard spectral choice | Lowest |
| `gap` | Uniform reference distribution | General-purpose, reference-based | Medium (GWC runs per K) |
| `jump` | None | Monotone inertia curves | Medium (GWC runs per K) |
| `stability` | Subsampling | Conservative, small / noisy datasets | Highest |

The default `eigengap` requires no reference distribution and is the
natural choice for spectral clustering, since it works directly on the
graph Laplacian whose spectrum is already computed.

---

## Backward compatibility

The previous name `grassmann_sc` is retained as a deprecated alias. It
forwards to `gotclust`, but note that its default `method` remains
`'spectral'` (whereas `gotclust` defaults to `'wasserstein'`). A
`DeprecationWarning` is emitted on use; new code should call
`gotclust` directly.

```python
from gotclust import grassmann_sc   # deprecated alias, still works
```

---

## Algorithm reference

### `gotclust(H, n_clusters, method, estimate_kwargs, **kwargs)`

Unified entry point. Defaults to `method="wasserstein"`.

- `method="wasserstein"` → forwards to `grassmann_wasserstein_clustering`
- `method="spectral"` → forwards to `grassmann_spectral_clustering`
- `n_clusters=None` or `"auto"` → estimate first, then cluster

### `grassmann_spectral_clustering(...)`

Pipeline:
1. `cells_to_grassmann` → local subspaces `U_i`
2. `grassmann_cost_matrix` → cost matrix `C`
3. `grassmann_affinity` → affinity matrix `A` (Zelnik-Perona local scaling)
4. `sklearn.SpectralClustering(affinity="precomputed")`

### `grassmann_wasserstein_clustering(...)`

Lloyd-style alternating optimization:
- **E-step** — assign each cell to the nearest cluster center
  (Grassmann projection distance)
- **M-step** — update each center to the Frechet mean of its members

### `grassmann_frechet_mean(V_list, weights, p)`

Closed-form Grassmann barycenter: eigen-decomposition of
`Σ w_j V_j V_j^T`, take top-`p` eigenvectors.

### `grassmann_affinity(C, method, sigma)`

Build an affinity matrix from a Grassmann cost matrix.
`method` ∈ `{"local", "global", "knn"}`.

### `estimate_n_clusters(H, k, p, backend, method, ...)`

Returns a dict with `n_clusters`, the per-`K` `scores`, the shared
cost matrix `C`, and the shared Grassmann points `U_list`.

### `gotclust_embed(H, n_components, method, mode, ...)`

GWC-aligned low-dimensional embedding. See [Embedding
(visualization)](#embedding-visualization). When `method='gwc'`,
`mode` selects between `soft` (SVD of gamma), `barycentric` (ilr of
gamma), and `distance` (cell-to-barycenter Grassmann distances).

### `gwc_soft_embedding(gamma, n_components, center)`

SVD / PCA of the soft-assignment matrix. `center=True` removes the
trivial all-rows-sum-to-one direction.

### `gwc_barycentric_embedding(gamma, n_components)`

Isometric-log-ratio transform followed by PCA; the appropriate
representation when memberships are compositional (a cell is a mixture
of regulatory states).

### `grassmann_mds_embedding(C, D, U_list, H, ...)`

Classical metric MDS on the Grassmann distance matrix. Either `C`,
`D`, `U_list`, or `H` must be supplied; earlier results are reused
when available.

### `grassmann_tsne_embedding(C, D, U_list, H, perplexity, ...)`

t-SNE on the Grassmann distance matrix (`metric='precomputed'` is set
automatically).

---

## Parameters

| Parameter | Default | Meaning |
|---|---|---|
| `k` | 30 | Neighborhood size for local subspace construction |
| `p` | 3 | Subspace dimension |
| `backend` | `"pca"` | Subspace construction backend (`loop`/`pca`/`batched`/`faiss`/`subsampling`) |
| `affinity` | `"local"` | Affinity construction (`local`/`global`/`knn`) |
| `n_iter` | 50 | Lloyd iterations (GWC) |
| `init` | `"kmeans++"` | Centroid initialization (GWC) |

---

## Citation

*Coming soon.*

---

## License

MIT
