Metadata-Version: 2.5
Name: GOTDiff
Version: 0.2.9
Summary: Differentiation path / trajectory inference via geodesic distance on the Grassmann manifold, with AnnData support.
Project-URL: Homepage, https://github.com/ZengFLab/GOTDiff
Project-URL: Issues, https://github.com/ZengFLab/GOTDiff/issues
Author: GOTDiff Developers
License: MIT
License-File: LICENSE
Keywords: differentiation,grassmann,optimal-transport,pseudotime,single-cell,trajectory-inference
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.9
Requires-Dist: anndata>=0.9
Requires-Dist: grassmann-ot>=0.3.1
Requires-Dist: numpy>=1.24
Requires-Dist: scanpy>=1.9
Requires-Dist: scikit-learn>=1.3
Requires-Dist: scipy>=1.10
Requires-Dist: torch>=2.0
Provides-Extra: all
Requires-Dist: faiss-gpu; extra == 'all'
Requires-Dist: matplotlib>=3.7; extra == 'all'
Requires-Dist: plotly>=5.18; extra == 'all'
Requires-Dist: seaborn>=0.12; extra == 'all'
Provides-Extra: faiss
Requires-Dist: faiss-cpu; extra == 'faiss'
Provides-Extra: gpu
Requires-Dist: faiss-gpu; extra == 'gpu'
Provides-Extra: plot
Requires-Dist: matplotlib>=3.7; extra == 'plot'
Requires-Dist: seaborn>=0.12; extra == 'plot'
Description-Content-Type: text/markdown

# GOTDiff

> **G**rassmann-**O**ptimal-**T**ransport **Diff**erentiation inference

Single-cell trajectory inference based on the **geodesic distance accumulated
along a differentiation path on the Grassmann manifold**.

---

## Why?

Each cell can be represented by a low-dimensional *subspace* of active
regulatory programs (NMF components, scVI / Harmony loadings, ...).  This
subspace is a point on a Grassmann manifold.  A differentiation trajectory is
therefore a **curve on that manifold**, and the **geodesic distance
accumulated along the curve** is the total amount of regulatory re-wiring a
cell has undergone since the root (most primitive) state.

```
differentiation distance = Σ  d_G( Γ(t), Γ(t + Δt) )
                            t
```

That scalar — the **total "调控变化量"** along the分化路程 — is the central
output of GOTDiff.

---

## Install

```bash
pip install GOTDiff
# with GPU / plotting extras
pip install "GOTDiff[all]"
```

---

## Quick start

### Raw arrays

```python
import numpy as np
from gotdiff import GOTDiff

# H comes from any external tool: NMF, scVI, Harmony, ...
# shape: (n_gene_programs, n_cells)
H = np.random.rand(20, 500)

gd = GOTDiff(k=30, p=3, metric="geodesic", backend="pca")
gd.fit(H)

adata.obs["gotdiff_pseudotime"]     # 伪时间
adata.obs["gotdiff_diff_distance"]  # 分化路程（核心输出）
adata.obsm["X_gotdiff_grassmann"]   # 每个细胞的 Grassmann 坐标
adata.uns["gotdiff"]                # 参数、分支点等元信息

# compare total differentiation "cost" of each lineage
lineage_costs = gd.branch_path_lengths(adata.obs["cell_type"])
```

### AnnData (recommended)

```python
import scanpy as sc
from gotdiff import GOTDiff

adata = sc.read_h5ad("hematopoiesis.h5ad")

# If you already have a factor matrix (NMF / scVI / Harmony), point GOTDiff at it:
gd = GOTDiff(k=30, p=3, backend="faiss")
gd.fit_anndata(adata, use_rep="X_pca")         

# If you don't, GOTDiff runs NMF for you and stores adata.obsm['X_nmf']:
gd.fit_anndata(adata)

# Results are written into adata in-place:
#   adata.obs['gotdiff_pseudotime']
#   adata.obs['gotdiff_diff_distance']
#   adata.obsm['X_gotdiff_grassmann']
#   adata.uns['gotdiff']
```

### Plotting

```python
from gotdiff._plot import scatter, diffusion_landscape

scatter(adata, color="gotdiff_diff_distance", basis="X_umap", show_root=True)
diffusion_landscape(adata, color="cell_type")
```

### One-line tree plot ⭐

`plot_tree()` draws the full differentiation tree in a single call: root (★),
branch points (×), lineages (coloured splines) and leaves.  It runs the
Grassmann kNN shortest-path tree, detects branches by curvature + local
anisotropy, and lays out the skeleton in MDS / UMAP / PCA space.

```python
import scanpy as sc
from gotdiff import GOTDiff

adata = sc.datasets.paul15()      # or any scRNA-seq AnnData
sc.pp.pca(adata, n_comps=50)

gd = GOTDiff(k=30, p=3, backend="pca")
gd.fit_anndata(adata, use_rep="X_pca", n_programs=20)

# ★ one line → saves tree.png
gd.plot_tree(
    adata,
    layout="mds",                # "mds" (default) | "umap" | "pca"
    labels_key="paul15_clusters", # colour cells / label leaves
    show_root=True,
    show_branch_points=True,
    save="tree.png",
)
```

What happens under the hood:

1. **2-D layout** — by default MDS on the Grassmann geodesic distance matrix
   (faithful to the manifold; falls back to UMAP / PCA if `sklearn` is absent).
2. **Branch detection** — local curvature (projected residuals + variance of
   Grassmann neighbour distances) combined with PCA anisotropy; non-maximum
   suppression avoids duplicate points.
3. **Skeleton** — shortest-path tree on the Grassmann kNN graph, then
   root→branch and root→leaf paths are extracted and spline-smoothed.

You can also draw a single lineage curve without the skeleton:

```python
gd.plot_trajectory_curve(
    adata,
    path_idx=0,            # which extracted path (0 = trunk / longest)
    layout="mds",
    color="gotdiff_diff_distance",
    save="lineage.png",
)
```

### Velocity (new in 0.2.0) ⭐

`compute_velocity()` estimates a **tangent-vector velocity** for every cell on
the Grassmann manifold: it tells you how each cell's active regulatory program
(a p-dimensional subspace) is changing and in which direction the cell is
heading.  Think of it as RNA velocity, but operating on **regulatory programs
instead of unspliced counts** — so it is naturally robust to dropout and can
capture non-linear program switches.

```python
import scanpy as sc
from gotdiff import GOTDiff

adata = sc.datasets.paul15()
sc.pp.pca(adata, n_comps=50)

gd = GOTDiff(k=30, p=3, backend="faiss")
gd.fit_anndata(adata, use_rep="X_pca")

# 1. compute the Grassmann-velocity field
velocity = gd.compute_velocity(adata, method="logmap", k=15)

# 2. project tangent vectors onto UMAP (or any 2-D embedding)
vel_umap = gd.project_velocity(adata.obsm["X_umap"], velocity=velocity)

# 3. one-line arrow plot
gd.plot_velocity(adata, basis="X_umap", arrow_scale=1.5, step=2)
```

Under the hood:

1. **Tangent vectors** — for each cell, the log-map vectors to its k nearest
   Grassmann neighbours are weighted by inverse geodesic distance and
   pseudotime direction (`forward_only=True` keeps the field oriented along
   differentiation).  The result lives in the horizontal / tangent space
   `T_U Gr(p, d)`, i.e. `U_i^T velocity[i] = 0`.
2. **Projection** — a local linear map is fitted in each cell's neighbourhood
   so that displacements in Grassmann space become displacements in the
   target embedding (UMAP / MDS / ForceAtlas2); the resulting `(n_cells, 2)`
   array can be drawn directly as arrows.
3. **Speed** — `adata.obs["gotdiff_velocity_speed"]` stores the geodesic
   speed (Frobenius norm of each tangent vector), a measure of how fast the
   regulatory program is being rewritten.

You can also use the functional API directly:

```python
from gotdiff import (
    grassmann_velocity,          # field as (n_cells, d, p) tangent tensors
    GrassmannVelocity,           # sklearn-style estimator
    project_velocity_to_embedding,
    plot_velocity,               # scatter + quiver on any 2-D basis
    plot_velocity_grid,          # one panel per lineage / cluster
)

vel, speed = grassmann_velocity(
    gd.U_list_, pseudotime=gd.pseudotime_, method="logmap", k=15,
)
```

---

## Pipeline

```
   expression matrix / factor matrix (H)
                 │
                 ▼
   cells_to_grassmann  ────────────────  (from grassmann-ot)
   → U_list : (n_cells, d, p)              each cell = a subspace
                 │
                 ▼
   grassmann_pseudotime  ───────────────  intrinsic to Grassmann space
   → pseudotime, root
                 │
                 ▼
   accumulate_geodesic_distance  ──────  ★ the differentiation path length
   → diff_distance for every cell
                 │
                 ▼
   detect_branch_points ───────────────  curvature + local anisotropy
   → branch indices & scores
```

---

## API summary

| Object | Purpose |
|--------|---------|
| `GOTDiff` | Main estimator — `fit(H)` or `fit_anndata(adata)` |
| `GOTDiff.compute_velocity` | ★ Tangent-vector velocity field (0.2.0) |
| `GOTDiff.project_velocity` | Project tangent vectors to a 2-D embedding |
| `GOTDiff.plot_velocity` | Draw velocity arrows on an embedding |
| `grassmann_velocity` | Functional API: field as `(n_cells, d, p)` tensors |
| `GrassmannVelocity` | sklearn-style estimator for the velocity field |
| `project_velocity_to_embedding` | Map tangent vectors to arrow coordinates |
| `plot_velocity` / `plot_velocity_grid` | Velocity visualisation |
| `grassmann_geodesic_distance` | Pairwise geodesic distance on Gr(p, d) |
| `grassmann_chordal_distance` | Cheaper Frobenius projector distance |
| `accumulate_geodesic_distance` | ★ Differentiation path length |
| `grassmann_pseudotime` | Intrinsic Grassmann pseudotime |
| `fit_geodesic_curve` | Smooth curve through Grassmann points |
| `detect_branch_points` | Branch / lineage divergence points |
| `extract_H_from_adata` | Read a factor matrix from AnnData |
| `write_results_to_adata` | Persist every result to AnnData |

---

## Relation to `grassmann-ot`

GOTDiff **builds on** [`grassmann-ot`](https://github.com/ZengFLab/grassmann-ot):
it reuses `cells_to_grassmann` to map cells to Grassmann points, then adds a
full **trajectory-inference layer** on top (pseudotime, path-length, branching,
AnnData I/O, plotting).

---

## License

MIT
