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/_plot.py ADDED
@@ -0,0 +1,175 @@
1
+ """
2
+ Visualisation helpers.
3
+
4
+ Keeps plotting optional (matplotlib / seaborn are not hard dependencies). The
5
+ plotting API is intentionally Scanpy-flavoured so that it feels native to
6
+ single-cell users.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Optional, Tuple
12
+
13
+ import numpy as np
14
+
15
+ try:
16
+ import matplotlib
17
+ import matplotlib.pyplot as plt
18
+ from matplotlib import rcParams
19
+ _HAS_MPL = True
20
+ except ImportError: # pragma: no cover
21
+ _HAS_MPL = False
22
+
23
+
24
+ def _require_mpl():
25
+ if not _HAS_MPL: # pragma: no cover
26
+ raise ImportError("matplotlib is required for plotting.")
27
+
28
+
29
+ def _ensure_2d(embedding: np.ndarray) -> np.ndarray:
30
+ """If the embedding is high-dimensional, reduce it to 2-D with PCA."""
31
+ if embedding.shape[1] == 2:
32
+ return embedding
33
+ # lazy import to avoid a hard sklearn dependency at import time
34
+ from sklearn.decomposition import PCA
35
+ return PCA(n_components=2).fit_transform(embedding)
36
+
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # 2-D scatter coloured by a GOTDiff field
40
+ # ---------------------------------------------------------------------------
41
+
42
+ def scatter(
43
+ adata,
44
+ color: str = "gotdiff_diff_distance",
45
+ basis: str = "X_umap",
46
+ show_root: bool = False,
47
+ root: Optional[int] = None,
48
+ ax: Optional[Any] = None,
49
+ cmap: str = "viridis",
50
+ s: int = 8,
51
+ **kwargs,
52
+ ) -> Any:
53
+ """
54
+ Scatter plot of cells in an embedding, coloured by any GOTDiff field.
55
+
56
+ Parameters
57
+ ----------
58
+ adata : AnnData
59
+ Must contain the embedding in ``adata.obsm[basis]`` and the colour
60
+ field in ``adata.obs[color]``.
61
+ color : str, default 'gotdiff_diff_distance'
62
+ Column of ``adata.obs`` to colour points by.
63
+ basis : str, default 'X_umap'
64
+ Embedding key in ``adata.obsm`` (typically UMAP / TSNE / PHATE).
65
+ show_root : bool, default False
66
+ Highlight the inferred root cell.
67
+ root : int, optional
68
+ Override root index.
69
+ ax : matplotlib.axes.Axes, optional
70
+ Axis to draw into.
71
+ cmap : str, default 'viridis'
72
+ s : int, default 8
73
+ Point size.
74
+ """
75
+ _require_mpl()
76
+ if basis not in adata.obsm:
77
+ raise KeyError(f"Embedding '{basis}' not found in adata.obsm.")
78
+ if color not in adata.obs:
79
+ raise KeyError(f"Colour key '{color}' not found in adata.obs.")
80
+
81
+ coords = _ensure_2d(np.asarray(adata.obsm[basis]))
82
+ values = np.asarray(adata.obs[color])
83
+
84
+ if ax is None:
85
+ _, ax = plt.subplots(figsize=(6, 5.5))
86
+
87
+ sc = ax.scatter(
88
+ coords[:, 0], coords[:, 1], c=values, cmap=cmap, s=s, **kwargs
89
+ )
90
+ plt.colorbar(sc, ax=ax, label=color)
91
+
92
+ if show_root:
93
+ r = root if root is not None else adata.uns.get("gotdiff", {}).get("root")
94
+ if r is not None:
95
+ ax.scatter(
96
+ [coords[r, 0]], [coords[r, 1]],
97
+ c="red", s=120, marker="*", edgecolors="black",
98
+ label="root", zorder=5,
99
+ )
100
+ ax.legend()
101
+ ax.set_xlabel(basis.split("_")[-1].upper() + "1")
102
+ ax.set_ylabel(basis.split("_")[-1].upper() + "2")
103
+ ax.set_aspect("equal")
104
+ return ax
105
+
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # Differentiation "landscape" — pseudotime vs path length
109
+ # ---------------------------------------------------------------------------
110
+
111
+ def diffusion_landscape(
112
+ adata,
113
+ color: Optional[str] = None,
114
+ ax: Optional[Any] = None,
115
+ s: int = 12,
116
+ cmap: str = "tab20",
117
+ ) -> Any:
118
+ """
119
+ Plot accumulated differentiation distance against pseudotime.
120
+
121
+ Each dot is a cell; its vertical position is the total geodesic arc-length
122
+ from the root, i.e. the total regulatory re-wiring needed to reach that
123
+ state. A steep slope means rapid re-programming; a plateau is a stable
124
+ intermediate / progenitor state.
125
+
126
+ Parameters
127
+ ----------
128
+ adata : AnnData
129
+ color : str, optional
130
+ Categorical column of ``adata.obs`` for point colours.
131
+ ax : matplotlib.axes.Axes, optional
132
+ """
133
+ _require_mpl()
134
+ pt = np.asarray(adata.obs["gotdiff_pseudotime"])
135
+ dl = np.asarray(adata.obs["gotdiff_diff_distance"])
136
+ if ax is None:
137
+ _, ax = plt.subplots(figsize=(6, 4.5))
138
+
139
+ if color is not None and color in adata.obs:
140
+ cats = adata.obs[color].astype("category")
141
+ for i, cat in enumerate(cats.categories):
142
+ mask = cats == cat
143
+ ax.scatter(pt[mask], dl[mask], s=s, label=str(cat))
144
+ ax.legend(frameon=False, bbox_to_anchor=(1.02, 1))
145
+ else:
146
+ ax.scatter(pt, dl, s=s, c="#2b6cb0", alpha=0.7)
147
+
148
+ ax.set_xlabel("Pseudotime (Grassmann, normalised)")
149
+ ax.set_ylabel("Differentiation path length\n(accumulated geodesic distance)")
150
+ return ax
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Trajectory curve in a 2-D embedding
155
+ # ---------------------------------------------------------------------------
156
+
157
+ def trajectory_curve(
158
+ adata,
159
+ basis: str = "X_umap",
160
+ ax: Optional[Any] = None,
161
+ color: str = "gotdiff_diff_distance",
162
+ cmap: str = "plasma",
163
+ s: int = 6,
164
+ ) -> Any:
165
+ """
166
+ Draw the inferred geodesic trajectory as a colour-graded line over a
167
+ cell embedding. Requires the fitted curve to have been persisted; if
168
+ not available, it simply draws cells ordered by pseudotime.
169
+ """
170
+ _require_mpl()
171
+ _ = adata # placeholder for curve-persistence support
172
+ raise NotImplementedError(
173
+ "Persisting the fitted geodesic curve in AnnData is planned; for now "
174
+ "use scatter() and colour by gotdiff_pseudotime."
175
+ )
gotdiff/_pseudotime.py ADDED
@@ -0,0 +1,196 @@
1
+ """
2
+ Pseudotime inference from Grassmann geometry.
3
+
4
+ Pipeline
5
+ --------
6
+ 1. Build the pairwise Grassmann-distance matrix (reuse ``grassmann-ot`` for the
7
+ cell-to-subspace construction, then our geodesic-distance routine).
8
+ 2. Build a kNN graph in Grassmann space.
9
+ 3. Infer pseudotime as diffusion pseudotime (DPT) rooted at the cell that is
10
+ globally most peripheral / lowest-total-distance — the biological "root".
11
+
12
+ This keeps the whole pipeline intrinsic to the Grassmann representation; no
13
+ Euclidean PCA is used for pseudotime.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Tuple
20
+
21
+ import numpy as np
22
+ from scipy.sparse import csr_matrix
23
+ from scipy.sparse.csgraph import shortest_path
24
+ from sklearn.neighbors import kneighbors_graph
25
+
26
+ from ._grassmann_dist import grassmann_geodesic_distance_batched
27
+
28
+ Array = np.ndarray
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Root inference
33
+ # ---------------------------------------------------------------------------
34
+
35
+ def infer_root_cell(
36
+ D: Array,
37
+ method: str = "periphery",
38
+ k: int = 10,
39
+ ) -> int:
40
+ """
41
+ Identify the trajectory root from a Grassmann-distance matrix.
42
+
43
+ Parameters
44
+ ----------
45
+ D : ndarray, shape (n_cells, n_cells)
46
+ Pairwise Grassmann-distance matrix.
47
+ method : {'periphery', 'min_degree'}, default 'periphery'
48
+ - 'periphery' : cell with the largest average distance to others
49
+ (the "most extreme / primitive" cell — typical for haematopoiesis).
50
+ - 'min_degree' : cell with the fewest kNN connections; a reasonable
51
+ fallback when the trajectory has a clear starting tip.
52
+ k : int, default 10
53
+ Neighbourhood size for the 'min_degree' method.
54
+
55
+ Returns
56
+ -------
57
+ int
58
+ Index of the inferred root cell.
59
+ """
60
+ n = D.shape[0]
61
+ if method == "periphery":
62
+ return int(np.argmax(D.sum(axis=1)))
63
+ elif method == "min_degree":
64
+ knn = kneighbors_graph(D, n_neighbors=k, mode="connectivity")
65
+ deg = np.asarray(knn.sum(axis=1)).ravel()
66
+ return int(np.argmin(deg))
67
+ else:
68
+ raise ValueError(f"Unknown root method '{method}'.")
69
+
70
+
71
+ # ---------------------------------------------------------------------------
72
+ # Graph-based pseudotime
73
+ # ---------------------------------------------------------------------------
74
+
75
+ def grassmann_pseudotime(
76
+ U_list: Array,
77
+ root_cell: Optional[int] = None,
78
+ k: int = 30,
79
+ metric: str = "geodesic",
80
+ batch_size: int = 256,
81
+ use_shortest_path: bool = True,
82
+ ) -> Tuple[Array, int]:
83
+ """
84
+ Pseudotime inference intrinsic to Grassmann space.
85
+
86
+ Parameters
87
+ ----------
88
+ U_list : ndarray, shape (n_cells, d, p)
89
+ Grassmann points (one per cell).
90
+ root_cell : int, optional
91
+ Index of the root cell. If None, inferred via
92
+ :func:`infer_root_cell` ('periphery').
93
+ k : int, default 30
94
+ kNN graph connectivity.
95
+ metric : {'geodesic', 'chordal'}, default 'geodesic'
96
+ Grassmann distance for graph construction.
97
+ batch_size : int, default 256
98
+ Mini-batch size for distance computation.
99
+ use_shortest_path : bool, default True
100
+ If True, graph distances are shortest-path distances on the kNN graph
101
+ (robust to outliers). If False, the raw Grassmann distances from the
102
+ root are used directly.
103
+
104
+ Returns
105
+ -------
106
+ pseudotime : ndarray, shape (n_cells,)
107
+ Pseudotime values, normalised to [0, 1].
108
+ root_idx : int
109
+ The root cell that was used.
110
+
111
+ Notes
112
+ -----
113
+ The returned pseudotime is *uncalibrated* (arbitrary unit). For a
114
+ biologically calibrated timescale, feed it to
115
+ :func:`accumulate_geodesic_distance` which returns an actual geodesic
116
+ arc-length (the quantity with physical meaning).
117
+ """
118
+ U_list = np.asarray(U_list)
119
+ n = U_list.shape[0]
120
+
121
+ # pairwise distance matrix
122
+ if metric == "geodesic":
123
+ D = grassmann_geodesic_distance_batched(U_list, batch_size=batch_size)
124
+ else:
125
+ from ._grassmann_dist import grassmann_chordal_distance
126
+ D = grassmann_chordal_distance(U_list)
127
+
128
+ # infer root if needed
129
+ if root_cell is None:
130
+ root_cell = infer_root_cell(D)
131
+ root_cell = int(root_cell)
132
+
133
+ # build symmetric kNN graph
134
+ knn = kneighbors_graph(D, n_neighbors=k, mode="distance", include_self=False)
135
+ graph = (knn + knn.T).tocsr()
136
+
137
+ if use_shortest_path:
138
+ dists = shortest_path(
139
+ graph, directed=False, indices=root_cell, return_predecessors=False
140
+ )
141
+ else:
142
+ dists = D[root_cell].copy()
143
+
144
+ # normalise
145
+ dmax = dists.max()
146
+ if dmax <= 0:
147
+ pseudotime = np.zeros(n)
148
+ else:
149
+ pseudotime = dists / dmax
150
+ return pseudotime, root_cell
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Scikit-learn-style estimator
155
+ # ---------------------------------------------------------------------------
156
+
157
+ @dataclass
158
+ class GrassmannPseudotime:
159
+ """
160
+ Scikit-learn-style estimator wrapping :func:`grassmann_pseudotime`.
161
+
162
+ Parameters
163
+ ----------
164
+ k : int, default 30
165
+ kNN connectivity.
166
+ metric : {'geodesic', 'chordal'}, default 'geodesic'
167
+ root_method : {'periphery', 'min_degree'}, default 'periphery'
168
+ How to pick the root when none is supplied.
169
+ batch_size : int, default 256
170
+ """
171
+
172
+ k: int = 30
173
+ metric: str = "geodesic"
174
+ root_method: str = "periphery"
175
+ batch_size: int = 256
176
+
177
+ def __post_init__(self):
178
+ if self.metric not in {"geodesic", "chordal"}:
179
+ raise ValueError("metric must be 'geodesic' or 'chordal'.")
180
+ if self.root_method not in {"periphery", "min_degree"}:
181
+ raise ValueError("root_method must be 'periphery' or 'min_degree'.")
182
+
183
+ def fit_transform(
184
+ self, U_list: Array, root_cell: Optional[int] = None
185
+ ) -> Tuple[Array, int]:
186
+ pt, root = grassmann_pseudotime(
187
+ U_list,
188
+ root_cell=root_cell,
189
+ k=self.k,
190
+ metric=self.metric,
191
+ batch_size=self.batch_size,
192
+ )
193
+ self.pseudotime_ = pt
194
+ self.root_ = root
195
+ self.U_list_ = np.asarray(U_list)
196
+ return pt, root
gotdiff/_trajectory.py ADDED
@@ -0,0 +1,293 @@
1
+ """
2
+ Trajectory modelling on the Grassmann manifold.
3
+
4
+ Given a sequence of Grassmann points ordered by pseudotime, the total
5
+ **differentiation path length** of cell i is the geodesic distance accumulated
6
+ along the trajectory from the root to cell i:
7
+
8
+ S_i = sum_{t = 1}^{i} d_G(Gamma(t-1), Gamma(t))
9
+
10
+ where Gamma(t) is the Grassmann point of the cell at pseudotime rank t.
11
+ This quantity is the central output of GOTDiff: it measures how much
12
+ regulatory re-wiring a cell has undergone since the primitive state.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ from scipy.interpolate import splprep, splev
22
+
23
+ from ._grassmann_dist import (
24
+ _orthonormalize,
25
+ grassmann_geodesic_distance,
26
+ )
27
+
28
+ Array = np.ndarray
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Path-length accumulation
33
+ # ---------------------------------------------------------------------------
34
+
35
+ def accumulate_geodesic_distance(
36
+ U_list: Array,
37
+ pseudotime: Optional[Array] = None,
38
+ root_idx: Optional[int] = None,
39
+ metric: str = "geodesic",
40
+ ) -> Array:
41
+ """
42
+ Accumulated geodesic distance along a pseudotime-ordered trajectory.
43
+
44
+ Parameters
45
+ ----------
46
+ U_list : ndarray, shape (n_cells, d, p)
47
+ Grassmann points (orthonormal bases). If not already ordered, pass
48
+ `pseudotime` to sort them first.
49
+ pseudotime : ndarray, shape (n_cells,), optional
50
+ Pseudotime values used to order the cells. If None the input order is
51
+ used as-is.
52
+ root_idx : int, optional
53
+ Index (in the *original* array) of the root cell. If None and
54
+ `pseudotime` is given, the cell with the minimum pseudotime is used.
55
+ If `pseudotime` is None too, index 0 is used.
56
+ metric : {'geodesic', 'chordal'}, default 'geodesic'
57
+ Distance used for accumulation.
58
+
59
+ Returns
60
+ -------
61
+ diff_dist : ndarray, shape (n_cells,)
62
+ For every cell, the cumulative geodesic distance from the root along
63
+ the trajectory. The root itself is 0; terminal cells have the
64
+ largest values (total differentiation "cost" to reach that state).
65
+
66
+ Notes
67
+ -----
68
+ Complexity: O(n * p^3) for the pairwise SVDs (p is tiny, so effectively
69
+ linear in n_cells).
70
+ """
71
+ U_list = np.asarray(U_list)
72
+ if U_list.ndim != 3:
73
+ raise ValueError(
74
+ "U_list must have shape (n_cells, d, p); got %s." % (U_list.shape,)
75
+ )
76
+ n = U_list.shape[0]
77
+
78
+ # ---- determine ordering ------------------------------------------------
79
+ if pseudotime is not None:
80
+ pseudotime = np.asarray(pseudotime).reshape(-1)
81
+ if pseudotime.shape[0] != n:
82
+ raise ValueError("pseudotime must have length n_cells.")
83
+ order = np.argsort(pseudotime)
84
+ if root_idx is not None:
85
+ # user-given root overrides pseudotime ordering for the start
86
+ root_rank = int(np.argmin(order == root_idx))
87
+ else:
88
+ root_rank = 0
89
+ else:
90
+ order = np.arange(n)
91
+ root_rank = 0 if root_idx is None else int(root_idx)
92
+
93
+ ordered = U_list[order]
94
+
95
+ # ---- accumulate --------------------------------------------------------
96
+ diff_dist = np.zeros(n, dtype=np.float64)
97
+ for t in range(1, n):
98
+ prev, curr = ordered[t - 1], ordered[t]
99
+ if metric == "geodesic":
100
+ s = np.linalg.svd(
101
+ prev.T @ curr, compute_uv=False, full_matrices=False
102
+ )
103
+ s = np.clip(np.abs(s), 0.0, 1.0 - 1e-14)
104
+ step = np.sqrt(np.sum(np.arccos(s) ** 2))
105
+ else: # chordal
106
+ step = np.sqrt(np.sum((prev @ prev.T - curr @ curr.T) ** 2))
107
+ diff_dist[t] = diff_dist[t - 1] + step
108
+
109
+ # ---- place values back in original cell order ---------------------------
110
+ out = np.empty(n, dtype=np.float64)
111
+ out[order] = diff_dist
112
+ return out
113
+
114
+
115
+ # ---------------------------------------------------------------------------
116
+ # Geodesic-curve fitting (for visualisation / interpolation)
117
+ # ---------------------------------------------------------------------------
118
+
119
+ def fit_geodesic_curve(
120
+ U_list: Array,
121
+ pseudotime: Optional[Array] = None,
122
+ n_nodes: int = 100,
123
+ k_spline: int = 3,
124
+ ) -> Tuple[Array, Array]:
125
+ """
126
+ Fit a smooth curve through Grassmann points via spline interpolation.
127
+
128
+ The bases are first vectorised by flattening their orthonormal columns
129
+ (after a consistent sign flip) and then interpolated with a B-spline in
130
+ ambient space. The result can be re-orthonormalized for evaluation.
131
+
132
+ Parameters
133
+ ----------
134
+ U_list : ndarray, shape (n_cells, d, p)
135
+ Grassmann points.
136
+ pseudotime : ndarray, shape (n_cells,), optional
137
+ Parameter along which to interpolate. If None, uniform spacing is
138
+ used (assumes the input is already trajectory-ordered).
139
+ n_nodes : int, default 100
140
+ Number of points on the fitted curve.
141
+ k_spline : int, default 3
142
+ Spline degree.
143
+
144
+ Returns
145
+ -------
146
+ t_curve : ndarray, shape (n_nodes,)
147
+ Parameter values at which the curve is evaluated.
148
+ curve : ndarray, shape (n_nodes, d, p)
149
+ Orthonormalised curve points — a smooth proxy for the differentiation
150
+ trajectory on the Grassmann manifold.
151
+ """
152
+ U_list = np.asarray(U_list)
153
+ n, d, p = U_list.shape
154
+
155
+ # parameter
156
+ if pseudotime is not None:
157
+ t = np.asarray(pseudotime, dtype=float)
158
+ t = (t - t.min()) / (t.max() - t.min() + 1e-15)
159
+ else:
160
+ t = np.linspace(0.0, 1.0, n)
161
+
162
+ # sign-consistent vectorisation: flip columns whose dot with the previous
163
+ # frame is negative (avoids artificial jumps in the spline)
164
+ frames = U_list.copy().reshape(n, d * p)
165
+ for i in range(1, n):
166
+ dots = frames[i].reshape(d, p) * frames[i - 1].reshape(d, p)
167
+ signs = np.sign(dots.sum(axis=0))
168
+ signs[signs == 0] = 1.0
169
+ frames[i] = (frames[i].reshape(d, p) * signs).reshape(d * p)
170
+
171
+ # spline in ambient space
172
+ try:
173
+ tck, u = splprep(frames.T, u=t, s=0, k=min(k_spline, n - 1))
174
+ t_curve = np.linspace(0.0, 1.0, n_nodes)
175
+ coeffs = np.array(splev(t_curve, tck)) # (d*p, n_nodes)
176
+ except Exception: # fallback: linear interpolation
177
+ t_curve = np.linspace(0.0, 1.0, n_nodes)
178
+ coeffs = np.array([
179
+ np.interp(t_curve, t, frames[:, j]) for j in range(d * p)
180
+ ])
181
+
182
+ # re-orthonormalize every point on the curve
183
+ curve = coeffs.T.reshape(n_nodes, d, p)
184
+ curve = np.stack([_orthonormalize(C) for C in curve], axis=0)
185
+ return t_curve, curve
186
+
187
+
188
+ # ---------------------------------------------------------------------------
189
+ # Scikit-learn-style estimator
190
+ # ---------------------------------------------------------------------------
191
+
192
+ @dataclass
193
+ class GrassmannTrajectory:
194
+ """
195
+ Scikit-learn-style estimator for Grassmann trajectory modelling.
196
+
197
+ Parameters
198
+ ----------
199
+ metric : {'geodesic', 'chordal'}, default 'geodesic'
200
+ Distance used for path-length accumulation.
201
+ n_curve_nodes : int, default 100
202
+ Resolution of the fitted geodesic curve.
203
+ """
204
+
205
+ metric: str = "geodesic"
206
+ n_curve_nodes: int = 100
207
+
208
+ def __post_init__(self):
209
+ if self.metric not in {"geodesic", "chordal"}:
210
+ raise ValueError("metric must be 'geodesic' or 'chordal'.")
211
+
212
+ # ------------------------------------------------------------------
213
+ def fit(
214
+ self,
215
+ U_list: Array,
216
+ pseudotime: Optional[Array] = None,
217
+ root_idx: Optional[int] = None,
218
+ ) -> "GrassmannTrajectory":
219
+ """
220
+ Fit the trajectory and compute differentiation distances.
221
+
222
+ Stores
223
+ ------
224
+ diff_distances_ : ndarray, shape (n_cells,)
225
+ Cumulative geodesic distance from root for every cell.
226
+ order_ : ndarray, shape (n_cells,)
227
+ Pseudotime ordering of cells.
228
+ curve_ : ndarray, shape (n_curve_nodes, d, p) or None
229
+ Fitted geodesic curve (computed on demand).
230
+ """
231
+ U_list = np.asarray(U_list)
232
+ self.n_cells_ = U_list.shape[0]
233
+
234
+ self.diff_distances_ = accumulate_geodesic_distance(
235
+ U_list, pseudotime=pseudotime, root_idx=root_idx, metric=self.metric
236
+ )
237
+ if pseudotime is not None:
238
+ self.order_ = np.argsort(np.asarray(pseudotime))
239
+ else:
240
+ self.order_ = np.arange(self.n_cells_)
241
+
242
+ self.U_list_ = U_list
243
+ self.pseudotime_ = (
244
+ np.asarray(pseudotime) if pseudotime is not None else None
245
+ )
246
+ self.curve_ = None
247
+ return self
248
+
249
+ # ------------------------------------------------------------------
250
+ def geodesic_curve(self) -> Tuple[Array, Array]:
251
+ """Lazily build and return the fitted curve."""
252
+ if self.curve_ is None:
253
+ _, self.curve_ = fit_geodesic_curve(
254
+ self.U_list_[self.order_],
255
+ pseudotime=self.pseudotime_,
256
+ n_nodes=self.n_curve_nodes,
257
+ )
258
+ t = np.linspace(0.0, 1.0, self.n_curve_nodes)
259
+ return t, self.curve_
260
+
261
+ # ------------------------------------------------------------------
262
+ def branch_distances(
263
+ self,
264
+ branch_labels: Array,
265
+ U_list: Optional[Array] = None,
266
+ ) -> dict:
267
+ """
268
+ Total differentiation distance from the root to each branch terminal.
269
+
270
+ Parameters
271
+ ----------
272
+ branch_labels : ndarray, shape (n_cells,)
273
+ Discrete label assigning each cell to a branch / lineage.
274
+ U_list : ndarray, shape (n_cells, d, p), optional
275
+ Required only if :meth:`fit` has not been called yet.
276
+
277
+ Returns
278
+ -------
279
+ dict
280
+ Mapping ``branch_label -> total_geodesic_length`` (float).
281
+ """
282
+ if not hasattr(self, "diff_distances_"):
283
+ if U_list is None:
284
+ raise ValueError("Call fit() first or provide U_list.")
285
+ raise NotImplementedError(
286
+ "Branch distances require a fitted trajectory; call fit() first."
287
+ )
288
+ labels = np.asarray(branch_labels)
289
+ result = {}
290
+ for lab in np.unique(labels):
291
+ mask = labels == lab
292
+ result[int(lab)] = float(self.diff_distances_[mask].max())
293
+ return result