GOTDiff 0.1.0__tar.gz → 0.1.1__tar.gz
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-0.1.0 → gotdiff-0.1.1}/PKG-INFO +53 -3
- {gotdiff-0.1.0 → gotdiff-0.1.1}/README.md +52 -2
- {gotdiff-0.1.0 → gotdiff-0.1.1}/gotdiff/__init__.py +22 -1
- gotdiff-0.1.1/gotdiff/_branching.py +347 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/gotdiff/_core.py +165 -3
- gotdiff-0.1.1/gotdiff/_plot.py +474 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/gotdiff/_trajectory.py +238 -41
- {gotdiff-0.1.0 → gotdiff-0.1.1}/pyproject.toml +1 -1
- gotdiff-0.1.0/gotdiff/_branching.py +0 -188
- gotdiff-0.1.0/gotdiff/_plot.py +0 -175
- {gotdiff-0.1.0 → gotdiff-0.1.1}/LICENSE +0 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/examples/anndata_example.py +0 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/examples/basic_usage.py +0 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/examples/trajectory_viz.py +0 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/gotdiff/_adata.py +0 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/gotdiff/_grassmann_dist.py +0 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/gotdiff/_pseudotime.py +0 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/tests/conftest.py +0 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/tests/test_anndata.py +0 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/tests/test_core.py +0 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/tests/test_grassmann_dist.py +0 -0
- {gotdiff-0.1.0 → gotdiff-0.1.1}/tests/test_trajectory.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: GOTDiff
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.1
|
|
4
4
|
Summary: Differentiation path / trajectory inference via geodesic distance on the Grassmann manifold, with AnnData support.
|
|
5
5
|
Project-URL: Homepage, https://github.com/ZengFLab/GOTDiff
|
|
6
6
|
Project-URL: Issues, https://github.com/ZengFLab/GOTDiff/issues
|
|
@@ -111,10 +111,10 @@ adata = sc.read_h5ad("hematopoiesis.h5ad")
|
|
|
111
111
|
|
|
112
112
|
# If you already have a factor matrix (NMF / scVI / Harmony), point GOTDiff at it:
|
|
113
113
|
gd = GOTDiff(k=30, p=3, backend="faiss")
|
|
114
|
-
gd.fit_anndata(adata, use_rep="X_pca")
|
|
114
|
+
gd.fit_anndata(adata, use_rep="X_pca")
|
|
115
115
|
|
|
116
116
|
# If you don't, GOTDiff runs NMF for you and stores adata.obsm['X_nmf']:
|
|
117
|
-
gd.fit_anndata(adata
|
|
117
|
+
gd.fit_anndata(adata)
|
|
118
118
|
|
|
119
119
|
# Results are written into adata in-place:
|
|
120
120
|
# adata.obs['gotdiff_pseudotime']
|
|
@@ -132,6 +132,56 @@ scatter(adata, color="gotdiff_diff_distance", basis="X_umap", show_root=True)
|
|
|
132
132
|
diffusion_landscape(adata, color="cell_type")
|
|
133
133
|
```
|
|
134
134
|
|
|
135
|
+
### One-line tree plot ⭐
|
|
136
|
+
|
|
137
|
+
`plot_tree()` draws the full differentiation tree in a single call: root (★),
|
|
138
|
+
branch points (×), lineages (coloured splines) and leaves. It runs the
|
|
139
|
+
Grassmann kNN shortest-path tree, detects branches by curvature + local
|
|
140
|
+
anisotropy, and lays out the skeleton in MDS / UMAP / PCA space.
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
import scanpy as sc
|
|
144
|
+
from gotdiff import GOTDiff
|
|
145
|
+
|
|
146
|
+
adata = sc.datasets.paul15() # or any scRNA-seq AnnData
|
|
147
|
+
sc.pp.pca(adata, n_comps=50)
|
|
148
|
+
|
|
149
|
+
gd = GOTDiff(k=30, p=3, backend="faiss")
|
|
150
|
+
gd.fit_anndata(adata, use_rep="X_pca")
|
|
151
|
+
|
|
152
|
+
# ★ one line → saves tree.png
|
|
153
|
+
gd.plot_tree(
|
|
154
|
+
adata,
|
|
155
|
+
layout="mds", # "mds" (default) | "umap" | "pca"
|
|
156
|
+
labels_key="paul15_clusters", # colour cells / label leaves
|
|
157
|
+
show_root=True,
|
|
158
|
+
show_branch_points=True,
|
|
159
|
+
save="tree.png",
|
|
160
|
+
)
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
What happens under the hood:
|
|
164
|
+
|
|
165
|
+
1. **2-D layout** — by default MDS on the Grassmann geodesic distance matrix
|
|
166
|
+
(faithful to the manifold; falls back to UMAP / PCA if `sklearn` is absent).
|
|
167
|
+
2. **Branch detection** — local curvature (projected residuals + variance of
|
|
168
|
+
Grassmann neighbour distances) combined with PCA anisotropy; non-maximum
|
|
169
|
+
suppression avoids duplicate points.
|
|
170
|
+
3. **Skeleton** — shortest-path tree on the Grassmann kNN graph, then
|
|
171
|
+
root→branch and root→leaf paths are extracted and spline-smoothed.
|
|
172
|
+
|
|
173
|
+
You can also draw a single lineage curve without the skeleton:
|
|
174
|
+
|
|
175
|
+
```python
|
|
176
|
+
gd.plot_trajectory_curve(
|
|
177
|
+
adata,
|
|
178
|
+
path_idx=0, # which extracted path (0 = trunk / longest)
|
|
179
|
+
layout="mds",
|
|
180
|
+
color="gotdiff_diff_distance",
|
|
181
|
+
save="lineage.png",
|
|
182
|
+
)
|
|
183
|
+
```
|
|
184
|
+
|
|
135
185
|
---
|
|
136
186
|
|
|
137
187
|
## Pipeline
|
|
@@ -70,10 +70,10 @@ adata = sc.read_h5ad("hematopoiesis.h5ad")
|
|
|
70
70
|
|
|
71
71
|
# If you already have a factor matrix (NMF / scVI / Harmony), point GOTDiff at it:
|
|
72
72
|
gd = GOTDiff(k=30, p=3, backend="faiss")
|
|
73
|
-
gd.fit_anndata(adata, use_rep="X_pca")
|
|
73
|
+
gd.fit_anndata(adata, use_rep="X_pca")
|
|
74
74
|
|
|
75
75
|
# If you don't, GOTDiff runs NMF for you and stores adata.obsm['X_nmf']:
|
|
76
|
-
gd.fit_anndata(adata
|
|
76
|
+
gd.fit_anndata(adata)
|
|
77
77
|
|
|
78
78
|
# Results are written into adata in-place:
|
|
79
79
|
# adata.obs['gotdiff_pseudotime']
|
|
@@ -91,6 +91,56 @@ scatter(adata, color="gotdiff_diff_distance", basis="X_umap", show_root=True)
|
|
|
91
91
|
diffusion_landscape(adata, color="cell_type")
|
|
92
92
|
```
|
|
93
93
|
|
|
94
|
+
### One-line tree plot ⭐
|
|
95
|
+
|
|
96
|
+
`plot_tree()` draws the full differentiation tree in a single call: root (★),
|
|
97
|
+
branch points (×), lineages (coloured splines) and leaves. It runs the
|
|
98
|
+
Grassmann kNN shortest-path tree, detects branches by curvature + local
|
|
99
|
+
anisotropy, and lays out the skeleton in MDS / UMAP / PCA space.
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
import scanpy as sc
|
|
103
|
+
from gotdiff import GOTDiff
|
|
104
|
+
|
|
105
|
+
adata = sc.datasets.paul15() # or any scRNA-seq AnnData
|
|
106
|
+
sc.pp.pca(adata, n_comps=50)
|
|
107
|
+
|
|
108
|
+
gd = GOTDiff(k=30, p=3, backend="faiss")
|
|
109
|
+
gd.fit_anndata(adata, use_rep="X_pca")
|
|
110
|
+
|
|
111
|
+
# ★ one line → saves tree.png
|
|
112
|
+
gd.plot_tree(
|
|
113
|
+
adata,
|
|
114
|
+
layout="mds", # "mds" (default) | "umap" | "pca"
|
|
115
|
+
labels_key="paul15_clusters", # colour cells / label leaves
|
|
116
|
+
show_root=True,
|
|
117
|
+
show_branch_points=True,
|
|
118
|
+
save="tree.png",
|
|
119
|
+
)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
What happens under the hood:
|
|
123
|
+
|
|
124
|
+
1. **2-D layout** — by default MDS on the Grassmann geodesic distance matrix
|
|
125
|
+
(faithful to the manifold; falls back to UMAP / PCA if `sklearn` is absent).
|
|
126
|
+
2. **Branch detection** — local curvature (projected residuals + variance of
|
|
127
|
+
Grassmann neighbour distances) combined with PCA anisotropy; non-maximum
|
|
128
|
+
suppression avoids duplicate points.
|
|
129
|
+
3. **Skeleton** — shortest-path tree on the Grassmann kNN graph, then
|
|
130
|
+
root→branch and root→leaf paths are extracted and spline-smoothed.
|
|
131
|
+
|
|
132
|
+
You can also draw a single lineage curve without the skeleton:
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
gd.plot_trajectory_curve(
|
|
136
|
+
adata,
|
|
137
|
+
path_idx=0, # which extracted path (0 = trunk / longest)
|
|
138
|
+
layout="mds",
|
|
139
|
+
color="gotdiff_diff_distance",
|
|
140
|
+
save="lineage.png",
|
|
141
|
+
)
|
|
142
|
+
```
|
|
143
|
+
|
|
94
144
|
---
|
|
95
145
|
|
|
96
146
|
## Pipeline
|
|
@@ -29,6 +29,10 @@ from ._trajectory import (
|
|
|
29
29
|
GrassmannTrajectory,
|
|
30
30
|
accumulate_geodesic_distance,
|
|
31
31
|
fit_geodesic_curve,
|
|
32
|
+
grassmann_distance_matrix,
|
|
33
|
+
build_trajectory_tree,
|
|
34
|
+
extract_main_paths,
|
|
35
|
+
landmark_paths,
|
|
32
36
|
)
|
|
33
37
|
from ._pseudotime import (
|
|
34
38
|
grassmann_pseudotime,
|
|
@@ -37,6 +41,13 @@ from ._pseudotime import (
|
|
|
37
41
|
from ._branching import (
|
|
38
42
|
BranchAnalyzer,
|
|
39
43
|
detect_branch_points,
|
|
44
|
+
build_skeleton,
|
|
45
|
+
)
|
|
46
|
+
from ._plot import (
|
|
47
|
+
scatter,
|
|
48
|
+
diffusion_landscape,
|
|
49
|
+
plot_trajectory_curve,
|
|
50
|
+
plot_tree,
|
|
40
51
|
)
|
|
41
52
|
from ._adata import (
|
|
42
53
|
extract_H_from_adata,
|
|
@@ -44,7 +55,7 @@ from ._adata import (
|
|
|
44
55
|
)
|
|
45
56
|
from ._core import GOTDiff
|
|
46
57
|
|
|
47
|
-
__version__ = "0.1.
|
|
58
|
+
__version__ = "0.1.1"
|
|
48
59
|
|
|
49
60
|
__all__ = [
|
|
50
61
|
# top-level estimator
|
|
@@ -58,12 +69,22 @@ __all__ = [
|
|
|
58
69
|
"GrassmannTrajectory",
|
|
59
70
|
"accumulate_geodesic_distance",
|
|
60
71
|
"fit_geodesic_curve",
|
|
72
|
+
"grassmann_distance_matrix",
|
|
73
|
+
"build_trajectory_tree",
|
|
74
|
+
"extract_main_paths",
|
|
75
|
+
"landmark_paths",
|
|
61
76
|
# pseudotime
|
|
62
77
|
"grassmann_pseudotime",
|
|
63
78
|
"infer_root_cell",
|
|
64
79
|
# branching
|
|
65
80
|
"BranchAnalyzer",
|
|
66
81
|
"detect_branch_points",
|
|
82
|
+
"build_skeleton",
|
|
83
|
+
# plotting
|
|
84
|
+
"scatter",
|
|
85
|
+
"diffusion_landscape",
|
|
86
|
+
"plot_trajectory_curve",
|
|
87
|
+
"plot_tree",
|
|
67
88
|
# AnnData I/O
|
|
68
89
|
"extract_H_from_adata",
|
|
69
90
|
"write_results_to_adata",
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Branch-point detection on a Grassmann trajectory.
|
|
3
|
+
|
|
4
|
+
Two complementary signals are used:
|
|
5
|
+
|
|
6
|
+
1. **Local curvature** — cells where the trajectory "bends" sharply in
|
|
7
|
+
Grassmann space are candidate branch points. It is estimated both as
|
|
8
|
+
(a) the variance of projected residuals onto the local tangent space and
|
|
9
|
+
(b) the local variance of Grassmann distances to neighbours, a proxy for
|
|
10
|
+
bi-modality that is cheap to compute in batches.
|
|
11
|
+
2. **Local PCA / covariance anisotropy** — cells whose local neighbourhood
|
|
12
|
+
has multiple dominant directions in Grassmann space (high ratio of the
|
|
13
|
+
second to first local-PCA eigenvalue) indicate where lineages diverge.
|
|
14
|
+
|
|
15
|
+
The two scores are combined into a single branch score; a simple
|
|
16
|
+
threshold + non-maximum-suppression yields a small set of branch points.
|
|
17
|
+
|
|
18
|
+
The module also exposes :func:`build_skeleton`, which turns a fitted
|
|
19
|
+
:class:`GOTDiff` object plus its detected branch points into the
|
|
20
|
+
(root, branches, leaves, edges) structure consumed by
|
|
21
|
+
:meth:`GOTDiff.plot_tree`.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
from sklearn.neighbors import NearestNeighbors
|
|
31
|
+
|
|
32
|
+
Array = np.ndarray
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ---------------------------------------------------------------------------
|
|
36
|
+
# Detection routine
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
def detect_branch_points(
|
|
40
|
+
U_list: Array,
|
|
41
|
+
pseudotime: Optional[Array] = None,
|
|
42
|
+
embedding: Optional[Array] = None,
|
|
43
|
+
k_local: int = 15,
|
|
44
|
+
curvature_weight: float = 0.5,
|
|
45
|
+
anisotropy_weight: float = 0.5,
|
|
46
|
+
threshold: Optional[float] = None,
|
|
47
|
+
use_distance_variance: bool = True,
|
|
48
|
+
min_separation: Optional[int] = None,
|
|
49
|
+
) -> Tuple[Array, Dict[str, Array]]:
|
|
50
|
+
"""
|
|
51
|
+
Detect branch points along a Grassmann trajectory.
|
|
52
|
+
|
|
53
|
+
Parameters
|
|
54
|
+
----------
|
|
55
|
+
U_list : ndarray, shape (n_cells, d, p)
|
|
56
|
+
Grassmann points.
|
|
57
|
+
pseudotime : ndarray, shape (n_cells,), optional
|
|
58
|
+
Used to rank candidates and to set the non-maximum-suppression
|
|
59
|
+
spacing. Detection itself is intrinsic.
|
|
60
|
+
embedding : ndarray, shape (n_cells, d_emb), optional
|
|
61
|
+
Low-dimensional coordinates used for the local-PCA anisotropy
|
|
62
|
+
estimate. Recommended: the vectorised Grassmann coordinates
|
|
63
|
+
(``X_gotdiff_grassmann``) reduced with PCA/MDS. If None, the
|
|
64
|
+
flattened Grassmann frames are used directly (slower / noisier).
|
|
65
|
+
k_local : int, default 15
|
|
66
|
+
Neighbourhood size for curvature and local-PCA estimates.
|
|
67
|
+
curvature_weight, anisotropy_weight : float
|
|
68
|
+
Convex-combination weights (automatically renormalised to sum to 1).
|
|
69
|
+
threshold : float, optional
|
|
70
|
+
Minimum combined score to keep a point. If None, points in the
|
|
71
|
+
upper decile are returned.
|
|
72
|
+
use_distance_variance : bool, default True
|
|
73
|
+
Include the local-Grassmann-distance-variance term in curvature.
|
|
74
|
+
min_separation : int, optional
|
|
75
|
+
Minimum separation (in pseudotime rank) between kept branch points.
|
|
76
|
+
Defaults to ``k_local``.
|
|
77
|
+
|
|
78
|
+
Returns
|
|
79
|
+
-------
|
|
80
|
+
branch_indices : ndarray, shape (n_branch,)
|
|
81
|
+
Indices of detected branch-point cells.
|
|
82
|
+
scores : dict
|
|
83
|
+
Mapping of score arrays, each of shape (n_cells,):
|
|
84
|
+
``'curvature'``, ``'anisotropy'``, ``'combined'``.
|
|
85
|
+
"""
|
|
86
|
+
U_list = np.asarray(U_list)
|
|
87
|
+
n, d, p = U_list.shape
|
|
88
|
+
|
|
89
|
+
flat = U_list.reshape(n, d * p)
|
|
90
|
+
if embedding is None:
|
|
91
|
+
embedding = flat
|
|
92
|
+
embedding = np.asarray(embedding)
|
|
93
|
+
|
|
94
|
+
k_local = min(k_local, n - 1)
|
|
95
|
+
nbrs = NearestNeighbors(n_neighbors=k_local + 1, metric="euclidean").fit(embedding)
|
|
96
|
+
_, idx = nbrs.kneighbors(embedding) # (n, k_local+1)
|
|
97
|
+
|
|
98
|
+
# ---- curvature estimate (a): projected residual -----------------------
|
|
99
|
+
Pi_all = flat @ flat.T # (n, n) Gram; used to build local projectors cheaply
|
|
100
|
+
curv_resid = np.zeros(n)
|
|
101
|
+
for i in range(n):
|
|
102
|
+
Pi = flat[i] @ flat[i].T # rank-p projector (row vector outer)
|
|
103
|
+
nb = idx[i, 1:]
|
|
104
|
+
neighbours = flat[nb]
|
|
105
|
+
resid = neighbours - neighbours @ (flat[i].reshape(-1, 1) @ flat[i].reshape(1, -1))
|
|
106
|
+
curv_resid[i] = float(np.mean(np.sum(resid ** 2, axis=1)))
|
|
107
|
+
|
|
108
|
+
# ---- curvature estimate (b): variance of local Grassmann distances ----
|
|
109
|
+
curv_dist = np.zeros(n)
|
|
110
|
+
if use_distance_variance:
|
|
111
|
+
# squared Grassmann distance via principal angles = Frobenius diff of projectors
|
|
112
|
+
proj = flat[:, None, :] * flat[None, :, :] # placeholder for clarity
|
|
113
|
+
del proj
|
|
114
|
+
for i in range(n):
|
|
115
|
+
nb = idx[i, 1:]
|
|
116
|
+
# ||U_i U_i^T - U_j U_j^T||_F^2 = 2p - 2 tr(U_i^T U_j U_j^T U_i)
|
|
117
|
+
Ui = U_list[i]
|
|
118
|
+
P_i = Ui @ Ui.T
|
|
119
|
+
d_loc = np.zeros(len(nb))
|
|
120
|
+
for m, j in enumerate(nb):
|
|
121
|
+
Uj = U_list[j]
|
|
122
|
+
d_loc[m] = np.sum((P_i - Uj @ Uj.T) ** 2)
|
|
123
|
+
m_loc = d_loc.mean()
|
|
124
|
+
if m_loc > 0:
|
|
125
|
+
curv_dist[i] = d_loc.var() / (m_loc ** 2)
|
|
126
|
+
|
|
127
|
+
curv = 0.5 * (curv_resid / (curv_resid.max() + 1e-15)) + \
|
|
128
|
+
0.5 * (curv_dist / (curv_dist.max() + 1e-15))
|
|
129
|
+
|
|
130
|
+
# ---- anisotropy estimate ---------------------------------------------
|
|
131
|
+
aniso = np.zeros(n)
|
|
132
|
+
for i in range(n):
|
|
133
|
+
nb = idx[i, 1:]
|
|
134
|
+
local = embedding[nb] - embedding[nb].mean(axis=0)
|
|
135
|
+
cov = local.T @ local / max(len(nb) - 1, 1)
|
|
136
|
+
ev = np.linalg.eigvalsh(cov)
|
|
137
|
+
ev = np.sort(ev)
|
|
138
|
+
aniso[i] = ev[-2] / (ev[-1] + 1e-15)
|
|
139
|
+
|
|
140
|
+
# ---- combine ---------------------------------------------------------
|
|
141
|
+
w_sum = curvature_weight + anisotropy_weight
|
|
142
|
+
cw = curvature_weight / w_sum
|
|
143
|
+
aw = anisotropy_weight / w_sum
|
|
144
|
+
curv_n = (curv - curv.min()) / (curv.max() - curv.min() + 1e-15)
|
|
145
|
+
aniso_n = (aniso - aniso.min()) / (aniso.max() - aniso.min() + 1e-15)
|
|
146
|
+
combined = cw * curv_n + aw * aniso_n
|
|
147
|
+
|
|
148
|
+
if threshold is None:
|
|
149
|
+
threshold = np.quantile(combined, 0.9)
|
|
150
|
+
mask = combined >= threshold
|
|
151
|
+
|
|
152
|
+
# ---- non-maximum suppression -----------------------------------------
|
|
153
|
+
if pseudotime is not None:
|
|
154
|
+
pt = np.asarray(pseudotime)
|
|
155
|
+
order = np.argsort(pt)
|
|
156
|
+
else:
|
|
157
|
+
order = np.argsort(combined)[::-1]
|
|
158
|
+
inv = np.empty(n, dtype=int)
|
|
159
|
+
inv[order] = np.arange(n)
|
|
160
|
+
|
|
161
|
+
if min_separation is None:
|
|
162
|
+
min_separation = k_local
|
|
163
|
+
|
|
164
|
+
keep = []
|
|
165
|
+
for c in np.argsort(combined)[::-1]:
|
|
166
|
+
if not mask[c]:
|
|
167
|
+
continue
|
|
168
|
+
if all(abs(inv[c] - inv[k]) >= min_separation for k in keep):
|
|
169
|
+
keep.append(c)
|
|
170
|
+
branch_indices = np.array(sorted(keep), dtype=int)
|
|
171
|
+
|
|
172
|
+
scores = {
|
|
173
|
+
"curvature": curv,
|
|
174
|
+
"anisotropy": aniso,
|
|
175
|
+
"combined": combined,
|
|
176
|
+
}
|
|
177
|
+
return branch_indices, scores
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# ---------------------------------------------------------------------------
|
|
181
|
+
# Skeleton builder
|
|
182
|
+
# ---------------------------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
def build_skeleton(
|
|
185
|
+
adata: Any,
|
|
186
|
+
gd: Any,
|
|
187
|
+
branch_points: Optional[Sequence[int]] = None,
|
|
188
|
+
basis: str = "X_gotdiff_mds",
|
|
189
|
+
knn: int = 10,
|
|
190
|
+
labels_key: Optional[str] = None,
|
|
191
|
+
k_local: int = 15,
|
|
192
|
+
) -> Dict[str, Any]:
|
|
193
|
+
"""
|
|
194
|
+
Construct the (root, branches, leaves, edges) skeleton for plotting.
|
|
195
|
+
|
|
196
|
+
Parameters
|
|
197
|
+
----------
|
|
198
|
+
adata : AnnData
|
|
199
|
+
Must contain 2-D layout coordinates in ``adata.obsm[basis]`` and the
|
|
200
|
+
GOTDiff fields ``gotdiff_pseudotime`` / ``gotdiff_diff_distance`` in
|
|
201
|
+
``adata.obs``.
|
|
202
|
+
gd : GOTDiff
|
|
203
|
+
Fitted estimator (provides ``U_list_`` and ``root_``).
|
|
204
|
+
branch_points : sequence of int, optional
|
|
205
|
+
Pre-detected branch-point indices. If None, falls back to
|
|
206
|
+
``gd.branch_points_``; if that is empty, branch detection is run
|
|
207
|
+
on the fly with default settings.
|
|
208
|
+
basis : str, default 'X_gotdiff_mds'
|
|
209
|
+
Key in ``adata.obsm`` holding the 2-D layout coordinates.
|
|
210
|
+
knn : int, default 10
|
|
211
|
+
kNN graph connectivity for the shortest-path tree.
|
|
212
|
+
labels_key : str, optional
|
|
213
|
+
Categorical ``adata.obs`` column used to colour / name lineages.
|
|
214
|
+
k_local : int, default 15
|
|
215
|
+
Neighbourhood size for on-the-fly branch detection.
|
|
216
|
+
|
|
217
|
+
Returns
|
|
218
|
+
-------
|
|
219
|
+
skeleton : dict with keys
|
|
220
|
+
- ``root`` : int
|
|
221
|
+
- ``branch_points`` : ndarray of ints
|
|
222
|
+
- ``leaves`` : ndarray of ints
|
|
223
|
+
- ``edges`` : list of (parent_idx, child_idx)
|
|
224
|
+
- ``paths`` : dict (name -> ordered ndarray of cell indices)
|
|
225
|
+
- ``coords`` : ndarray, shape (n_cells, 2)
|
|
226
|
+
- ``pseudotime`` : ndarray, shape (n_cells,)
|
|
227
|
+
- ``diff_distance`` : ndarray, shape (n_cells,)
|
|
228
|
+
- ``labels`` : ndarray or None
|
|
229
|
+
- ``basis`` : str
|
|
230
|
+
"""
|
|
231
|
+
if basis not in adata.obsm:
|
|
232
|
+
raise KeyError(
|
|
233
|
+
f"Layout '{basis}' not found in adata.obsm. "
|
|
234
|
+
f"Run the corresponding dimensionality reduction first "
|
|
235
|
+
f"(e.g. MDS/UMAP on the Grassmann distance matrix)."
|
|
236
|
+
)
|
|
237
|
+
coords = np.asarray(adata.obsm[basis])
|
|
238
|
+
if coords.shape[1] != 2:
|
|
239
|
+
from sklearn.decomposition import PCA
|
|
240
|
+
coords = PCA(n_components=2).fit_transform(coords)
|
|
241
|
+
|
|
242
|
+
if branch_points is None:
|
|
243
|
+
branch_points = getattr(gd, "branch_points_", np.array([], dtype=int))
|
|
244
|
+
branch_points = np.asarray(branch_points, dtype=int)
|
|
245
|
+
|
|
246
|
+
# on-the-fly detection if nothing available
|
|
247
|
+
if branch_points.size == 0 and hasattr(gd, "U_list_"):
|
|
248
|
+
U_list = np.asarray(gd.U_list_)
|
|
249
|
+
pt = np.asarray(adata.obs.get("gotdiff_pseudotime"))
|
|
250
|
+
flat = U_list.reshape(U_list.shape[0], -1)
|
|
251
|
+
from sklearn.decomposition import PCA as _PCA
|
|
252
|
+
emb = _PCA(n_components=min(10, flat.shape[1])).fit_transform(flat)
|
|
253
|
+
branch_points, _ = detect_branch_points(
|
|
254
|
+
U_list, pseudotime=pt, embedding=emb, k_local=k_local
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
root = int(getattr(gd, "root_", np.argmin(adata.obs["gotdiff_pseudotime"])))
|
|
258
|
+
|
|
259
|
+
# build tree on Grassmann distance graph
|
|
260
|
+
from ._trajectory import (
|
|
261
|
+
grassmann_distance_matrix,
|
|
262
|
+
build_trajectory_tree,
|
|
263
|
+
extract_main_paths,
|
|
264
|
+
)
|
|
265
|
+
U_list = np.asarray(gd.U_list_)
|
|
266
|
+
D = grassmann_distance_matrix(U_list)
|
|
267
|
+
pred, _ = build_trajectory_tree(D, root_idx=root, k=knn)
|
|
268
|
+
|
|
269
|
+
labels = None
|
|
270
|
+
if labels_key is not None and labels_key in adata.obs:
|
|
271
|
+
labels = np.asarray(adata.obs[labels_key].astype("category").cat.codes)
|
|
272
|
+
|
|
273
|
+
paths = extract_main_paths(pred, branch_indices=branch_points, labels=labels)
|
|
274
|
+
|
|
275
|
+
# edges: parent -> child
|
|
276
|
+
edges = []
|
|
277
|
+
for j, p in enumerate(pred):
|
|
278
|
+
if p != -1:
|
|
279
|
+
edges.append((int(p), int(j)))
|
|
280
|
+
|
|
281
|
+
leaves = np.array(
|
|
282
|
+
sorted({v[-1] for v in paths.values() if len(v) > 0}), dtype=int
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
return {
|
|
286
|
+
"root": root,
|
|
287
|
+
"branch_points": branch_points,
|
|
288
|
+
"leaves": leaves,
|
|
289
|
+
"edges": edges,
|
|
290
|
+
"paths": paths,
|
|
291
|
+
"coords": coords,
|
|
292
|
+
"pseudotime": np.asarray(adata.obs["gotdiff_pseudotime"]).reshape(-1),
|
|
293
|
+
"diff_distance": np.asarray(adata.obs["gotdiff_diff_distance"]).reshape(-1),
|
|
294
|
+
"labels": labels,
|
|
295
|
+
"basis": basis,
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
# ---------------------------------------------------------------------------
|
|
300
|
+
# Scikit-learn-style estimator
|
|
301
|
+
# ---------------------------------------------------------------------------
|
|
302
|
+
|
|
303
|
+
@dataclass
|
|
304
|
+
class BranchAnalyzer:
|
|
305
|
+
"""
|
|
306
|
+
Scikit-learn-style façade for branch-point detection.
|
|
307
|
+
|
|
308
|
+
Parameters
|
|
309
|
+
----------
|
|
310
|
+
k_local : int, default 15
|
|
311
|
+
Neighbourhood size.
|
|
312
|
+
curvature_weight : float, default 0.5
|
|
313
|
+
anisotropy_weight : float, default 0.5
|
|
314
|
+
threshold : float, optional
|
|
315
|
+
Override the default quantile-based threshold.
|
|
316
|
+
embedding : ndarray, optional
|
|
317
|
+
Pre-computed low-dimensional embedding for anisotropy. If None, the
|
|
318
|
+
flattened Grassmann frames are used.
|
|
319
|
+
"""
|
|
320
|
+
|
|
321
|
+
k_local: int = 15
|
|
322
|
+
curvature_weight: float = 0.5
|
|
323
|
+
anisotropy_weight: float = 0.5
|
|
324
|
+
threshold: Optional[float] = None
|
|
325
|
+
embedding: Optional[Array] = None
|
|
326
|
+
|
|
327
|
+
def fit(
|
|
328
|
+
self,
|
|
329
|
+
U_list: Array,
|
|
330
|
+
pseudotime: Optional[Array] = None,
|
|
331
|
+
) -> "BranchAnalyzer":
|
|
332
|
+
self.branch_points_, self.scores_ = detect_branch_points(
|
|
333
|
+
U_list,
|
|
334
|
+
pseudotime=pseudotime,
|
|
335
|
+
embedding=self.embedding,
|
|
336
|
+
k_local=self.k_local,
|
|
337
|
+
curvature_weight=self.curvature_weight,
|
|
338
|
+
anisotropy_weight=self.anisotropy_weight,
|
|
339
|
+
threshold=self.threshold,
|
|
340
|
+
)
|
|
341
|
+
return self
|
|
342
|
+
|
|
343
|
+
def transform(self, branch_labels: Array) -> Dict[int, float]:
|
|
344
|
+
raise NotImplementedError(
|
|
345
|
+
"Branch-path comparison is performed by GrassmannTrajectory."
|
|
346
|
+
"branch_distances()."
|
|
347
|
+
)
|