Skip to main content

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

pip install GOTClust

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

pip install GOTClust[gpu]

Quick start

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.

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.


Embedding (visualization)

GOTClust's default clustering method is GWC (see Why GWC is the default), so the default embedding is built from the soft-assignment matrix gamma produced by the same Lloyd run. This has three immediate advantages over treating the embedding as an independent post-processing step:

  1. Zero extra cost — gamma already exists once gotclust has finished; there is no second Grassmann construction.
  2. It cannot disagree with the clustering — a cell plotted between two clusters is genuinely intermediate between them in membership space.
  3. Every axis is interpretable — the coordinates are principal components of the cluster-membership distribution, so they describe which regulatory programs a cell mixes between rather than an arbitrary non-linear projection.
from gotclust import gotclust, gotclust_embed

labels, info = gotclust(H)                 # GWC, auto K
Z, e_info   = gotclust_embed(H)           # soft (default), 2-D

# pass a previously computed result to avoid recomputation:
Z2 = gotclust_embed(None, method="gwc",
                    gamma=info["gamma"], labels=labels,
                    centroids=info["centroids"], info=info)

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

Argument Values Meaning
method gwc (default) Embedding derived from the GWC soft assignments
mds Classical MDS on the Grassmann distance matrix
tsne t-SNE on the Grassmann distance matrix
mode soft (default) PCA / SVD of gamma
barycentric Isometric-log-ratio representation of gamma
distance Embed the cell-to-barycenter Grassmann distances

Which option should I use?

Option Cost Preserves Best for
soft (default) O(n K d) Cluster-membership structure Default. Continuous / transitional states, mixture interpretation
barycentric O(n K d) Compositional (simplex) structure Developmental continua, perturbation-response mixtures
distance O(n K d) Distances to each barycenter Comparing individual cells to the learned cluster centers
mds O(n³) Global pairwise Grassmann geometry Up to a few thousand cells, faithful global picture
tsne O(n log n) Local neighbourhoods Rare-cell discovery, fine-grained subtypes

soft and barycentric scale linearly with the number of cells and are therefore the recommended choices for modern single-cell datasets; mds is retained as the geometrically faithful global baseline.

Why GWC is the default

Real-data evaluation showed that GWC is consistently stronger than GSC — both in cluster purity and in the stability of the result. GWC optimizes cluster centers as Grassmann Frechet barycenters, which is the principled subspace-aware objective; GSC is the faster spectral alternative. The embedding layer was consequently designed to consume the GWC output as its primary representation.


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.

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). 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

Metadata

Release files for GOTClust 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for GOTClust 0.4.0
File Size Uploaded Provenance Actions
gotclust-0.4.0.tar.gz 20.3 kB Without provenance Details for gotclust-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for GOTClust 0.4.0
File Interpreter ABI Platform Actions
gotclust-0.4.0-py3-none-any.whl Python 3 none any Details for gotclust-0.4.0-py3-none-any.whl

Total release size: 40.7 kB

Release files / gotclust-0.4.0.tar.gz

Download URL gotclust-0.4.0.tar.gz
Size 20.3 kB
Tags Source
SHA-256 checksum
How to use checksums
661d9e37e32eaf934fdf8c08da22f7073621051c3e142166ab7d37a96a020a00
BLAKE2b-256 checksum
How to use checksums
c9d378ce997f9ed4ebb7317e8a6248212b1098dbd9b49557340624d8745d7242
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.18

Release files / gotclust-0.4.0-py3-none-any.whl

Download URL gotclust-0.4.0-py3-none-any.whl
Size 20.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0c5735353db62224f010cb27df762c46f096649a9a76782ba9c77786410cac7f
BLAKE2b-256 checksum
How to use checksums
49b516919d84ff181b505c706094061c671f5e530334983759cb61bfee9bf52d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.18

Security for GOTClust 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page