Metadata-Version: 2.4
Name: gotmap
Version: 0.3.1
Summary: Query-to-Reference Atlas Mapping for Single-Cell Data via Grassmann Optimal Transport
Author: GOTMap Developers
License: MIT
Project-URL: Homepage, https://github.com/ZengFLab/gotmap
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: numpy>=1.21
Requires-Dist: scipy>=1.8
Requires-Dist: torch>=1.12
Requires-Dist: scanpy>=1.9
Requires-Dist: grassmann-ot>=0.3.1
Requires-Dist: scikit-learn>=1.0
Requires-Dist: matplotlib>=3.5

# GOTMap

> **Query-to-Reference Atlas Mapping via Grassmann Optimal Transport**

GOTMap maps query single-cell data into a fixed reference atlas using
[grassmann-ot](https://github.com/ZengFLab/grassmann-ot). It is NOT a
symmetric batch-integration tool — its purpose is to project new samples
into an existing atlas for annotation transfer and quality control.

---

## Why GOTMap?

| | Symmetric Integration | **GOTMap (Query → Atlas)** |
|---|---|---|
| Goal | Remove batch effects | **Map new data into a stable atlas** |
| Symmetry | Bidirectional | **Unidirectional (reference fixed)** |
| Output | Joint embedding | **Query coords in reference space** |
| Labels | Optional | **First-class (transfer + confidence)** |
| Use case | Combining batches | **Clinical / atlas extension / QC** |

---

## Installation

```bash
pip install grassmann-ot scanpy torch
pip install gotmap
```

---

## Quick start

```python
import scanpy as sc
import gotmap
from gotmap.pp import preprocess_reference, preprocess_query
from gotmap.tl import map_query_to_reference, transfer_labels, evaluate_mapping
from gotmap.pl import sanity_check, label_transfer_confidence

# ---- 1. Build & freeze reference atlas ----
ref = sc.read_h5ad("atlas.h5ad")
ref = preprocess_reference(ref, n_comps=50, n_top_genes=2000)

# ---- 2. Preprocess and map query ----
query = sc.read_h5ad("new_sample.h5ad")
query = preprocess_query(query, ref, n_comps=50)

mapped = map_query_to_reference(query, ref, method="nn",
                                hidden_dim=128, epochs=200)

# ---- 3. Transfer labels ----
labelled = transfer_labels(query, ref, label_key="cell_type")

# ---- 4. Evaluate ----
quality = evaluate_mapping(query, ref)
print(quality)  # {'mean_confidence': ..., 'mapping_rate': ..., 'n_anchors': ...}

# ---- 5. Visualize ----
sanity_check(ref, query, mapped_query=mapped, label_key="cell_type")
label_transfer_confidence(labelled, label_key="cell_type")
```

---

## API

### `gotmap.pp` — Preprocessing

| Function | Purpose |
|---|---|
| `preprocess_reference(adata, n_comps=50, ...)` | Full pipeline: normalize → HVG → PCA |
| `preprocess_query(adata, reference, n_comps=50)` | Normalize + project query into **reference PCA space** |
| `normalize_and_hvg(adata, ...)` | Normalize and select HVGs |

### `gotmap.tl` — Tools

| Function | Purpose |
|---|---|
| `map_query_to_reference(query, ref, method="nn", ...)` | Map query → reference space |
| `transfer_labels(query, ref, label_key, ...)` | Transfer labels + confidence |
| `evaluate_mapping(query, ref, ...)` | Mapping quality metrics |

### `gotmap.pl` — Plotting

| Function | Purpose |
|---|---|
| `mapping_scatter(adata, basis="X_gotmap", color=...)` | Scatter of mapped cells |
| `label_transfer_confidence(adata, label_key)` | Confidence histogram + by-label boxplot |
| `embedding(adata, basis=..., color=...)` | Generic embedding plot |
| `sanity_check(ref, query, mapped_query=...)` | Reference / mapped / overlay panels |

### `gotmap.GOTMap` — Low-level class

```python
from gotmap import GOTMap

# Reference Grassmann points are built and cached on the first call to
# fit(); every subsequent query reuses them through
# grassmann_ot.GrassmannOT.fit_points(), so the reference side is never
# recomputed.

mapper = GOTMap(ref_adata=ref, use_rep="X_pca", k=30, p=3, reg=0.1)

# ---- Build the cache (reference only) ----
mapper.fit(ref)                      # reference Grassmann points -> U_ref
len(mapper.U_ref)                    # one point per reference cell

# ---- Map a query ----
mapped_nn  = mapper.transform(query, method="nn",   hidden_dim=128, epochs=200)
mapped_knn = mapper.transform(query, method="knn")  # no reference recomputation

# ---- Or compute the coupling explicitly ----
mapper.fit(query)                    # fit_points(U_ref, V_query)
gamma   = mapper.gamma_              # soft coupling, shape (n_ref, n_query)
anchors = mapper.anchors_            # mutual nearest anchors, shape (K, 2)

# ---- Transfer labels ----
labelled = mapper.transfer_labels(query, label_key="cell_type")

# ---- Quality report ----
quality = mapper.evaluate_mapping(query)
```

**`GOTMap.__init__` parameters**

| Parameter | Default | Meaning |
|---|---|---|
| `ref_adata` | required | Reference atlas (well-annotated, stable) |
| `use_rep` | `"X_pca"` | Key in `obsm` for PCA coordinates |
| `k` | `30` | Neighborhood size for Grassmann construction |
| `p` | `3` | Grassmann subspace dimension |
| `reg` | `0.1` | Sinkhorn entropy regularization |
| `backend` | `"batched"` | Grassmann construction backend |
| `device` | `None` | Torch device (`None` = auto-detect) |

**`fit(ref=None, query=None, V_query=None, ...)`** has two modes:

1. `fit(ref)` — build and cache the reference Grassmann points. Call
   `transform(query)` afterwards to obtain the coupling.
2. `fit(query=query)` — reuse the cached `U_ref` and run
   `fit_points(U_ref, V_query)` for that query.

`V_query` accepts a precomputed list of Grassmann points (the output of
`cells_to_grassmann`) and skips query-side construction.

**`transform(query, method="nn", V_query=None)`** — `method="nn"` uses a
trained neural mapper; `method="knn"` uses non-parametric kNN projection
via anchors and `gamma`. The result carries `obsm["X_mapped"]` (and
`obsm["X_gotmap"]`).

**`transfer_labels(query, label_key, method="weighted_knn", k=50)`** —
transfers `ref_adata.obs[label_key]` into the query.

#### Backends (new in grassmann-ot 0.3.0)

| Backend | Requirements | Use when |
|---|---|---|
| `loop` | numpy | Baseline / debugging |
| `batched` | torch | Default; medium datasets |
| `pca` | scipy, numpy | Want 10–20× speed, accept small precision loss |
| `subsampling` | sklearn, scipy | Very large n, tolerate interpolation |
| `faiss` | faiss + torch | Largest datasets, GPU available |

Pass the backend at construction time:

```python
mapper = GOTMap(ref, use_rep="X_pca", k=30, p=3, reg=0.1, backend="pca")
```

`pca` is recommended for atlas-scale data such as Tabula Sapiens or the
Human Immune Health Atlas, where the reference has more than ~10^5 cells.
Switch to `batched` when you need maximum numerical accuracy.

### `gotmap.FrozenReference` — Lightweight update (scArches-style)

```python
from gotmap import FrozenReference, GOTMap

# ---- Freeze ----
frozen = FrozenReference(ref, use_rep="X_pca")
frozen.save("./frozen_atlas")

# ---- Load (no recomputation) ----
frozen = FrozenReference.load("./frozen_atlas")

# ---- Project any new query into the SAME space ----
query_pca = frozen.project_query(new_query)

# ---- Recover the Grassmann cache and map ----
mapper = GOTMap.from_frozen(frozen, use_rep="X_pca", k=30, p=3, reg=0.1)
mapped = mapper.transform(new_query, method="knn")   # U_ref reused

# ---- Or persist the cache manually ----
import numpy as np
frozen._grassmann_points = mapper.U_ref
frozen.save("./frozen_atlas")

# ---- Extend with new validated cells ----
report = frozen.extend(new_cells, min_new_cells=500, update_ratio=0.1)
# - lightweight: append only (PCA unchanged)
# - full rebuild triggered when new cells exceed threshold

# ---- Full rebuild (call sparingly) ----
frozen.rebuild_reference(full_atlas)
frozen.save("./frozen_atlas_v2")
```

---

## Reusing the reference Grassmann cache

Constructing Grassmann points for the reference is the dominant cost.
GOTMap therefore caches `U_ref` and feeds it to
`GrassmannOT.fit_points()` on every subsequent call, so a
multi-donor atlas is built once and each donor is mapped independently.

```python
import scanpy as sc
from gotmap import GOTMap

atlas = sc.read_h5ad("human_immune_atlas.h5ad")   # e.g. Tabula Sapiens
mapper = GOTMap(atlas, use_rep="X_pca", k=30, p=3, reg=0.1, backend="pca")

mapper.fit(atlas)                                   # 1) build U_ref, once
print("reference Grassmann points:", len(mapper.U_ref))

for donor in atlas.obs["donor_id"].unique():        # 2) map each donor
    query = atlas[atlas.obs["donor_id"] == donor]
    mapped = mapper.transform(query, method="knn")
    print(donor, mapped.obsm["X_mapped"].shape)
```

The cache is parameter-aware: changing `k`, `p`, `backend`, or the
coordinate dimension invalidates it and triggers a rebuild. Changing
`metric` or `reg` does **not** trigger a rebuild, because those
parameters do not affect subspace construction.

You can also feed precomputed points directly and skip construction on
both sides:

```python
from grassmann_ot import cells_to_grassmann

U_ref = cells_to_grassmann(H_atlas.T, k=30, p=3, backend="pca")   # (n_ref,)
V_q   = cells_to_grassmann(H_query.T, k=30, p=3, backend="pca")  # (n_query,)

ot = GrassmannOT(k=30, p=3, reg=0.1)
gamma = ot.fit_points(U_ref, V_q)           # reference points never recomputed
```

---

## How it works

1. **Grassmann subspaces** — For each cell, a local PCA neighborhood
   defines a point on the Grassmann manifold (dimension `p`).
2. **Optimal transport** — Sinkhorn OT computes a soft coupling
   `gamma` (n_ref × n_query) and hard anchors between reference and
   query cells.
3. **Mapping** — Anchors (+ gamma-sampled soft pairs) supervise a
   neural network that projects query cells into reference PCA space.
4. **Label transfer** — Weighted kNN in reference space assigns
   cell-type labels; confidence = max class probability.

GOTMap calls `grassmann-ot` only for coupling (`fit`, `get_hard_anchors`).
All mapping logic is implemented independently.

---

## Requirements

- Python ≥ 3.9
- scanpy ≥ 1.9
- grassmann-ot ≥ 0.3.1
- torch ≥ 1.12
- numpy, scipy, scikit-learn

---

## License

MIT
