GOTDiff 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.
gotdiff/_core.py ADDED
@@ -0,0 +1,365 @@
1
+ """
2
+ Top-level estimator: :class:`GOTDiff`.
3
+
4
+ This is the single object an end-user interacts with. It composes:
5
+
6
+ - ``grassmann-ot`` — cell expression -> Grassmann point cloud
7
+ (:func:`cells_to_grassmann`)
8
+ - :mod:`gotdiff._pseudotime` — intrinsic Grassmann pseudotime
9
+ - :mod:`gotdiff._trajectory` — accumulated geodesic path length
10
+ - :mod:`gotdiff._branching` — branch-point detection
11
+ - :mod:`gotdiff._adata` — AnnData I/O
12
+
13
+ Design
14
+ ------
15
+ Follows the scikit-learn estimator protocol (``fit`` / ``fit_transform`` /
16
+ ``get_params`` / ``set_params``) so it slots into existing single-cell
17
+ pipelines and can be tuned with ``GridSearchCV`` if desired.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import Any, Dict, Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+
26
+ try:
27
+ from grassmann_ot import cells_to_grassmann
28
+ except ImportError: # pragma: no cover
29
+ cells_to_grassmann = None
30
+
31
+ from ._adata import (
32
+ BRANCH_KEY,
33
+ DIST_KEY,
34
+ PT_KEY,
35
+ X_KEY,
36
+ extract_H_from_adata,
37
+ write_results_to_adata,
38
+ )
39
+ from ._branching import BranchAnalyzer
40
+ from ._grassmann_dist import _orthonormalize
41
+ from ._pseudotime import grassmann_pseudotime
42
+ from ._trajectory import (
43
+ GrassmannTrajectory,
44
+ accumulate_geodesic_distance,
45
+ )
46
+
47
+ Array = np.ndarray
48
+ MaybeAnnData = Any # either an AnnData instance or None
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Main estimator
53
+ # ---------------------------------------------------------------------------
54
+
55
+ class GOTDiff:
56
+ """
57
+ Differentiation-path inference on the Grassmann manifold.
58
+
59
+ Parameters
60
+ ----------
61
+ k : int, default 30
62
+ Neighbourhood size used when constructing Grassmann points
63
+ (passed to ``cells_to_grassmann``).
64
+ p : int, default 3
65
+ Subspace dimension (passed to ``cells_to_grassmann``).
66
+ metric : {'geodesic', 'chordal'}, default 'geodesic'
67
+ Grassmann distance used for pseudotime and path-length.
68
+ backend : str, default 'pca'
69
+ Construction backend for ``cells_to_grassmann``
70
+ ('loop' | 'batched' | 'pca' | 'subsampling' | 'faiss').
71
+ root_cell : int, optional
72
+ Index of the trajectory root. If None, inferred automatically.
73
+ n_programs : int, default 20
74
+ Number of factors for the automatic NMF fallback in
75
+ :meth:`fit_anndata`.
76
+ knn : int, default 30
77
+ kNN graph connectivity for pseudotime.
78
+ n_curve_nodes : int, default 100
79
+ Resolution of the fitted geodesic trajectory curve.
80
+ batch_size : int, default 256
81
+ Mini-batch size for pairwise Grassmann-distance computations.
82
+
83
+ Attributes
84
+ ----------
85
+ pseudotime_ : ndarray, shape (n_cells,)
86
+ Normalised pseudotime.
87
+ diff_distances_ : ndarray, shape (n_cells,)
88
+ Accumulated geodesic path length from the root — the main GOTDiff
89
+ output ("total regulatory re-wiring since the primitive state").
90
+ U_list_ : ndarray, shape (n_cells, d, p)
91
+ Per-cell Grassmann points (orthonormal bases).
92
+ root_ : int
93
+ Index of the trajectory root.
94
+ branch_points_ : ndarray or None
95
+ Indices of detected branch-point cells.
96
+ """
97
+
98
+ def __init__(
99
+ self,
100
+ k: int = 30,
101
+ p: int = 3,
102
+ metric: str = "geodesic",
103
+ backend: str = "faiss",
104
+ root_cell: Optional[int] = None,
105
+ n_programs: int = 20,
106
+ knn: int = 30,
107
+ n_curve_nodes: int = 100,
108
+ batch_size: int = 256,
109
+ **grassmann_kwargs: Any,
110
+ ) -> None:
111
+ self.k = k
112
+ self.p = p
113
+ self.metric = metric
114
+ self.backend = backend
115
+ self.root_cell = root_cell
116
+ self.n_programs = n_programs
117
+ self.knn = knn
118
+ self.n_curve_nodes = n_curve_nodes
119
+ self.batch_size = batch_size
120
+ self.grassmann_kwargs = grassmann_kwargs
121
+
122
+ if metric not in {"geodesic", "chordal"}:
123
+ raise ValueError("metric must be 'geodesic' or 'chordal'.")
124
+
125
+ # ------------------------------------------------------------------
126
+ # Construction helpers
127
+ # ------------------------------------------------------------------
128
+ def _to_grassmann(self, H: Array) -> Array:
129
+ """Convert a (n_programs, n_cells) factor matrix to Grassmann points."""
130
+ if cells_to_grassmann is None: # pragma: no cover
131
+ raise ImportError(
132
+ "grassmann-ot is required for automatic subspace construction. "
133
+ "Install with `pip install grassmann-ot`."
134
+ )
135
+ return cells_to_grassmann(
136
+ H,
137
+ k=self.k,
138
+ p=self.p,
139
+ backend=self.backend,
140
+ **self.grassmann_kwargs,
141
+ )
142
+
143
+ # ------------------------------------------------------------------
144
+ # Public fit API — raw arrays
145
+ # ------------------------------------------------------------------
146
+ def fit(
147
+ self,
148
+ H: Array,
149
+ pseudotime: Optional[Array] = None,
150
+ root_cell: Optional[int] = None,
151
+ detect_branches: bool = True,
152
+ ) -> "GOTDiff":
153
+ """
154
+ Fit the full GOTDiff model from a factor matrix.
155
+
156
+ Parameters
157
+ ----------
158
+ H : ndarray, shape (n_programs, n_cells)
159
+ Cell-by-subspace representation (rows = factors / gene programs,
160
+ columns = cells). Any external source is acceptable: NMF, scVI,
161
+ Harmony, ICA, topic models, etc.
162
+ pseudotime : ndarray, shape (n_cells,), optional
163
+ Pre-computed pseudotime. If None, inferred intrinsically from
164
+ Grassmann geometry.
165
+ root_cell : int, optional
166
+ Override the root cell.
167
+ detect_branches : bool, default True
168
+ Whether to run branch-point detection.
169
+
170
+ Returns
171
+ -------
172
+ self
173
+ """
174
+ H = np.asarray(H)
175
+ if H.ndim != 2:
176
+ raise ValueError(f"H must be 2-D (n_programs, n_cells); got {H.shape}.")
177
+ n_programs, n_cells = H.shape
178
+ self.n_cells_ = n_cells
179
+
180
+ # ---- 1. Grassmann point cloud -------------------------------------
181
+ U_list = self._to_grassmann(H) # (n_cells, d, p)
182
+ U_list = np.asarray(U_list)
183
+ self.U_list_ = U_list
184
+
185
+ # ---- 2. Pseudotime -------------------------------------------------
186
+ if pseudotime is None:
187
+ pseudotime, root = grassmann_pseudotime(
188
+ U_list,
189
+ root_cell=root_cell if root_cell is not None else self.root_cell,
190
+ k=self.knn,
191
+ metric=self.metric,
192
+ batch_size=self.batch_size,
193
+ )
194
+ else:
195
+ pseudotime = np.asarray(pseudotime).reshape(-1)
196
+ if pseudotime.shape[0] != n_cells:
197
+ raise ValueError("pseudotime length must equal n_cells.")
198
+ if root_cell is None:
199
+ root = int(np.argmin(pseudotime))
200
+ else:
201
+ root = int(root_cell)
202
+
203
+ self.pseudotime_ = pseudotime
204
+ self.root_ = root
205
+
206
+ # ---- 3. Differentiation path length -------------------------------
207
+ self.diff_distances_ = accumulate_geodesic_distance(
208
+ U_list, pseudotime=pseudotime, root_idx=root, metric=self.metric
209
+ )
210
+
211
+ # ---- 4. Geodesic curve (lazy-ready) -------------------------------
212
+ self._trajectory = GrassmannTrajectory(
213
+ metric=self.metric, n_curve_nodes=self.n_curve_nodes
214
+ ).fit(U_list, pseudotime=pseudotime, root_idx=root)
215
+
216
+ # ---- 5. Branches --------------------------------------------------
217
+ if detect_branches:
218
+ self._branch_analyzer = BranchAnalyzer()
219
+ self.branch_points_, self.branch_scores_ = (
220
+ self._branch_analyzer.fit(U_list, pseudotime=pseudotime)
221
+ .branch_points_,
222
+ self._branch_analyzer.scores_,
223
+ )
224
+ else:
225
+ self.branch_points_ = np.array([], dtype=int)
226
+ self.branch_scores_ = None
227
+
228
+ return self
229
+
230
+ # alias kept for scikit-learn convention
231
+ fit_transform = fit
232
+
233
+ # ------------------------------------------------------------------
234
+ # Public fit API — AnnData
235
+ # ------------------------------------------------------------------
236
+ def fit_anndata(
237
+ self,
238
+ adata,
239
+ h_key: Optional[str] = None,
240
+ layer: Optional[str] = None,
241
+ use_rep: Optional[str] = None,
242
+ pseudotime_key: Optional[str] = None,
243
+ root_cell: Optional[int] = None,
244
+ detect_branches: bool = True,
245
+ copy: bool = False,
246
+ ) -> Union[Any, "GOTDiff"]:
247
+ """
248
+ Fit GOTDiff and write every result back into an AnnData object.
249
+
250
+ Parameters
251
+ ----------
252
+ adata : AnnData
253
+ Annotated data matrix.
254
+ h_key, layer, use_rep, n_programs
255
+ Forwarded to :func:`extract_H_from_adata`.
256
+ pseudotime_key : str, optional
257
+ If present and valid, use ``adata.obs[pseudotime_key]`` as the
258
+ pre-computed pseudotime instead of inferring it.
259
+ root_cell : int, optional
260
+ Override the root cell index.
261
+ detect_branches : bool, default True
262
+ copy : bool, default False
263
+ Return a copy of ``adata`` instead of modifying in place.
264
+
265
+ Returns
266
+ -------
267
+ adata : AnnData
268
+ The same object (or a copy) with GOTDiff results stored in
269
+ ``obs``, ``obsm`` and ``uns``.
270
+ """
271
+ if copy:
272
+ adata = adata.copy()
273
+
274
+ H, source = extract_H_from_adata(
275
+ adata,
276
+ h_key=h_key,
277
+ layer=layer,
278
+ use_rep=use_rep,
279
+ n_programs=self.n_programs,
280
+ )
281
+ self.H_source_ = source
282
+
283
+ if pseudotime_key is not None and pseudotime_key in adata.obs:
284
+ pt = np.asarray(adata.obs[pseudotime_key]).reshape(-1)
285
+ else:
286
+ pt = None
287
+
288
+ self.fit(
289
+ H,
290
+ pseudotime=pt,
291
+ root_cell=root_cell,
292
+ detect_branches=detect_branches,
293
+ )
294
+
295
+ write_results_to_adata(
296
+ adata,
297
+ pseudotime=self.pseudotime_,
298
+ diff_distances=self.diff_distances_,
299
+ branch_scores=getattr(self, "branch_scores_", None),
300
+ branch_points=getattr(self, "branch_points_", None),
301
+ U_list=self.U_list_,
302
+ extra={
303
+ "params": self.get_params(),
304
+ "n_cells": self.n_cells_,
305
+ "root": int(self.root_),
306
+ "H_source": source,
307
+ },
308
+ )
309
+ self.adata_ = adata
310
+ return adata
311
+
312
+ # ------------------------------------------------------------------
313
+ # Inspection helpers
314
+ # ------------------------------------------------------------------
315
+ def differentiation_distance(self) -> Array:
316
+ """Return the accumulated geodesic path length for every cell."""
317
+ return self.diff_distances_
318
+
319
+ def branch_path_lengths(self, branch_labels: Array) -> Dict[int, float]:
320
+ """
321
+ Total differentiation distance from the root to each lineage terminal.
322
+
323
+ Parameters
324
+ ----------
325
+ branch_labels : ndarray, shape (n_cells,)
326
+ Discrete assignment of every cell to a branch / lineage.
327
+
328
+ Returns
329
+ -------
330
+ dict
331
+ ``branch_label -> total_geodesic_length``.
332
+ """
333
+ labels = np.asarray(branch_labels)
334
+ result = {}
335
+ for lab in np.unique(labels):
336
+ mask = labels == lab
337
+ result[int(lab)] = float(self.diff_distances_[mask].max())
338
+ return result
339
+
340
+ def geodesic_curve(self) -> Tuple[Array, Array]:
341
+ """Return the fitted smooth trajectory on the Grassmann manifold."""
342
+ return self._trajectory.geodesic_curve()
343
+
344
+ # ------------------------------------------------------------------
345
+ # scikit-learn compatibility
346
+ # ------------------------------------------------------------------
347
+ def get_params(self, deep: bool = True) -> Dict[str, Any]:
348
+ return {
349
+ "k": self.k,
350
+ "p": self.p,
351
+ "metric": self.metric,
352
+ "backend": self.backend,
353
+ "root_cell": self.root_cell,
354
+ "n_programs": self.n_programs,
355
+ "knn": self.knn,
356
+ "n_curve_nodes": self.n_curve_nodes,
357
+ "batch_size": self.batch_size,
358
+ }
359
+
360
+ def set_params(self, **params: Any) -> "GOTDiff":
361
+ for key, value in params.items():
362
+ if not hasattr(self, key):
363
+ raise ValueError(f"Invalid parameter '{key}'.")
364
+ setattr(self, key, value)
365
+ return self
@@ -0,0 +1,324 @@
1
+ """
2
+ Grassmann-manifold distance primitives.
3
+
4
+ A point on the Grassmann manifold Gr(p, d) is the column-space of a
5
+ d-by-p matrix U whose columns are orthonormal (U.T @ U = I_p).
6
+ We support three standard distances:
7
+
8
+ 1. **Geodesic (projection) distance**
9
+ d_G(U, V) = (sum_{i=1}^p arccos^2(s_i))^{1/2}
10
+ where s_i are the singular values of U.T @ V.
11
+ This is the length of the shortest curve on the manifold connecting U and V.
12
+
13
+ 2. **Chordal distance**
14
+ d_C(U, V) = ||U U.T - V V.T||_F = sqrt(2 p - 2 sum_i s_i)
15
+
16
+ 3. **Principal angles**
17
+ theta_i = arccos(s_i) — the canonical angles between the two subspaces.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from dataclasses import dataclass
23
+ from typing import Optional, Tuple
24
+
25
+ import numpy as np
26
+
27
+ # Numerical guards
28
+ _EPS = 1e-12
29
+ _ACOS_CLIP = 1.0 - 1e-14
30
+
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Low-level primitives
34
+ # ---------------------------------------------------------------------------
35
+
36
+ def _orthonormalize(U: np.ndarray) -> np.ndarray:
37
+ """
38
+ Orthonormalize the columns of U via QR.
39
+
40
+ Parameters
41
+ ----------
42
+ U : ndarray, shape (d, p)
43
+ Arbitrary basis of a p-dimensional subspace of R^d.
44
+
45
+ Returns
46
+ -------
47
+ ndarray, shape (d, p)
48
+ Orthonormal basis (Q.T @ Q = I_p). Sign / orientation is arbitrary,
49
+ which is correct for Grassmann (not Stiefel) geometry.
50
+ """
51
+ Q, _ = np.linalg.qr(U, mode="reduced")
52
+ return Q
53
+
54
+
55
+ def principal_angles(U: np.ndarray, V: np.ndarray) -> np.ndarray:
56
+ """
57
+ Principal angles between two subspaces.
58
+
59
+ Parameters
60
+ ----------
61
+ U, V : ndarray, shape (d, p)
62
+ Orthonormal bases of two p-dimensional subspaces.
63
+
64
+ Returns
65
+ -------
66
+ thetas : ndarray, shape (p,)
67
+ Principal angles sorted in [0, pi/2], ascending.
68
+ """
69
+ if U.shape != V.shape:
70
+ raise ValueError(
71
+ f"Subspace bases must have identical shape, got {U.shape} and {V.shape}."
72
+ )
73
+ d, p = U.shape
74
+ if p > d:
75
+ raise ValueError(f"Subspace dimension p={p} cannot exceed ambient d={d}.")
76
+
77
+ # Singular values of U.T @ V lie in [-1, 1]; clip for numerical safety.
78
+ M = U.T @ V
79
+ s = np.linalg.svd(M, compute_uv=False, full_matrices=False)
80
+ s = np.clip(np.abs(s), 0.0, 1.0)
81
+ thetas = np.arccos(s)
82
+ thetas = np.minimum(thetas, np.pi / 2 - _EPS)
83
+ return np.sort(thetas)
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Pairwise distances
88
+ # ---------------------------------------------------------------------------
89
+
90
+ def grassmann_geodesic_distance(
91
+ U: np.ndarray,
92
+ V: np.ndarray = None,
93
+ orthonormal: bool = False,
94
+ ) -> np.ndarray:
95
+ """
96
+ Pairwise geodesic distance on the Grassmann manifold.
97
+
98
+ Parameters
99
+ ----------
100
+ U : ndarray, shape (n, d, p) or (d, p)
101
+ Grassmann points. If 2-D, V must be given.
102
+ V : ndarray, shape (m, d, p), optional
103
+ Second set of points. If omitted, a square pairwise matrix is returned.
104
+ orthonormal : bool, default False
105
+ If False (default), columns of every point are QR-orthonormalized first.
106
+
107
+ Returns
108
+ -------
109
+ D : ndarray
110
+ - If V is None: shape (n, n), D[i, j] = d_G(U[i], U[j]).
111
+ - If V is given: shape (n, m), D[i, j] = d_G(U[i], V[j]).
112
+
113
+ Notes
114
+ -----
115
+ d_G^2(U, V) = sum_i arccos^2(clip(s_i, -1, 1)),
116
+ where s_i are the singular values of U_i.T @ V_j.
117
+ """
118
+ U = np.asarray(U)
119
+ if U.ndim == 2:
120
+ if V is None:
121
+ raise ValueError("For a single (d, p) input, V must be provided.")
122
+ U = U[None, ...]
123
+ if V is not None:
124
+ V = np.asarray(V)
125
+ if V.ndim == 2:
126
+ V = V[None, ...]
127
+ if U.shape[-2:] != V.shape[-2:]:
128
+ raise ValueError(
129
+ f"Subspace shape mismatch: {U.shape[-2:]} vs {V.shape[-2:]}."
130
+ )
131
+
132
+ if not orthonormal:
133
+ U = np.stack([_orthonormalize(Up) for Up in U], axis=0)
134
+ if V is not None:
135
+ V = np.stack([_orthonormalize(Vp) for Vp in V], axis=0)
136
+
137
+ if V is None:
138
+ n = U.shape[0]
139
+ D = np.zeros((n, n), dtype=np.float64)
140
+ for i in range(n):
141
+ Ui = U[i].T # (p, d)
142
+ # M_ij = U_i.T @ U_j -> singular values -> geodesic dist
143
+ M = Ui @ U # (p, d) @ (n, d, p) -> (p, n, p) (via broadcasting)
144
+ # reshape for batched SVD
145
+ Ui_b = Ui.T[None, :, :] # (1, d, p)
146
+ M = np.einsum("ij, kjl -> kil", Ui, U) # (1, p, p) effectively
147
+ # Simpler: loop over j (fine for moderate n)
148
+ for j in range(n):
149
+ if i < j:
150
+ s = np.linalg.svd(U[i].T @ U[j], compute_uv=False, full_matrices=False)
151
+ s = np.clip(np.abs(s), 0.0, _ACOS_CLIP)
152
+ D[i, j] = np.sqrt(np.sum(np.arccos(s) ** 2))
153
+ D[j, i] = D[i, j]
154
+ return D
155
+ else:
156
+ n, m = U.shape[0], V.shape[0]
157
+ D = np.zeros((n, m), dtype=np.float64)
158
+ for i in range(n):
159
+ for j in range(m):
160
+ s = np.linalg.svd(U[i].T @ V[j], compute_uv=False, full_matrices=False)
161
+ s = np.clip(np.abs(s), 0.0, _ACOS_CLIP)
162
+ D[i, j] = np.sqrt(np.sum(np.arccos(s) ** 2))
163
+ return D
164
+
165
+
166
+ def grassmann_chordal_distance(
167
+ U: np.ndarray,
168
+ V: np.ndarray | None = None,
169
+ orthonormal: bool = False,
170
+ ) -> np.ndarray:
171
+ """
172
+ Pairwise chordal distance: ||P_U - P_V||_F where P = U U.T is the projector.
173
+
174
+ This metric is much cheaper than the geodesic (no arccos) and is often a
175
+ good proxy when only relative ordering matters.
176
+ """
177
+ U = np.asarray(U)
178
+ if U.ndim == 2:
179
+ if V is None:
180
+ raise ValueError("For a single (d, p) input, V must be provided.")
181
+ U = U[None, ...]
182
+ if V is not None:
183
+ V = np.asarray(V)
184
+ if V.ndim == 2:
185
+ V = V[None, ...]
186
+
187
+ if not orthonormal:
188
+ U = np.stack([_orthonormalize(Up) for Up in U], axis=0)
189
+ if V is not None:
190
+ V = np.stack([_orthonormalize(Vp) for Vp in V], axis=0)
191
+
192
+ def _proj(X):
193
+ # X: (n, d, p) -> (n, d, d) projectors
194
+ return X @ np.swapaxes(X, -2, -1)
195
+
196
+ P = _proj(U)
197
+ if V is None:
198
+ n = U.shape[0]
199
+ D = np.zeros((n, n), dtype=np.float64)
200
+ for i in range(n):
201
+ for j in range(n):
202
+ if i < j:
203
+ val = np.sqrt(np.sum((P[i] - P[j]) ** 2))
204
+ D[i, j] = val
205
+ D[j, i] = val
206
+ return D
207
+ else:
208
+ P2 = _proj(V)
209
+ n, m = U.shape[0], V.shape[0]
210
+ D = np.zeros((n, m), dtype=np.float64)
211
+ for i in range(n):
212
+ for j in range(m):
213
+ D[i, j] = np.sqrt(np.sum((P[i] - P2[j]) ** 2))
214
+ return D
215
+
216
+
217
+ # ---------------------------------------------------------------------------
218
+ # Vectorised variants (recommended for large n)
219
+ # ---------------------------------------------------------------------------
220
+
221
+ def grassmann_geodesic_distance_batched(
222
+ U: np.ndarray,
223
+ V: np.ndarray | None = None,
224
+ orthonormal: bool = False,
225
+ batch_size: int = 256,
226
+ ) -> np.ndarray:
227
+ """
228
+ Memory-friendly batched version of :func:`grassmann_geodesic_distance`.
229
+
230
+ Processes cells in mini-batches to avoid O(n^2) memory. Falls back to
231
+ the dense loop when the full matrix fits easily in memory.
232
+ """
233
+ U = np.asarray(U)
234
+ if U.ndim == 2:
235
+ U = U[None, ...]
236
+ if V is not None:
237
+ V = np.asarray(V)
238
+ if V.ndim == 2:
239
+ V = V[None, ...]
240
+
241
+ if not orthonormal:
242
+ U = np.stack([_orthonormalize(Up) for Up in U], axis=0)
243
+ if V is not None:
244
+ V = np.stack([_orthonormalize(Vp) for Vp in V], axis=0)
245
+
246
+ if V is None:
247
+ n = U.shape[0]
248
+ D = np.zeros((n, n), dtype=np.float64)
249
+ Ut = U.swapaxes(-2, -1) # (n, p, d)
250
+ for i in range(0, n, batch_size):
251
+ end = min(i + batch_size, n)
252
+ # Ut[i:end]: (B, p, d), U: (n, d, p)
253
+ # -> (B, n, p, p): contract d, keep both p dims
254
+ M = np.einsum("bpd, ndq -> bnpq", Ut[i:end], U)
255
+ # SVD on the last two dims: (B, n, p, p) -> (B, n, p)
256
+ s = np.linalg.svd(M, compute_uv=False, full_matrices=False)
257
+ s = np.clip(np.abs(s), 0.0, _ACOS_CLIP)
258
+ block = np.sqrt(np.sum(np.arccos(s) ** 2, axis=-1)) # (B, n)
259
+ D[i:end, :] = block
260
+ D[:, i:end] = block.T
261
+ np.fill_diagonal(D, 0.0)
262
+ return D
263
+ else:
264
+ n, m = U.shape[0], V.shape[0]
265
+ D = np.zeros((n, m), dtype=np.float64)
266
+ Ut = U.swapaxes(-2, -1) # (n, p, d)
267
+ for i in range(0, n, batch_size):
268
+ end = min(i + batch_size, n)
269
+ # (B, p, d) @ (m, d, p) -> (B, m, p, p)
270
+ M = np.einsum("bpd, mdq -> bmpq", Ut[i:end], V)
271
+ s = np.linalg.svd(M, compute_uv=False, full_matrices=False)
272
+ s = np.clip(np.abs(s), 0.0, _ACOS_CLIP)
273
+ D[i:end, :] = np.sqrt(np.sum(np.arccos(s) ** 2, axis=-1))
274
+ return D
275
+
276
+
277
+ # ---------------------------------------------------------------------------
278
+ # OOP façade
279
+ # ---------------------------------------------------------------------------
280
+
281
+ @dataclass
282
+ class GrassmannDistance:
283
+ """
284
+ Scikit-learn-style façade over the distance primitives.
285
+
286
+ Parameters
287
+ ----------
288
+ metric : {'geodesic', 'chordal'}, default 'geodesic'
289
+ Which Grassmann distance to use.
290
+ batch_size : int, default 256
291
+ Mini-batch size for the batched implementation.
292
+ """
293
+
294
+ metric: str = "geodesic"
295
+ batch_size: int = 256
296
+
297
+ def __post_init__(self):
298
+ if self.metric not in {"geodesic", "chordal"}:
299
+ raise ValueError(
300
+ f"Unknown metric '{self.metric}'. Choose 'geodesic' or 'chordal'."
301
+ )
302
+
303
+ # ------------------------------------------------------------------
304
+ def pairwise(self, U: np.ndarray, V: np.ndarray | None = None) -> np.ndarray:
305
+ """Pairwise distance matrix."""
306
+ if self.metric == "geodesic":
307
+ return grassmann_geodesic_distance_batched(
308
+ U, V, batch_size=self.batch_size
309
+ )
310
+ else:
311
+ return grassmann_chordal_distance(U, V)
312
+
313
+ # ------------------------------------------------------------------
314
+ def single(self, U: np.ndarray, V: np.ndarray) -> float:
315
+ """Distance between exactly two (d, p) points."""
316
+ if U.shape != V.shape:
317
+ raise ValueError(f"Shape mismatch: {U.shape} vs {V.shape}.")
318
+ Qu, Qv = _orthonormalize(U), _orthonormalize(V)
319
+ s = np.linalg.svd(Qu.T @ Qv, compute_uv=False, full_matrices=False)
320
+ s = np.clip(np.abs(s), 0.0, _ACOS_CLIP)
321
+ if self.metric == "geodesic":
322
+ return float(np.sqrt(np.sum(np.arccos(s) ** 2)))
323
+ else:
324
+ return float(np.sqrt(np.sum((Qu @ Qu.T - Qv @ Qv.T) ** 2)))