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/__init__.py ADDED
@@ -0,0 +1,72 @@
1
+ """
2
+ GOTDiff — Differentiation path / trajectory inference on the Grassmann manifold.
3
+
4
+ Core idea
5
+ ----------
6
+ Single-cell RNA-seq (or any matrix-factorization output) gives, for each cell,
7
+ a low-dimensional **subspace** of active regulatory programs (e.g. NMF components,
8
+ scVI / Harmony loadings). Each such subspace is a point on a Grassmann manifold.
9
+ A differentiation trajectory is therefore a *curve* on that manifold; the
10
+ **geodesic distance accumulated along the curve** is the total amount of
11
+ regulatory re-wiring a cell has undergone since the root (most primitive) state.
12
+
13
+ Public API
14
+ ----------
15
+ - :class:`GOTDiff` — main estimator, supports both raw arrays and AnnData.
16
+ - :func:`grassmann_geodesic_distance` — pairwise geodesic distance between
17
+ Grassmann points.
18
+ - :func:`accumulate_geodesic_distance` — turn a pseudotime-ordered sequence of
19
+ Grassmann points into a vector of differentiation-path lengths.
20
+ """
21
+
22
+ from ._grassmann_dist import (
23
+ GrassmannDistance,
24
+ grassmann_geodesic_distance,
25
+ grassmann_chordal_distance,
26
+ principal_angles,
27
+ )
28
+ from ._trajectory import (
29
+ GrassmannTrajectory,
30
+ accumulate_geodesic_distance,
31
+ fit_geodesic_curve,
32
+ )
33
+ from ._pseudotime import (
34
+ grassmann_pseudotime,
35
+ infer_root_cell,
36
+ )
37
+ from ._branching import (
38
+ BranchAnalyzer,
39
+ detect_branch_points,
40
+ )
41
+ from ._adata import (
42
+ extract_H_from_adata,
43
+ write_results_to_adata,
44
+ )
45
+ from ._core import GOTDiff
46
+
47
+ __version__ = "0.1.0"
48
+
49
+ __all__ = [
50
+ # top-level estimator
51
+ "GOTDiff",
52
+ # Grassmann geometry
53
+ "GrassmannDistance",
54
+ "grassmann_geodesic_distance",
55
+ "grassmann_chordal_distance",
56
+ "principal_angles",
57
+ # trajectory / path-length
58
+ "GrassmannTrajectory",
59
+ "accumulate_geodesic_distance",
60
+ "fit_geodesic_curve",
61
+ # pseudotime
62
+ "grassmann_pseudotime",
63
+ "infer_root_cell",
64
+ # branching
65
+ "BranchAnalyzer",
66
+ "detect_branch_points",
67
+ # AnnData I/O
68
+ "extract_H_from_adata",
69
+ "write_results_to_adata",
70
+ # metadata
71
+ "__version__",
72
+ ]
gotdiff/_adata.py ADDED
@@ -0,0 +1,205 @@
1
+ """
2
+ AnnData integration layer.
3
+
4
+ Responsibilities
5
+ ---------------
6
+ 1. Extract / construct the cell-by-subspace representation ``H`` from an
7
+ :class:`anndata.AnnData` object, with sensible fallbacks:
8
+ - ``adata.varm[key]`` (n_vars, n_cells) -> transpose
9
+ - ``adata.obsm[key]`` (n_cells, n_programs) -> transpose
10
+ - run NMF on ``adata.X`` / ``adata.layers[...]`` -> store in varm
11
+ 2. Write all GOTDiff outputs back into the AnnData object in a self-contained
12
+ way (obs columns, obsm, uns) so results survive a round-trip to disk.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Dict, Optional, Tuple
18
+
19
+ import numpy as np
20
+
21
+ try:
22
+ import anndata
23
+ from anndata import AnnData
24
+ except ImportError: # pragma: no cover
25
+ AnnData = None # type: ignore[assignment]
26
+
27
+ try:
28
+ from sklearn.decomposition import NMF
29
+ except ImportError: # pragma: no cover
30
+ NMF = None
31
+
32
+ from ._grassmann_dist import _orthonormalize
33
+
34
+ Array = np.ndarray
35
+
36
+ # Reserved keys written by GOTDiff
37
+ PT_KEY = "gotdiff_pseudotime"
38
+ DIST_KEY = "gotdiff_diff_distance"
39
+ BRANCH_KEY = "gotdiff_branch_score"
40
+ X_KEY = "X_gotdiff_grassmann"
41
+ UNS_KEY = "gotdiff"
42
+
43
+
44
+ # ---------------------------------------------------------------------------
45
+ # Extraction
46
+ # ---------------------------------------------------------------------------
47
+
48
+ def extract_H_from_adata(
49
+ adata,
50
+ h_key: Optional[str] = None,
51
+ layer: Optional[str] = None,
52
+ use_rep: Optional[str] = None,
53
+ n_programs: int = 20,
54
+ nmf_init: str = "nndsvda",
55
+ nmf_max_iter: int = 400,
56
+ transpose: bool = True,
57
+ ) -> Tuple[Array, str]:
58
+ """
59
+ Obtain a cell-by-subspace representation ``H`` from an AnnData object.
60
+
61
+ Lookup order
62
+ ------------
63
+ 1. If ``h_key`` is given, use it directly (tries ``varm``, then ``obsm``,
64
+ then ``layers``). The returned array is **transposed to**
65
+ ``(n_programs, n_cells)`` unless ``transpose`` is False.
66
+ 2. If ``use_rep`` is given, use ``adata.obsm[use_rep]`` (already
67
+ ``(n_cells, n_components)`` -> transpose).
68
+ 3. Otherwise run NMF on the expression matrix (honouring ``layer``) and
69
+ store the result in ``adata.varm['X_nmf']``.
70
+
71
+ Parameters
72
+ ----------
73
+ adata : AnnData
74
+ Annotated data matrix.
75
+ h_key : str, optional
76
+ Explicit key to read H from.
77
+ layer : str, optional
78
+ Which layer to use for NMF fallback. None = ``adata.X``.
79
+ use_rep : str, optional
80
+ ``adata.obsm`` key (e.g. 'X_scVI', 'X_nmf') used as the factor
81
+ representation.
82
+ n_programs : int, default 20
83
+ Number of factors for the NMF fallback.
84
+ nmf_init : str, default 'nndsvda'
85
+ nmf_max_iter : int, default 400
86
+ transpose : bool, default True
87
+ If True, guarantee output shape ``(n_programs, n_cells)``.
88
+
89
+ Returns
90
+ -------
91
+ H : ndarray, shape (n_programs, n_cells)
92
+ The cell-by-subspace representation.
93
+ source : str
94
+ A short string describing where H came from (for logging).
95
+ """
96
+ if AnnData is None: # pragma: no cover
97
+ raise ImportError("anndata is required for AnnData integration.")
98
+
99
+ # ---- explicit key ------------------------------------------------------
100
+ if h_key is not None:
101
+ for attr in ("varm", "obsm", "layers"):
102
+ store = getattr(adata, attr)
103
+ if h_key in store:
104
+ arr = np.asarray(store[h_key])
105
+ if attr == "obsm":
106
+ arr = arr.T
107
+ if not transpose:
108
+ arr = arr.T
109
+ return arr, f"adata.{attr}['{h_key}']"
110
+
111
+ raise KeyError(
112
+ f"h_key='{h_key}' not found in adata.varm, adata.obsm or adata.layers."
113
+ )
114
+
115
+ # ---- use_rep -----------------------------------------------------------
116
+ if use_rep is not None:
117
+ if use_rep not in adata.obsm:
118
+ raise KeyError(f"use_rep='{use_rep}' not in adata.obsm.")
119
+ arr = np.asarray(adata.obsm[use_rep]).T # -> (n_comp, n_cells)
120
+ if not transpose:
121
+ arr = arr.T
122
+ return arr, f"adata.obsm['{use_rep}']"
123
+
124
+ # ---- NMF fallback ------------------------------------------------------
125
+ if NMF is None: # pragma: no cover
126
+ raise ImportError("scikit-learn is required to run NMF automatically.")
127
+
128
+ X = adata.layers[layer] if layer is not None else adata.X
129
+ if not isinstance(X, np.ndarray):
130
+ X = X.toarray()
131
+ X = X.astype(np.float64)
132
+ # NMF needs non-negative counts; clip defensively
133
+ X = np.clip(X, 0.0, None)
134
+
135
+ model = NMF(
136
+ n_components=n_programs,
137
+ init=nmf_init,
138
+ max_iter=nmf_max_iter,
139
+ random_state=0,
140
+ )
141
+ H = model.fit_transform(X) # (n_cells, n_programs)
142
+ W = model.components_ # (n_programs, n_vars)
143
+ adata.varm["X_nmf"] = W.T # AnnData convention: (n_vars, n)
144
+ adata.obsm["X_nmf"] = H
145
+ if transpose:
146
+ return H.T, "NMF(adata.X)"
147
+ else:
148
+ return H, "NMF(adata.X)"
149
+
150
+
151
+ # ---------------------------------------------------------------------------
152
+ # Writing results back
153
+ # ---------------------------------------------------------------------------
154
+
155
+ def write_results_to_adata(
156
+ adata,
157
+ pseudotime: Array,
158
+ diff_distances: Array,
159
+ branch_scores: Optional[Dict[str, Array]] = None,
160
+ branch_points: Optional[Array] = None,
161
+ U_list: Optional[Array] = None,
162
+ extra: Optional[dict] = None,
163
+ ) -> None:
164
+ """
165
+ Persist every GOTDiff result in a single AnnData object.
166
+
167
+ Writes
168
+ ------
169
+ adata.obs['gotdiff_pseudotime']
170
+ Normalised pseudotime [0, 1].
171
+ adata.obs['gotdiff_diff_distance']
172
+ Accumulated geodesic path length.
173
+ adata.obs['gotdiff_branch_score']
174
+ Combined branch-score (if computed).
175
+ adata.obsm['X_gotdiff_grassmann']
176
+ Per-cell Grassmann coordinates, flattened (n_cells, d*p).
177
+ adata.uns['gotdiff']
178
+ Dictionary with parameters, branch-point indices, and any ``extra``
179
+ metadata passed by the caller.
180
+
181
+ The output is therefore fully self-describing and round-trip safe.
182
+ """
183
+ if AnnData is None: # pragma: no cover
184
+ raise ImportError("anndata is required for AnnData integration.")
185
+
186
+ adata.obs[PT_KEY] = np.asarray(pseudotime)
187
+ adata.obs[DIST_KEY] = np.asarray(diff_distances)
188
+
189
+ uns = {}
190
+ if branch_scores is not None:
191
+ adata.obs[BRANCH_KEY] = np.asarray(branch_scores["combined"])
192
+ uns["branch_scores"] = {
193
+ k: np.asarray(v) for k, v in branch_scores.items()
194
+ }
195
+ if branch_points is not None:
196
+ uns["branch_points"] = np.asarray(branch_points, dtype=int).tolist()
197
+
198
+ if U_list is not None:
199
+ adata.obsm[X_KEY] = U_list.reshape(U_list.shape[0], -1)
200
+
201
+ if extra:
202
+ uns.update(extra)
203
+
204
+ if uns:
205
+ adata.uns[UNS_KEY] = uns
gotdiff/_branching.py ADDED
@@ -0,0 +1,188 @@
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.
8
+ 2. **Local PCA / covariance anisotropy** — cells whose local neighbourhood
9
+ has multiple dominant directions in Grassmann space (high second eigenvalue
10
+ of the local covariance) indicate where lineages diverge.
11
+
12
+ The two scores are combined into a single branch-score; a simple
13
+ threshold + non-maximum-suppression yields a small set of branch points.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+ from typing import Dict, Optional, Tuple
20
+
21
+ import numpy as np
22
+ from sklearn.neighbors import NearestNeighbors
23
+
24
+ from ._grassmann_dist import grassmann_geodesic_distance_batched
25
+
26
+ Array = np.ndarray
27
+
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # Detection routine
31
+ # ---------------------------------------------------------------------------
32
+
33
+ def detect_branch_points(
34
+ U_list: Array,
35
+ pseudotime: Optional[Array] = None,
36
+ k_local: int = 15,
37
+ curvature_weight: float = 0.5,
38
+ anisotropy_weight: float = 0.5,
39
+ threshold: Optional[float] = None,
40
+ batch_size: int = 256,
41
+ ) -> Tuple[Array, Dict[str, Array]]:
42
+ """
43
+ Detect branch points along a Grassmann trajectory.
44
+
45
+ Parameters
46
+ ----------
47
+ U_list : ndarray, shape (n_cells, d, p)
48
+ Grassmann points.
49
+ pseudotime : ndarray, shape (n_cells,), optional
50
+ Used only to rank candidate points; the detection itself is intrinsic.
51
+ k_local : int, default 15
52
+ Neighbourhood size for curvature and local-PCA estimates.
53
+ curvature_weight, anisotropy_weight : float
54
+ Convex-combination weights (automatically renormalised to sum to 1).
55
+ Curvature catches sharp bends; anisotropy catches fan-out / lineage
56
+ divergence.
57
+ threshold : float, optional
58
+ Minimum branch score to keep a point. If None, points in the upper
59
+ decile are returned.
60
+ batch_size : int, default 256
61
+ Mini-batch size for distance calculations.
62
+
63
+ Returns
64
+ -------
65
+ branch_indices : ndarray, shape (n_branch,)
66
+ Indices of detected branch-point cells.
67
+ scores : dict
68
+ Mapping of score arrays, each of shape (n_cells,):
69
+ ``'curvature'``, ``'anisotropy'``, ``'combined'``.
70
+ """
71
+ U_list = np.asarray(U_list)
72
+ n, d, p = U_list.shape
73
+
74
+ # ---- local neighbourhood ---------------------------------------------
75
+ flat = U_list.reshape(n, d * p)
76
+ nbrs = NearestNeighbors(n_neighbors=k_local, metric="euclidean").fit(flat)
77
+ _, idx = nbrs.kneighbors(flat) # (n, k_local)
78
+
79
+ # ---- curvature estimate ----------------------------------------------
80
+ # discrete second derivative of the Grassmann position along its local
81
+ # sequence; use geodesic distance to neighbours as a robust proxy
82
+ curv = np.zeros(n)
83
+ for i in range(n):
84
+ nb = idx[i]
85
+ Pi = U_list[i] @ U_list[i].T # projector
86
+ neighbours = U_list[nb]
87
+ # distances from cell i to its neighbours, projected residual
88
+ resid = neighbours - Pi @ neighbours # (k, d, p)
89
+ resid = resid.reshape(len(nb), -1)
90
+ curv[i] = float(np.mean(np.sum(resid ** 2, axis=1)))
91
+
92
+ # ---- anisotropy estimate ---------------------------------------------
93
+ aniso = np.zeros(n)
94
+ for i in range(n):
95
+ nb = idx[i]
96
+ local = flat[nb] - flat[nb].mean(axis=0) # centre
97
+ cov = local.T @ local / max(len(nb) - 1, 1)
98
+ ev = np.linalg.eigvalsh(cov)
99
+ ev = np.sort(ev)
100
+ # ratio of 2nd / 1st eigenvalue: high = multiple directions
101
+ aniso[i] = ev[-2] / (ev[-1] + 1e-15)
102
+
103
+ # ---- combine ---------------------------------------------------------
104
+ w_sum = curvature_weight + anisotropy_weight
105
+ curvature_weight /= w_sum
106
+ anisotropy_weight /= w_sum
107
+ curv_n = (curv - curv.min()) / (curv.max() - curv.min() + 1e-15)
108
+ aniso_n = (aniso - aniso.min()) / (aniso.max() - aniso.min() + 1e-15)
109
+ combined = curvature_weight * curv_n + anisotropy_weight * aniso_n
110
+
111
+ # ---- threshold --------------------------------------------------------
112
+ if threshold is None:
113
+ threshold = np.quantile(combined, 0.9)
114
+ mask = combined >= threshold
115
+
116
+ # non-maximum suppression in pseudotime order
117
+ if pseudotime is not None:
118
+ order = np.argsort(np.asarray(pseudotime))
119
+ else:
120
+ order = np.argsort(combined)[::-1]
121
+ inv = np.empty(n, dtype=int)
122
+ inv[order] = np.arange(n)
123
+ keep = []
124
+ for c in np.argsort(combined)[::-1]:
125
+ if not mask[c]:
126
+ continue
127
+ if all(abs(inv[c] - inv[k]) > k_local for k in keep):
128
+ keep.append(c)
129
+ branch_indices = np.array(sorted(keep), dtype=int)
130
+
131
+ scores = {
132
+ "curvature": curv,
133
+ "anisotropy": aniso,
134
+ "combined": combined,
135
+ }
136
+ return branch_indices, scores
137
+
138
+
139
+ # ---------------------------------------------------------------------------
140
+ # Scikit-learn-style estimator
141
+ # ---------------------------------------------------------------------------
142
+
143
+ @dataclass
144
+ class BranchAnalyzer:
145
+ """
146
+ Scikit-learn-style façade for branch-point detection.
147
+
148
+ Parameters
149
+ ----------
150
+ k_local : int, default 15
151
+ Neighbourhood size.
152
+ curvature_weight : float, default 0.5
153
+ anisotropy_weight : float, default 0.5
154
+ threshold : float, optional
155
+ Override the default quantile-based threshold.
156
+ """
157
+
158
+ k_local: int = 15
159
+ curvature_weight: float = 0.5
160
+ anisotropy_weight: float = 0.5
161
+ threshold: Optional[float] = None
162
+
163
+ def fit(
164
+ self,
165
+ U_list: Array,
166
+ pseudotime: Optional[Array] = None,
167
+ ) -> "BranchAnalyzer":
168
+ self.branch_points_, self.scores_ = detect_branch_points(
169
+ U_list,
170
+ pseudotime=pseudotime,
171
+ k_local=self.k_local,
172
+ curvature_weight=self.curvature_weight,
173
+ anisotropy_weight=self.anisotropy_weight,
174
+ threshold=self.threshold,
175
+ )
176
+ return self
177
+
178
+ def transform(
179
+ self, branch_labels: Array
180
+ ) -> Dict[int, float]:
181
+ """
182
+ Total path length to each branch terminal (requires a fitted
183
+ :class:`~gotdiff._trajectory.GrassmannTrajectory` upstream).
184
+ """
185
+ raise NotImplementedError(
186
+ "Branch-path comparison is performed by GrassmannTrajectory."
187
+ "branch_distances()."
188
+ )