gotvis 0.1.0__py3-none-any.whl

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.
gotvis/__init__.py ADDED
@@ -0,0 +1,80 @@
1
+ """GOTVis - visualization embeddings for GOTClust (gamma / Grassmann based)."""
2
+ from ._version import __version__
3
+ from ._embeddings import (
4
+ classical_mds_from_dist,
5
+ gamma_affinity,
6
+ laplacian_eigenmaps_from_affinity,
7
+ )
8
+ from . import api as _api
9
+ from ._validate import coerce_gamma, resolve_gamma
10
+
11
+
12
+ def sinkhorn_embedding(gamma, method="svd", n_components=None,
13
+ return_info=False, **kw):
14
+ """Embed a Sinkhorn / soft-assignment matrix gamma.
15
+
16
+ Methods: 'svd', 'barycentric', 'spectral', 'mds', 'tsne'.
17
+ Returns Y, or (Y, info) when return_info=True.
18
+ """
19
+ return _api.sinkhorn_embedding(gamma, method=method,
20
+ n_components=n_components,
21
+ return_info=return_info, **kw)
22
+
23
+
24
+ def sinkhorn_svd_embedding(gamma, n_components=2, return_info=False, **kw):
25
+ return sinkhorn_embedding(gamma, method="svd", n_components=n_components,
26
+ return_info=return_info, **kw)
27
+
28
+
29
+ def barycentric_embedding(gamma, n_components=None, transform="ilr",
30
+ return_info=False, **kw):
31
+ kw.setdefault("transform", transform)
32
+ return sinkhorn_embedding(gamma, method="barycentric",
33
+ n_components=n_components,
34
+ return_info=return_info, **kw)
35
+
36
+
37
+ def sinkhorn_spectral_embedding(gamma, n_components=2, return_info=False,
38
+ **kw):
39
+ return sinkhorn_embedding(gamma, method="spectral",
40
+ n_components=n_components,
41
+ return_info=return_info, **kw)
42
+
43
+
44
+ def gammagram_embedding(gamma, method="mds", n_components=2,
45
+ return_info=False, **kw):
46
+ return sinkhorn_embedding(gamma, method=method, n_components=n_components,
47
+ return_info=return_info, **kw)
48
+
49
+
50
+ def functional_embedding(*a, **kw):
51
+ return _api.functional_embedding(*a, **kw)
52
+
53
+
54
+ def mds_embedding(*a, **kw):
55
+ return _api.mds_embedding(*a, **kw)
56
+
57
+
58
+ def tsne_embedding(*a, **kw):
59
+ return _api.tsne_embedding(*a, **kw)
60
+
61
+
62
+ def gotclust_embed(*a, **kw):
63
+ return _api.gotclust_embed(*a, **kw)
64
+
65
+
66
+ __all__ = [
67
+ "__version__", "sinkhorn_embedding", "sinkhorn_svd_embedding",
68
+ "barycentric_embedding", "sinkhorn_spectral_embedding",
69
+ "gammagram_embedding", "functional_embedding", "mds_embedding",
70
+ "tsne_embedding", "gotclust_embed", "gamma_affinity",
71
+ "classical_mds_from_dist", "laplacian_eigenmaps_from_affinity",
72
+ "coerce_gamma", "resolve_gamma",
73
+ ]
74
+
75
+
76
+ def __getattr__(name):
77
+ if name in ("tools", "plotting"):
78
+ from . import anndata as _m
79
+ return _m
80
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
gotvis/_embeddings.py ADDED
@@ -0,0 +1,466 @@
1
+ """
2
+ Low-level embedding primitives.
3
+
4
+ Everything in this module is *pure array in -> array out*: no AnnData, no
5
+ plotting, no I/O. The public API in :mod:`gotvis.api` wraps these.
6
+ """
7
+
8
+ import numpy as np
9
+ from scipy.linalg import eigh, svd as linalg_svd
10
+ from scipy.sparse import csgraph
11
+ from scipy.sparse.linalg import eigsh
12
+
13
+
14
+ # ----------------------------------------------------------------------------
15
+ # small numeric helpers
16
+ # ----------------------------------------------------------------------------
17
+ def _as_2d(X):
18
+ X = np.asarray(X, dtype=np.float64)
19
+ if X.ndim == 1:
20
+ X = X.reshape(1, -1)
21
+ return X
22
+
23
+
24
+ def _normalize_rows(A, eps=1e-12):
25
+ """Row-normalise, leaving all-zero rows alone."""
26
+ A = np.asarray(A, dtype=np.float64)
27
+ row = A.sum(axis=1, keepdims=True)
28
+ return A / np.maximum(row, eps)
29
+
30
+
31
+ def _normalize_cols(A, eps=1e-12):
32
+ A = np.asarray(A, dtype=np.float64)
33
+ col = A.sum(axis=0, keepdims=True)
34
+ return A / np.maximum(col, eps)
35
+
36
+
37
+ def _symmetrize(A):
38
+ A = np.asarray(A, dtype=np.float64)
39
+ return (A + A.T) / 2.0
40
+
41
+
42
+ def _check_gamma(gamma):
43
+ gamma = np.asarray(gamma, dtype=np.float64)
44
+ if gamma.ndim != 2:
45
+ raise ValueError(f"gamma must be 2-D (n_cells, n_prototypes), "
46
+ f"got shape {gamma.shape}")
47
+ n, m = gamma.shape
48
+ if n < 2:
49
+ raise ValueError(f"gamma must have at least 2 rows, got {n}")
50
+ if m < 1:
51
+ raise ValueError("gamma must have at least 1 column")
52
+ if not np.all(np.isfinite(gamma)):
53
+ raise ValueError("gamma contains NaN/Inf")
54
+ if gamma.min() < 0:
55
+ raise ValueError("gamma contains negative entries; expected a "
56
+ "non-negative transport / membership matrix")
57
+ return gamma
58
+
59
+
60
+ # ----------------------------------------------------------------------------
61
+ # classical MDS
62
+ # ----------------------------------------------------------------------------
63
+ def classical_mds_from_dist(D, n_components=2, n_landmarks=None,
64
+ random_state=0):
65
+ """
66
+ Classical (metric) MDS from a square distance matrix.
67
+
68
+ Parameters
69
+ ----------
70
+ D : ndarray, shape (n, n)
71
+ Pairwise distance / cost matrix.
72
+ n_components : int
73
+ Target dimension.
74
+ n_landmarks : int or None
75
+ If given, embed only `n_landmarks` landmark points exactly
76
+ (O(L^3 + n L d) instead of O(n^3)) and project the remaining
77
+ points out of sample via the standard landmark-MDS formula.
78
+
79
+ Returns
80
+ -------
81
+ Y : ndarray, shape (n, n_components)
82
+ """
83
+ D = np.asarray(D, dtype=np.float64)
84
+ n = D.shape[0]
85
+ d = int(max(1, min(n_components, n - 1)))
86
+
87
+ if n_landmarks is not None and int(n_landmarks) < n:
88
+ L = int(n_landmarks)
89
+ rng = np.random.RandomState(random_state)
90
+ idx = np.sort(rng.choice(n, size=L, replace=False))
91
+ Dll = D[np.ix_(idx, idx)]
92
+ Yl = classical_mds_from_dist(Dll, n_components=d)
93
+
94
+ # out-of-sample landmark MDS (Silva & Tenenbaum 2002):
95
+ # B = -1/2 (d2_iL - mean_row(d2_LL) - mean_col(d2_iL) + mean(d2_LL))
96
+ # Y = B @ pinv(Yl) (B: (n,L), Yl: (L,d) with zero mean)
97
+ D2 = D ** 2
98
+ D2ll = Dll ** 2
99
+ Yl = Yl - Yl.mean(axis=0, keepdims=True)
100
+ B = -0.5 * (D2[:, idx] - D2ll.mean(axis=0, keepdims=True)
101
+ - D2[:, idx].mean(axis=1, keepdims=True) + D2ll.mean())
102
+ # W = Bl^+ Yl (L x d): least-squares lift from scalar-product space
103
+ Jl = np.eye(L) - np.ones((L, L)) / L
104
+ Bl = -0.5 * Jl @ (Dll ** 2) @ Jl
105
+ W = np.linalg.lstsq(Bl, Yl, rcond=None)[0]
106
+ Y = B @ W
107
+ Y[idx] = Yl
108
+ return Y
109
+
110
+ D2 = D ** 2
111
+ J = np.eye(n) - np.ones((n, n)) / n
112
+ B = -0.5 * (J @ D2 @ J)
113
+ w, V = eigh(B)
114
+ order = np.argsort(w)[::-1]
115
+ w, V = w[order], V[:, order]
116
+ pos = w > 1e-12
117
+ if not np.any(pos):
118
+ pos = np.ones_like(w, dtype=bool)
119
+ w_pos = np.maximum(w[pos][:d], 0.0)
120
+ V_pos = V[:, pos][:, :d]
121
+ return V_pos * np.sqrt(w_pos)
122
+
123
+
124
+ # ----------------------------------------------------------------------------
125
+ # Laplacian eigenmaps
126
+ # ----------------------------------------------------------------------------
127
+ def laplacian_eigenmaps_from_affinity(A, n_components=2, knn=None,
128
+ normalized=True):
129
+ """
130
+ Laplacian Eigenmaps embedding from an affinity / adjacency matrix.
131
+
132
+ Parameters
133
+ ----------
134
+ A : ndarray, shape (n, n)
135
+ Non-negative affinity matrix.
136
+ n_components : int
137
+ Target dimension (excluding the trivial constant eigenvector).
138
+ knn : int or None
139
+ If given, keep only each row's `knn` largest affinities.
140
+ normalized : bool
141
+ Use the normalised Laplacian L = I - D^-1/2 A D^-1/2.
142
+
143
+ Returns
144
+ -------
145
+ Y : ndarray, shape (n, n_components)
146
+ """
147
+ A = np.asarray(A, dtype=np.float64).copy()
148
+ n = A.shape[0]
149
+
150
+ if knn is not None and knn > 0 and knn < n:
151
+ k = int(knn)
152
+ mask = np.zeros_like(A, dtype=bool)
153
+ idx = np.argpartition(A, -k, axis=1)[:, -k:]
154
+ rows = np.arange(n)[:, None]
155
+ mask[rows, idx] = True
156
+ A[~mask] = 0.0
157
+ A = np.maximum(A, A.T)
158
+
159
+ np.fill_diagonal(A, 0.0)
160
+
161
+ deg = A.sum(axis=1)
162
+ if normalized:
163
+ d_inv_sqrt = 1.0 / np.maximum(np.sqrt(deg), 1e-12)
164
+ L = np.eye(n) - A * d_inv_sqrt[:, None] * d_inv_sqrt[None, :]
165
+ else:
166
+ L = np.diag(deg) - A
167
+
168
+ d = int(max(1, min(n_components, n - 2)))
169
+ try:
170
+ _, V = eigsh(L, k=d + 1, which="SM", tol=1e-4, maxiter=5000)
171
+ vals = np.array([float((V[:, j] @ L @ V[:, j])) for j in range(V.shape[1])])
172
+ order = np.argsort(vals)
173
+ Y = np.real(V[:, order[1:d + 1]])
174
+ except Exception:
175
+ vals, vecs = eigh(L)
176
+ order = np.argsort(vals)
177
+ Y = np.real(vecs[:, order[1:d + 1]])
178
+
179
+ if Y.ndim == 1:
180
+ Y = Y.reshape(-1, 1)
181
+ Y = Y - Y.mean(axis=0, keepdims=True)
182
+ scale = np.linalg.norm(Y, axis=0, keepdims=True)
183
+ Y = Y / np.maximum(scale, 1e-12)
184
+ return Y
185
+
186
+
187
+ # ----------------------------------------------------------------------------
188
+ # gamma -> affinity
189
+ # ----------------------------------------------------------------------------
190
+ def gamma_affinity(gamma, mode="gram", eps=1e-12):
191
+ """
192
+ Build a cell-cell affinity matrix from a soft-assignment matrix.
193
+
194
+ Parameters
195
+ ----------
196
+ gamma : ndarray, shape (n, m)
197
+ Non-negative soft assignment (rows need not sum to 1).
198
+ mode : str
199
+ 'gram' -> A = G G^T (raw co-membership)
200
+ 'cosine' -> A = G G^T with G row-l2-normalised
201
+ 'joint' -> A = G G^T + G^T-style prototype overlap term
202
+ 'kl' -> affinity from a symmetric Jensen-Shannon-type
203
+ similarity between rows of gamma
204
+ 'barycentric' -> not an affinity; raises. Use the embedding instead.
205
+ eps : float
206
+ Numerical floor.
207
+
208
+ Returns
209
+ -------
210
+ A : ndarray, shape (n, n)
211
+ """
212
+ G = _check_gamma(gamma)
213
+
214
+ if mode == "gram":
215
+ A = G @ G.T
216
+ elif mode == "cosine":
217
+ Gn = G / np.maximum(np.linalg.norm(G, axis=1, keepdims=True), eps)
218
+ A = Gn @ Gn.T
219
+ elif mode == "joint":
220
+ Gn = G / np.maximum(np.linalg.norm(G, axis=1, keepdims=True), eps)
221
+ Pt = _normalize_cols(G) # prototype loading view
222
+ A = 0.5 * (Gn @ Gn.T) + 0.5 * (Pt @ Pt.T)
223
+ elif mode == "kl":
224
+ P = _normalize_rows(G)
225
+ m = P.shape[1]
226
+ uni = np.full(m, 1.0 / m, dtype=np.float64)
227
+ M = 0.5 * (P[:, None, :] + P[None, :, :])
228
+ kl_pm = np.sum(P[:, None, :] * np.log((P[:, None, :] + eps) / (M + eps)), axis=2)
229
+ kl_mp = np.sum(M * np.log((M + eps) / (P[None, :, :] + eps)), axis=2)
230
+ js = 0.5 * (kl_pm + kl_mp)
231
+ A = np.exp(-js)
232
+ elif mode == "barycentric":
233
+ raise ValueError("mode='barycentric' does not produce an affinity; "
234
+ "call barycentric_embedding(gamma) instead.")
235
+ else:
236
+ raise ValueError(f"Unknown affinity mode: {mode!r}")
237
+
238
+ A = _symmetrize(A)
239
+ scale = np.max(np.abs(A))
240
+ if scale > 0:
241
+ A = A / scale
242
+ return np.clip(A, 0.0, 1.0)
243
+
244
+
245
+ # ----------------------------------------------------------------------------
246
+ # gamma embeddings
247
+ # ----------------------------------------------------------------------------
248
+ def sinkhorn_svd_embedding(gamma, n_components=2, whiten=True,
249
+ sign_stabilize=True):
250
+ """
251
+ SVD embedding of a Sinkhorn / soft-assignment matrix gamma.
252
+
253
+ gamma (n cells x m prototypes) is a soft membership matrix. Its
254
+ truncated SVD gives coordinates in the "prototype membership" basis:
255
+ each axis is a direction of co-assignment, so cells sharing prototypes
256
+ land close together. This is the zero-extra-cost companion to GSSC.
257
+
258
+ Parameters
259
+ ----------
260
+ gamma : ndarray, shape (n, m)
261
+ n_components : int
262
+ whiten : bool
263
+ Scale axes by their singular values (True) or leave the raw
264
+ right-singular projection (False).
265
+ sign_stabilize : bool
266
+ Flip axis signs so the largest-|value| cell on each axis is
267
+ positive (SVD signs are arbitrary).
268
+
269
+ Returns
270
+ -------
271
+ Y : ndarray, shape (n, n_components)
272
+ info : dict with keys 'singular_values', 'explained_variance_ratio'
273
+ """
274
+ G = _check_gamma(gamma)
275
+ n, m = G.shape
276
+ d = int(max(1, min(n_components, min(n, m) - 1)))
277
+ if n_components == 0:
278
+ d = int(max(1, min(n, m) - 1))
279
+
280
+ # centre columns so axis 0 is not swallowed by the mass constant
281
+ Gc = G - G.mean(axis=0, keepdims=True)
282
+
283
+ try:
284
+ U, s, Vt = linalg_svd(Gc, full_matrices=False)
285
+ except np.linalg.LinAlgError:
286
+ U, s, Vt = linalg_svd(Gc + 1e-8 * np.random.RandomState(0).standard_normal(Gc.shape),
287
+ full_matrices=False)
288
+
289
+ if whiten:
290
+ Y = U[:, :d] * s[:d][None, :]
291
+ else:
292
+ Y = U[:, :d]
293
+
294
+ if sign_stabilize:
295
+ for j in range(Y.shape[1]):
296
+ col = Y[:, j]
297
+ if np.sum(col < 0) > np.sum(col > 0):
298
+ Y[:, j] = -col
299
+
300
+ sv = np.asarray(s, dtype=np.float64)
301
+ tot = float(np.sum(sv ** 2))
302
+ evr = (sv[:d] ** 2 / tot) if tot > 0 else np.zeros(d)
303
+ return Y, {"singular_values": sv, "explained_variance_ratio": evr}
304
+
305
+
306
+ def barycentric_embedding(gamma, n_components=None, transform="ilr",
307
+ eps=1e-9, pivot=None, **_kw):
308
+ """
309
+ Barycentric (simplex) embedding of a Sinkhorn / soft-assignment matrix.
310
+
311
+ Each row of gamma is treated as a point on the (m-1)-simplex and mapped
312
+ to Euclidean coordinates via an isometric log-ratio (ilr) or centred
313
+ log-ratio (clr) transform (Aitchison geometry).
314
+
315
+ Parameters
316
+ ----------
317
+ gamma : ndarray, shape (n, m)
318
+ n_components : int or None
319
+ Target dimension. For 'ilr' the natural dimension is m-1; if
320
+ n_components < m-1 a trailing PCA is applied. For 'clr' the
321
+ natural dimension is m.
322
+ transform : {'ilr', 'clr'}
323
+ 'ilr' : orthonormal log-ratio -> exactly m-1 coordinates.
324
+ 'clr' : centred log-ratio -> m coordinates (rank m-1).
325
+ eps : float
326
+ Floor for zero entries before taking logs.
327
+ pivot : int or None
328
+ Reference component for the ilr sequential binary partition
329
+ (default: last column). Ignored by 'clr'.
330
+
331
+ Returns
332
+ -------
333
+ Y : ndarray, shape (n, n_components or m-1 or m)
334
+ info : dict with keys 'transform', 'clr' (clr coords), 'gmean'
335
+ """
336
+ G = _check_gamma(gamma)
337
+ n, m = G.shape
338
+ if m < 2:
339
+ raise ValueError("barycentric_embedding needs >= 2 prototypes "
340
+ f"(gamma has {m} columns)")
341
+
342
+ K_ = m
343
+ Gs = G / np.maximum(G.sum(axis=1, keepdims=True), eps)
344
+ Gs = np.clip(Gs, eps, 1.0)
345
+ Gs = Gs / Gs.sum(axis=1, keepdims=True)
346
+
347
+ logG = np.log(Gs)
348
+ gmean = logG.mean(axis=1, keepdims=True)
349
+ clr = logG - gmean
350
+
351
+ if transform == "clr":
352
+ Y = clr - clr.mean(axis=1, keepdims=True)
353
+ elif transform == "ilr":
354
+ # Isometric log-ratio via an orthonormal contrast basis.
355
+ # Build (m-1) orthonormal contrasts of the clr coordinates:
356
+ # P[i, j] = +sqrt((m-i-1)/(m-i)) for j == i
357
+ # P[i, j] = -1/sqrt((m-i)(m-i-1)) for j > i
358
+ # P[i, j] = 0 for j < i
359
+ # so Y = clr @ P.T, with Y.shape == (n, m-1) and Y.sum(axis=1) == 0.
360
+ P = np.zeros((K_, m), dtype=np.float64) if False else None
361
+ m_ = m
362
+ P = np.zeros((m_ - 1, m_), dtype=np.float64)
363
+ for i in range(m_ - 1):
364
+ denom = m_ - i
365
+ P[i, i] = np.sqrt((denom - 1) / denom)
366
+ if denom > 1:
367
+ P[i, i + 1:] = -1.0 / np.sqrt(denom * (denom - 1))
368
+ Y = clr @ P.T
369
+ if pivot is not None and int(pivot) != m_ - 1:
370
+ # rotate so that `pivot` plays the reference role (sign-secure)
371
+ Y = Y[:, ::-1].copy()
372
+ Y = np.ascontiguousarray(Y)
373
+ else:
374
+ raise ValueError(f"Unknown transform: {transform!r}")
375
+
376
+ info = {"transform": transform, "clr": clr, "gmean": gmean.ravel()}
377
+ info["natural_dim"] = Y.shape[1]
378
+
379
+ if n_components is not None and int(n_components) < Y.shape[1]:
380
+ d = int(n_components)
381
+ Yc = Y - Y.mean(axis=0, keepdims=True)
382
+ try:
383
+ U, s, Vt = linalg_svd(Yc, full_matrices=False)
384
+ except np.linalg.LinAlgError:
385
+ U, s, _ = linalg_svd(Yc + 1e-10 * np.random.RandomState(0).standard_normal(Yc.shape),
386
+ full_matrices=False)
387
+ Vt = None
388
+ Y = U[:, :d] * s[:d][None, :]
389
+ info["pca_singular_values"] = s
390
+ if Vt is not None:
391
+ info["pca_components"] = Vt[:d]
392
+ info["n_components"] = d
393
+ return Y, info
394
+
395
+
396
+ def gamma_spectral_embedding(gamma, n_components=2, affinity="gram",
397
+ knn=None, normalized_laplacian=True):
398
+ """
399
+ Spectral embedding on a gamma-induced cell-cell graph.
400
+
401
+ Parameters
402
+ ----------
403
+ gamma : ndarray, shape (n, m)
404
+ n_components : int
405
+ affinity : str
406
+ Passed to :func:`gamma_affinity` ('gram', 'cosine', 'joint', 'kl').
407
+ knn : int or None
408
+ Sparsify the affinity to a kNN graph before the Laplacian.
409
+ normalized_laplacian : bool
410
+
411
+ Returns
412
+ -------
413
+ Y : ndarray, shape (n, n_components)
414
+ info : dict with key 'affinity'
415
+ """
416
+ A = gamma_affinity(gamma, mode=affinity)
417
+ Y = laplacian_eigenmaps_from_affinity(
418
+ A, n_components=n_components, knn=knn,
419
+ normalized=normalized_laplacian)
420
+ return Y, {"affinity": A}
421
+
422
+
423
+ # ----------------------------------------------------------------------------
424
+ # distance -> embedding
425
+ # ----------------------------------------------------------------------------
426
+ def distance_mds_embedding(D, n_components=2, n_landmarks=None,
427
+ random_state=0):
428
+ """Classical MDS on a precomputed distance matrix."""
429
+ D = np.asarray(D, dtype=np.float64)
430
+ Y = classical_mds_from_dist(D, n_components=n_components,
431
+ n_landmarks=n_landmarks,
432
+ random_state=random_state)
433
+ return Y, {"n_landmarks": n_landmarks}
434
+
435
+
436
+ def distance_tsne_embedding(D, n_components=2, perplexity=30.0,
437
+ random_state=0, **kwargs):
438
+ """
439
+ t-SNE on a precomputed distance matrix.
440
+
441
+ Tries sklearn's TSNE(metric='precomputed') first, then openTSNE, then
442
+ falls back to MDS if neither is installed.
443
+ """
444
+ D = np.asarray(D, dtype=np.float64)
445
+ n = D.shape[0]
446
+ try:
447
+ from sklearn.manifold import TSNE
448
+ ts = TSNE(n_components=n_components, metric="precomputed",
449
+ perplexity=float(min(perplexity, max(n / 3.0 - 1, 1.0))),
450
+ random_state=random_state, **kwargs)
451
+ Y = ts.fit_transform(D)
452
+ return Y, {"backend": "sklearn"}
453
+ except Exception:
454
+ pass
455
+ try:
456
+ import openTSNE
457
+ pp = float(min(perplexity, max(n / 3.0 - 1, 5.0)))
458
+ aff = openTSNE.affinity.PerplexityBasedNN(
459
+ D, perplexity=pp, metric="precomputed", random_state=random_state)
460
+ init = openTSNE.initialization.random(n, n_components, random_state=random_state)
461
+ emb = openTSNE.TSNE(**kwargs).fit(aff, initialization=init)
462
+ return np.asarray(emb), {"backend": "openTSNE"}
463
+ except Exception:
464
+ pass
465
+ Y = classical_mds_from_dist(D, n_components=n_components)
466
+ return Y, {"backend": "mds-fallback"}
gotvis/_validate.py ADDED
@@ -0,0 +1,94 @@
1
+ """Input validation and gamma resolution helpers."""
2
+
3
+ import numpy as np
4
+
5
+
6
+ def coerce_gamma(gamma, copy=True):
7
+ """
8
+ Validate and normalise a soft-assignment matrix.
9
+
10
+ Accepts ndarray, sparse matrix, or anything with ``__array__``.
11
+ Returns a float64 ndarray with negative values rejected and NaN/Inf
12
+ rejected. All-zero rows are left as they are.
13
+ """
14
+ if hasattr(gamma, "toarray"): # scipy sparse
15
+ gamma = gamma.toarray()
16
+ G = np.asarray(gamma, dtype=np.float64) if not copy \
17
+ else np.array(gamma, dtype=np.float64, copy=True)
18
+
19
+ if G.ndim != 2:
20
+ raise ValueError(f"gamma must be 2-D (n_cells, n_prototypes), "
21
+ f"got {G.ndim}-D with shape {G.shape}")
22
+ n, m = G.shape
23
+ if n < 2:
24
+ raise ValueError(f"gamma needs >= 2 rows (cells), got {n}")
25
+ if m < 1:
26
+ raise ValueError("gamma needs >= 1 column (prototypes)")
27
+ if not np.all(np.isfinite(G)):
28
+ bad = int((~np.isfinite(G)).sum())
29
+ raise ValueError(f"gamma contains {bad} NaN/Inf entr(y|ies)")
30
+ if G.min() < 0:
31
+ lo = float(G.min())
32
+ raise ValueError(f"gamma must be non-negative (min={lo:.3e}); "
33
+ f"expected a transport / membership matrix")
34
+ return G
35
+
36
+
37
+ def resolve_gamma(obj, source=None, keys=("gamma", "G", "soft_assign",
38
+ "assignment", "P", "C_proto")):
39
+ """
40
+ Pull a gamma matrix out of convenient containers.
41
+
42
+ Supported inputs
43
+ ----------------
44
+ ndarray / sparse -> returned as-is (validated)
45
+ dict -> looked up by `source` or `keys` order
46
+ object with `.gamma` -> attribute access
47
+ tuple/list of length 2 -> interpreted as (labels_or_info, gamma); the
48
+ second element must be array-like
49
+ """
50
+ if obj is None:
51
+ raise ValueError("no gamma supplied")
52
+
53
+ if isinstance(obj, (list, tuple)):
54
+ if len(obj) == 2:
55
+ try:
56
+ return coerce_gamma(obj[1])
57
+ except Exception:
58
+ return resolve_gamma(obj[0], source=source, keys=keys)
59
+ raise ValueError(f"cannot resolve gamma from a {len(obj)}-tuple")
60
+
61
+ if not isinstance(obj, (dict,)) and hasattr(obj, "gamma"):
62
+ cand = obj.gamma
63
+ if cand is not None:
64
+ return coerce_gamma(cand)
65
+
66
+ if isinstance(obj, dict):
67
+ if source is not None:
68
+ if source not in obj:
69
+ raise KeyError(f"gamma source {source!r} not in dict; "
70
+ f"available keys: {sorted(obj.keys())}")
71
+ return coerce_gamma(obj[source])
72
+ for k in keys:
73
+ if k in obj:
74
+ v = obj[k]
75
+ try:
76
+ return coerce_gamma(v)
77
+ except Exception:
78
+ continue
79
+ raise KeyError(f"no gamma-like array found in dict; tried {keys}, "
80
+ f"available keys: {sorted(obj.keys())}")
81
+
82
+ return coerce_gamma(obj)
83
+
84
+
85
+ def maybe_square_dist(D):
86
+ """Validate a square distance matrix."""
87
+ D = np.asarray(D, dtype=np.float64)
88
+ if D.ndim != 2 or D.shape[0] != D.shape[1]:
89
+ raise ValueError(f"expected a square distance matrix, got {D.shape}")
90
+ if D.shape[0] < 2:
91
+ raise ValueError("distance matrix must be at least 2x2")
92
+ if not np.allclose(D, D.T, atol=1e-6):
93
+ pass # non-symmetric distances tolerated (e.g. directed OT cost)
94
+ return D
gotvis/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
gotvis/anndata.py ADDED
@@ -0,0 +1,137 @@
1
+ """Optional AnnData / Scanpy integration (``gotvis.tools``)."""
2
+
3
+ import numpy as np
4
+
5
+
6
+ def _get_obs_frame(adata):
7
+ if adata is None:
8
+ return None
9
+ return adata.obs
10
+
11
+
12
+ def embed(adata, gamma=None, C=None, method="svd", n_components=2,
13
+ key_added="X_gotvis", obsm_key_gamma="gamma",
14
+ inplace=True, return_info=False, **kwargs):
15
+ """
16
+ Compute a GOTVis embedding and store it in ``adata.obsm[key_added]``.
17
+
18
+ Parameters
19
+ ----------
20
+ adata : AnnData
21
+ gamma : ndarray, str, or None
22
+ Either an array, or a key into ``adata.uns`` / ``adata.obsm``
23
+ (default lookup: ``obsm['gamma']`` then ``uns['gamma']``).
24
+ C : ndarray or str or None
25
+ Grassmann cost matrix, or a key into ``adata.uns``.
26
+ method : str
27
+ 'svd', 'barycentric', 'spectral', 'mds', 'tsne' (gamma path) or
28
+ 'laplacian', 'mds' (Grassmann cost path).
29
+ key_added : str
30
+ Destination key in ``adata.obsm``.
31
+ inplace : bool
32
+ Write into ``adata.obsm`` (True) or just return the array.
33
+ """
34
+ from .api import sinkhorn_embedding, functional_embedding
35
+
36
+ resolved = None
37
+ if gamma is not None:
38
+ resolved = _resolve_from_adata(adata, gamma,
39
+ obsm_key=obsm_key_gamma)
40
+ if resolved is not None:
41
+ out = sinkhorn_embedding(resolved, method=method,
42
+ n_components=n_components,
43
+ return_info=True, **kwargs)
44
+ else:
45
+ Cm = _resolve_from_adata(adata, C, obsm_key="C") if C is not None \
46
+ else None
47
+ gm = method if method in ("laplacian", "mds") else "laplacian"
48
+ out = functional_embedding(C=Cm, n_components=n_components,
49
+ method=gm, return_info=True, **kwargs)
50
+
51
+ Y, info = out
52
+ if inplace and adata is not None:
53
+ adata.obsm[key_added] = np.asarray(Y)
54
+ return (Y, info) if return_info else Y
55
+
56
+
57
+ def _resolve_from_adata(adata, obj, obsm_key="gamma"):
58
+ if isinstance(obj, str):
59
+ if adata is None:
60
+ raise ValueError("adata is required when passing a string key")
61
+ for getter in (lambda: adata.obsm[obj],
62
+ lambda: adata.uns[obj],
63
+ lambda: adata.obsm[obsm_key],
64
+ lambda: adata.uns[obsm_key]):
65
+ try:
66
+ v = getter()
67
+ except Exception:
68
+ continue
69
+ if v is not None:
70
+ return v
71
+ raise KeyError(f"{obj!r} not found in adata.obsm / adata.uns")
72
+ return obj
73
+
74
+
75
+ def gamma_from_gotclust(info, adata=None, uns_key="gamma", obsm_key=None,
76
+ inplace=True):
77
+ """
78
+ Copy a gamma matrix out of a GOTClust `info` dict into an AnnData object.
79
+
80
+ Usage
81
+ -----
82
+ >>> labels, info = gotclust.grassmann_sinkhorn_clustering(H, 5)
83
+ >>> gotvis.tools.gamma_from_gotclust(info, adata)
84
+ >>> gotvis.tools.embed(adata, method="svd")
85
+ """
86
+ from ._validate import resolve_gamma
87
+ G = resolve_gamma(info)
88
+ if inplace and adata is not None:
89
+ adata.uns[uns_key] = np.asarray(G)
90
+ if obsm_key is not None:
91
+ adata.obsm[obsm_key] = np.asarray(G)
92
+ return np.asarray(G)
93
+
94
+
95
+ def plot_embedding(adata_or_Y, color=None, basis="X_gotvis", **kwargs):
96
+ """Thin scatter wrapper. Returns the matplotlib axes."""
97
+ import matplotlib.pyplot as plt
98
+
99
+ if hasattr(adata_or_Y, "obsm"):
100
+ Y = np.asarray(adata_or_Y.obsm[basis])
101
+ c = adata_or_Y.obs[color].values if color else None
102
+ title = f"{basis}" + (f", colored by {color}" if color else "")
103
+ else:
104
+ Y = np.asarray(adata_or_Y)
105
+ c = color
106
+ title = kwargs.pop("title", "GOTVis embedding")
107
+
108
+ fig, ax = plt.subplots(figsize=kwargs.pop("figsize", (5, 5)))
109
+ if c is None:
110
+ ax.scatter(Y[:, 0], Y[:, 1], s=kwargs.pop("s", 8),
111
+ alpha=kwargs.pop("alpha", 0.7), **kwargs)
112
+ else:
113
+ try:
114
+ import pandas as pd
115
+ if isinstance(c, (pd.Categorical, pd.Series)):
116
+ c = c.astype(str).values
117
+ except Exception:
118
+ pass
119
+ cats = np.unique(c)
120
+ cmap = kwargs.pop("cmap", "tab10")
121
+ try:
122
+ import seaborn as sns
123
+ palette = sns.color_palette(cmap, len(cats))
124
+ except Exception:
125
+ cmap_obj = plt.get_cmap(cmap)
126
+ palette = [cmap_obj(i / max(len(cats) - 1, 1)) for i in range(len(cats))]
127
+ for i, cat in enumerate(cats):
128
+ m = c == cat
129
+ ax.scatter(Y[m, 0], Y[m, 1], s=kwargs.pop("s", 8),
130
+ alpha=kwargs.pop("alpha", 0.8),
131
+ color=palette[i], label=str(cat), **kwargs)
132
+ ax.legend(markerscale=2, fontsize=8, frameon=False)
133
+ ax.set_title(title, fontsize=10)
134
+ ax.set_xlabel(f"{basis} 1")
135
+ ax.set_ylabel(f"{basis} 2")
136
+ fig.tight_layout()
137
+ return ax
gotvis/api.py ADDED
@@ -0,0 +1,272 @@
1
+ """
2
+ Public embedding API.
3
+
4
+ Two families of entry points:
5
+
6
+ 1. **From a Sinkhorn / soft-assignment matrix ``gamma``** (new in GOTVis) --
7
+ :func:`sinkhorn_embedding`, :func:`sinkhorn_svd_embedding`,
8
+ :func:`barycentric_embedding`, :func:`sinkhorn_spectral_embedding`.
9
+ These work with *any* non-negative membership matrix, so they also accept
10
+ GWC soft assignments, NMF loadings, Seurat/SCANVI class probabilities, …
11
+
12
+ 2. **From Grassmann objects** (carried over from GOTClust) --
13
+ :func:`functional_embedding` (Laplacian Eigenmaps / MDS on the Grassmann
14
+ cost matrix C) and :func:`mds_embedding` / :func:`tsne_embedding`
15
+ (classical MDS / t-SNE on C).
16
+
17
+ Every function returns an ``(n_cells, n_components)`` array, optionally
18
+ packed with diagnostics. Set ``return_info=True`` to also get the ``info``
19
+ dict.
20
+ """
21
+
22
+ import numpy as np
23
+
24
+ from ._embeddings import (
25
+ barycentric_embedding as _barycentric,
26
+ classical_mds_from_dist,
27
+ distance_mds_embedding as _mds,
28
+ distance_tsne_embedding as _tsne,
29
+ gamma_affinity,
30
+ gamma_spectral_embedding as _gamma_spectral,
31
+ laplacian_eigenmaps_from_affinity,
32
+ sinkhorn_svd_embedding as _sinkhorn_svd,
33
+ )
34
+ from ._validate import coerce_gamma, resolve_gamma
35
+
36
+
37
+ # ============================================================
38
+ # (1) Sinkhorn / gamma-based embeddings
39
+ # ============================================================
40
+ def sinkhorn_embedding(gamma, method="svd", n_components=2,
41
+ gamma_source=None, **kwargs):
42
+ """
43
+ Unified entry point for embeddings derived from a Sinkhorn gamma.
44
+
45
+ Parameters
46
+ ----------
47
+ gamma : ndarray or object
48
+ Non-negative soft-assignment matrix (n_cells, n_prototypes).
49
+ You can also pass a GSSC/GWC *info dict* or any object exposing a
50
+ ``gamma`` attribute / key -- see :func:`resolve_gamma`.
51
+ method : str
52
+ 'svd' -> :func:`sinkhorn_svd_embedding` (default, cheapest)
53
+ 'barycentric'
54
+ -> :func:`barycentric_embedding` (simplex geometry)
55
+ 'spectral' -> :func:`sinkhorn_spectral_embedding`
56
+ 'mds' -> MDS on the gammagram distance sqrt(diag - 2GG' + diag)
57
+ 'tsne' -> t-SNE on that same gamma distance
58
+ n_components : int
59
+ Target dimension.
60
+ gamma_source : str or None
61
+ Only used when `gamma` is a dict-like object holding several
62
+ candidate matrices (e.g. an info dict with both 'gamma' and
63
+ 'soft_assign').
64
+ **kwargs :
65
+ Forwarded to the chosen backend.
66
+
67
+ Returns
68
+ -------
69
+ Y : ndarray, shape (n_cells, n_components)
70
+ info : dict (always returned as second element; the public wrapper in
71
+ ``gotvis.__init__`` hides it unless ``return_info=True``)
72
+ """
73
+ return_info = kwargs.pop("return_info", False)
74
+ G = resolve_gamma(gamma, source=gamma_source) if not isinstance(
75
+ gamma, np.ndarray) else coerce_gamma(gamma)
76
+
77
+ key = str(method).lower()
78
+ is_bary = key in ("barycentric", "simplex", "clr", "ilr")
79
+ # barycentric: None -> let the backend pick the natural dimension (m-1/m)
80
+ # others: None -> 0 means "full rank" for SVD, 2 elsewhere
81
+ if n_components is None:
82
+ # barycentric keeps its natural simplex dimension (m-1 / m);
83
+ # svd uses full rank when asked via 0, otherwise the caller's choice.
84
+ n_components = None if is_bary else 2
85
+ else:
86
+ n_components = int(n_components)
87
+
88
+ if key in ("svd", "gssc", "soft"):
89
+ Y, info = _sinkhorn_svd(G, n_components=n_components, **kwargs)
90
+ elif key in ("barycentric", "simplex", "clr", "ilr"):
91
+ Y, info = _barycentric(G, n_components=n_components, **kwargs)
92
+ elif key in ("spectral", "laplacian", "eigenmaps"):
93
+ Y, info = _gamma_spectral(G, n_components=n_components, **kwargs)
94
+ elif key in ("mds", "cmds"):
95
+ D = _gamma_distance(G)
96
+ Y, info = _mds(D, n_components=n_components, **kwargs)
97
+ info["distance"] = "gammagram"
98
+ elif key in ("tsne", "t-sne"):
99
+ D = _gamma_distance(G)
100
+ Y, info = _tsne(D, n_components=n_components, **kwargs)
101
+ info["distance"] = "gammagram"
102
+ else:
103
+ raise ValueError(f"Unknown sinkhorn embedding method: {method!r}. "
104
+ "Choose 'svd', 'barycentric', 'spectral', 'mds', "
105
+ "'tsne'.")
106
+ info["method"] = key
107
+ info["gamma_shape"] = G.shape
108
+ return (Y, info) if return_info else Y
109
+
110
+
111
+ # backwards-friendly aliases
112
+ def sinkhorn_svd_embedding(gamma, n_components=2, return_info=False, **kw):
113
+ """SVD embedding of gamma. See :func:`sinkhorn_embedding`."""
114
+ return sinkhorn_embedding(gamma, method="svd", n_components=n_components,
115
+ return_info=return_info, **kw)
116
+
117
+
118
+ def barycentric_embedding(gamma, n_components=None, transform="ilr",
119
+ return_info=False, **kw):
120
+ """Aitchison simplex embedding of gamma. See :func:`sinkhorn_embedding`."""
121
+ return sinkhorn_embedding(gamma, method="barycentric", transform=transform,
122
+ n_components=n_components,
123
+ return_info=return_info, **kw)
124
+
125
+
126
+ def sinkhorn_spectral_embedding(gamma, n_components=2, return_info=False,
127
+ **kw):
128
+ """Laplacian eigenmaps on the gamma-induced cell-cell graph."""
129
+ return sinkhorn_embedding(gamma, method="spectral",
130
+ n_components=n_components,
131
+ return_info=return_info, **kw)
132
+
133
+
134
+ def gammagram_embedding(gamma, method="mds", n_components=2,
135
+ return_info=False, **kw):
136
+ """
137
+ Embedding from the gamma-induced cell-cell distance
138
+ ``d(i,j) = sqrt( ||g_i||^2 + ||g_j||^2 - 2 g_i.g_j )``.
139
+ """
140
+ G = coerce_gamma(gamma)
141
+ D = _gamma_distance(G)
142
+ key = str(method).lower()
143
+ if key in ("mds", "cmds"):
144
+ Y, info = _mds(D, n_components=n_components, **kw)
145
+ elif key in ("tsne", "t-sne"):
146
+ Y, info = _tsne(D, n_components=n_components, **kw)
147
+ else:
148
+ raise ValueError(f"gammagram_embedding: unknown method {method!r}")
149
+ info["distance"] = "gammagram"
150
+ return (Y, info) if return_info else Y
151
+
152
+
153
+ def _gamma_distance(G):
154
+ """Euclidean distance between rows of gamma (gamma-gram distance)."""
155
+ G = coerce_gamma(G)
156
+ sq = np.sum(G ** 2, axis=1)
157
+ D2 = sq[:, None] + sq[None, :] - 2.0 * (G @ G.T)
158
+ D2 = np.maximum(D2, 0.0)
159
+ D = np.sqrt(D2)
160
+ np.fill_diagonal(D, 0.0)
161
+ return D
162
+
163
+
164
+ # ============================================================
165
+ # (2) Grassmann / distance based embeddings
166
+ # ============================================================
167
+ def functional_embedding(H=None, C=None, U_list=None, p=None, k=30,
168
+ backend="pca", metric="cosine", n_components=2,
169
+ knn=15, method="laplacian", landmarks=None,
170
+ random_state=0, return_info=False, **_):
171
+ """
172
+ Low-dimensional embedding preserving cell-cell functional proximity on
173
+ the Grassmann manifold.
174
+
175
+ Portable re-implementation of
176
+ ``gotclust.core.grassmann_functional_embedding``: builds (or reuses) the
177
+ Grassmann cost matrix C and embeds it with Laplacian Eigenmaps or
178
+ classical MDS.
179
+
180
+ Parameters
181
+ ----------
182
+ H : ndarray, shape (r, n_cells), optional
183
+ Expression / program-composition matrix. Required unless `C` or
184
+ `U_list` is supplied.
185
+ C : ndarray, shape (n, n), optional
186
+ Precomputed pairwise Grassmann cost matrix.
187
+ U_list : list of ndarray, optional
188
+ Precomputed Grassmann points. If given without `C`, C is built.
189
+ p : int, optional
190
+ Subspace dimension (needed when building C from U_list).
191
+ k, backend, metric : subspace construction (only used via grassmann-ot
192
+ when `H` is given and `C` is not).
193
+ n_components : int
194
+ knn : int
195
+ Neighbourhood size for the Laplacian backend.
196
+ method : {'laplacian', 'mds'}
197
+ landmarks : int or None
198
+ Landmark count for the MDS backend (n > 5000 recommended).
199
+ random_state : int
200
+
201
+ Returns
202
+ -------
203
+ Y : ndarray, shape (n, n_components)
204
+ """
205
+ if C is None:
206
+ if U_list is not None:
207
+ if p is None:
208
+ raise ValueError("p is required when building C from U_list")
209
+ from grassmann_ot import grassmann_cost_matrix
210
+ C = grassmann_cost_matrix(U_list, p=p)
211
+ elif H is not None:
212
+ from grassmann_ot import cells_to_grassmann, grassmann_cost_matrix
213
+ U_list = cells_to_grassmann(H, k=k, p=p if p is not None else 3,
214
+ backend=backend, metric=metric)
215
+ C = grassmann_cost_matrix(U_list, p=p if p is not None else 3)
216
+ else:
217
+ raise ValueError("Provide one of H, U_list, C")
218
+
219
+ C = np.asarray(C, dtype=np.float64)
220
+ key = str(method).lower()
221
+ if key in ("laplacian", "lap", "eigenmaps", "le"):
222
+ Y = laplacian_eigenmaps_from_affinity(C, n_components=n_components,
223
+ knn=knn, normalized=True)
224
+ info = {"backend": "laplacian", "knn": knn}
225
+ elif key in ("mds", "cmds"):
226
+ Y = classical_mds_from_dist(C, n_components=n_components,
227
+ n_landmarks=landmarks,
228
+ random_state=random_state)
229
+ info = {"backend": "mds", "landmarks": landmarks}
230
+ else:
231
+ raise ValueError(f"Unknown functional embedding method: {method!r}")
232
+ info["cost_range"] = (float(C.min()), float(C.max()))
233
+ return (Y, info) if return_info else Y
234
+
235
+
236
+ def mds_embedding(D, n_components=2, landmarks=None, random_state=0,
237
+ return_info=False, **_):
238
+ """Classical MDS on any precomputed distance / cost matrix."""
239
+ Y, info = _mds(np.asarray(D, dtype=np.float64),
240
+ n_components=n_components, n_landmarks=landmarks,
241
+ random_state=random_state)
242
+ return (Y, info) if return_info else Y
243
+
244
+
245
+ def tsne_embedding(D, n_components=2, perplexity=30.0, random_state=0,
246
+ return_info=False, **kw):
247
+ """t-SNE on a precomputed distance / cost matrix."""
248
+ Y, info = _tsne(np.asarray(D, dtype=np.float64),
249
+ n_components=n_components, perplexity=perplexity,
250
+ random_state=random_state, **kw)
251
+ return (Y, info) if return_info else Y
252
+
253
+
254
+ def gotclust_embed(H=None, gamma=None, C=None, U_list=None, p=None,
255
+ method="sinkhorn", n_components=2, return_info=False,
256
+ **kwargs):
257
+ """
258
+ Convenience wrapper.
259
+
260
+ Dispatches to :func:`sinkhorn_embedding` when `gamma` is given, else to
261
+ :func:`functional_embedding`. This mirrors the GOTClust
262
+ ``gotclust_embed`` signature while adding gamma support.
263
+ """
264
+ if gamma is not None:
265
+ return sinkhorn_embedding(gamma, method=method,
266
+ n_components=n_components,
267
+ return_info=return_info, **kwargs)
268
+ return functional_embedding(H=H, C=C, U_list=U_list, p=p,
269
+ n_components=n_components,
270
+ method="laplacian" if method == "sinkhorn"
271
+ else method,
272
+ return_info=return_info, **kwargs)
@@ -0,0 +1,166 @@
1
+ Metadata-Version: 2.4
2
+ Name: gotvis
3
+ Version: 0.1.0
4
+ Summary: Grassmann / Optimal-Transport embeddings for single-cell data (Sinkhorn-gamma aware)
5
+ Author: GOTVis Developers
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/ZengFLab/gotvis
8
+ Project-URL: Documentation, https://github.com/ZengFLab/gotvis#readme
9
+ Project-URL: Repository, https://github.com/ZengFLab/gotvis
10
+ Project-URL: Issues, https://github.com/ZengFLab/gotvis/issues
11
+ Keywords: single-cell,embedding,visualization,grassmann-manifold,optimal-transport,sinkhorn,single-cell-rna-seq,computational-biology
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
23
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
24
+ Classifier: Topic :: Scientific/Engineering :: Visualization
25
+ Classifier: Operating System :: OS Independent
26
+ Requires-Python: >=3.8
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: numpy>=1.20
30
+ Requires-Dist: scipy>=1.6
31
+ Provides-Extra: gotclust
32
+ Requires-Dist: grassmann-ot>=0.3.0; extra == "gotclust"
33
+ Provides-Extra: anndata
34
+ Requires-Dist: anndata>=0.8; extra == "anndata"
35
+ Provides-Extra: plot
36
+ Requires-Dist: matplotlib>=3.3; extra == "plot"
37
+ Requires-Dist: seaborn>=0.11; extra == "plot"
38
+ Provides-Extra: tsne
39
+ Requires-Dist: scikit-learn>=0.24; extra == "tsne"
40
+ Provides-Extra: opentsne
41
+ Requires-Dist: openTSNE>=1.0; extra == "opentsne"
42
+ Provides-Extra: dev
43
+ Requires-Dist: pytest>=7.0; extra == "dev"
44
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
45
+ Requires-Dist: numpy>=1.20; extra == "dev"
46
+ Requires-Dist: scipy>=1.6; extra == "dev"
47
+ Requires-Dist: scikit-learn>=0.24; extra == "dev"
48
+ Requires-Dist: POT>=0.9.0; extra == "dev"
49
+ Provides-Extra: all
50
+ Requires-Dist: anndata>=0.8; extra == "all"
51
+ Requires-Dist: matplotlib>=3.3; extra == "all"
52
+ Requires-Dist: seaborn>=0.11; extra == "all"
53
+ Requires-Dist: scikit-learn>=0.24; extra == "all"
54
+ Requires-Dist: grassmann-ot>=0.3.0; extra == "all"
55
+ Dynamic: license-file
56
+
57
+ # GOTVis
58
+
59
+ **Grassmann / Optimal-Transport embeddings for single-cell data.**
60
+
61
+ GOTVis is the visualisation companion to
62
+ [GOTClust](https://github.com/gotclust/gotclust). It turns the objects
63
+ produced by Grassmann-optimal-transport clustering — above all the
64
+ **Sinkhorn transport plan `gamma`** returned by GSSC — into 2-D / 3-D
65
+ coordinates suitable for plotting, downstream QC and publication figures.
66
+
67
+ ## Why a separate package?
68
+
69
+ GOTClust ships a single functional-proximity embedding
70
+ (`grassmann_functional_embedding`). That embedding is *cell-centric*: it
71
+ preserves Grassmann cost C and says nothing about cluster membership.
72
+ GSSC (Grassmann Sinkhorn Spectral Clustering) introduces a **prototype
73
+ membership matrix `gamma`**, which carries a completely different kind of
74
+ geometry — simplex geometry over prototypes. Rather than overload
75
+ GOTClust's embedding namespace, GOTVis owns that geometry and keeps the
76
+ dependency surface tiny.
77
+
78
+ ## Install
79
+
80
+ ```bash
81
+ pip install gotvis # core: numpy + scipy only
82
+ pip install "gotvis[all]" # + anndata, sklearn, plotting, grassmann-ot
83
+ pip install "gotvis[tsne]" # + scikit-learn TSNE backend
84
+ pip install "gotvis[opentsne]" # + openTSNE backend
85
+ ```
86
+
87
+ ## What's inside
88
+
89
+ | Embedding | Input | Geometry | Cost |
90
+ |---|---|---|---|
91
+ | `sinkhorn_embedding(method="svd")` | gamma | truncated SVD of centred gamma — one axis per membership direction | O(n m²) |
92
+ | `sinkhorn_embedding(method="barycentric")` | gamma | Aitchison ilr / clr on the (m−1)-simplex | O(n m) |
93
+ | `sinkhorn_embedding(method="spectral")` | gamma | Laplacian eigenmaps on ΓΓᵀ / Jensen-Shannon affinity | O(n² m) |
94
+ | `gammagram_embedding()` | gamma | MDS / t-SNE on ‖gᵢ−gⱼ‖ | O(n²) |
95
+ | `functional_embedding()` | H / U_list / C | Laplacian Eigenmaps or classical MDS on Grassmann cost | O(n²) |
96
+ | `mds_embedding()` / `tsne_embedding()` | any distance | generic fallback | O(n³)/O(n²) |
97
+
98
+ ## Quick start
99
+
100
+ ### From a Sinkhorn gamma
101
+
102
+ ```python
103
+ import numpy as np
104
+ import gotvis
105
+
106
+ # gamma: (n_cells, n_prototypes) non-negative soft assignment
107
+ Y = gotvis.sinkhorn_embedding(gamma, method="svd")
108
+ Y = gotvis.sinkhorn_embedding(gamma, method="barycentric", transform="ilr")
109
+ Y, info = gotvis.sinkhorn_embedding(
110
+ gamma, method="spectral", affinity="kl", return_info=True
111
+ )
112
+ ```
113
+
114
+ ### Straight from a GOTClust GSSC run
115
+
116
+ ```python
117
+ from gotclust import grassmann_sinkhorn_clustering
118
+ import gotvis
119
+
120
+ labels, info = grassmann_sinkhorn_clustering(H, n_clusters=5)
121
+
122
+ # info dict is accepted directly — no plumbing
123
+ Y = gotvis.sinkhorn_embedding(info, method="svd")
124
+ Y = gotvis.sinkhorn_embedding(info, method="barycentric")
125
+ ```
126
+
127
+ ### From Grassmann cost (classic functional proximity)
128
+
129
+ ```python
130
+ Y = gotvis.functional_embedding(C=C, method="laplacian", knn=15)
131
+ Y = gotvis.functional_embedding(H=H, p=3, k=30, method="mds",
132
+ landmarks=500)
133
+ ```
134
+
135
+ ### With AnnData
136
+
137
+ ```python
138
+ import gotvis.tools as gt
139
+
140
+ gt.gamma_from_gotclust(info, adata) # adata.uns["gamma"]
141
+ gt.embed(adata, method="svd", key_added="X_gotvis")
142
+ ax = gt.plot_embedding(adata, color="cell_type", basis="X_gotvis")
143
+ ```
144
+
145
+ ## Design notes
146
+
147
+ * **Core is numpy + scipy only.** `anndata`, `matplotlib`, `sklearn`,
148
+ `POT` and `grassmann-ot` are all optional. GOTVis never imports them at
149
+ module scope.
150
+ * **`gamma` is validated everywhere.** Negative, NaN/Inf and degenerate
151
+ shapes raise immediately with an actionable message; all-zero rows are
152
+ tolerated (they embed at the origin).
153
+ * **Sign / rotation ambiguity is handled.** SVD axes are
154
+ sign-stabilised so repeated runs agree.
155
+
156
+ ## Relationship to GOTClust embeddings
157
+
158
+ GOTVis's `functional_embedding` is a **portable re-implementation** of
159
+ `gotclust.grassmann_functional_embedding` — same Laplacian-Eigenmaps /
160
+ MDS semantics, but with no GOTClust import required and an optional
161
+ landmark-MDS fast path. The genuinely new content is the whole
162
+ `gamma`-based family, which GOTClust does not provide.
163
+
164
+ ## License
165
+
166
+ MIT
@@ -0,0 +1,11 @@
1
+ gotvis/__init__.py,sha256=ThqXzLdSuGGkaQZ2R0c9YNzHjb5cuoCvapPim_ifAek,2753
2
+ gotvis/_embeddings.py,sha256=9o9LzoIqE4dopLNBWU2-3oSKVwittqxfwvieL4dvZk4,16608
3
+ gotvis/_validate.py,sha256=2iq3W_if5paBbZ3AViAQrvnlfVMF7dXR3L9RwWh7Eew,3481
4
+ gotvis/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
5
+ gotvis/anndata.py,sha256=P7oakH2SGC8kHTeTFu7XBoBdgB83TXV2LiFRfuqClpc,4920
6
+ gotvis/api.py,sha256=9upHjgeMizF3lR5-aeT-VKsHNUxfRlvOfR8M5oU75y4,11332
7
+ gotvis-0.1.0.dist-info/licenses/LICENSE,sha256=erQiwiAusnubmNGFe6XTM0m7e3nhihDN9r4fsv_L1hw,679
8
+ gotvis-0.1.0.dist-info/METADATA,sha256=0mXbab6H94kYJV_kGSKoskjfaNWYDfQK5IyalMsP_0A,6431
9
+ gotvis-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ gotvis-0.1.0.dist-info/top_level.txt,sha256=zgCVkHynCZxgrtuUnOv1mHKSEbh_1M40_twe7gK4Qbw,7
11
+ gotvis-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,15 @@
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.
@@ -0,0 +1 @@
1
+ gotvis