Metadata-Version: 2.4
Name: gotmap
Version: 0.4.0
Summary: Grassmann-subspace Optimal Transport mapping: project query datasets onto a frozen reference atlas.
Author: gotmap developers
License: MIT
Project-URL: Homepage, https://github.com/ZengFLab/gotmap
Keywords: single-cell,scanpy,grassmann,optimal-transport,atlas-mapping,query-to-reference,cell-anchoring
Classifier: Development Status :: 4 - Beta
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
Description-Content-Type: text/markdown
Requires-Dist: numpy>=1.21
Requires-Dist: scipy>=1.8
Requires-Dist: pandas>=1.3
Requires-Dist: scikit-learn>=1.0
Requires-Dist: scanpy>=1.9
Requires-Dist: anndata>=0.8
Requires-Dist: grassmann-ot>=0.3.1
Provides-Extra: gpu
Requires-Dist: torch>=1.12; extra == "gpu"
Requires-Dist: faiss-gpu; extra == "gpu"
Provides-Extra: cpu
Requires-Dist: torch>=1.12; extra == "cpu"
Requires-Dist: faiss-cpu; extra == "cpu"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"

# gotmap

**G**rassmann-subspace **O**ptimal **T**ransport **map**ping: project query
single-cell datasets onto a frozen reference atlas.

gotmap learns a cell-to-cell coupling between a query and a reference by
representing each cell as a point on a Grassmann manifold (a neighbourhood
subspace) and solving an entropic optimal-transport problem over those
points. The output is a shared coordinate representation of the query
(``obsm['X_mapped']``) plus a label transfer, both derived from the same
coupling.

## Install

```bash
pip install gotmap
# with the optional GPU construction backends:
pip install "gotmap[gpu]"
```

gotmap depends on `grassmann-ot>=0.3.1`, `scanpy>=1.9` and `numpy`. The
neural-network transform additionally needs `torch`.

## Quick start

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

ref   = sc.read_h5ad("reference_atlas.h5ad")
query = sc.read_h5ad("query_sample.h5ad")

mapper = GOTMap(ref_adata=ref, use_rep="X_pca", k=30, p=3, reg=0.1,
                backend="pca")      # 'pca' is ~10-20x faster; small precision cost

mapper.fit(ref)                    # 1. build & cache the reference Grassmann points
mapper.fit(query)                  # 2. build the query points + Sinkhorn OT
                                   #    (reference side is NOT recomputed)

mapped = mapper.transform(query, method="knn")
labels = mapper.transfer_labels(query, label_key="cell_type")

print(mapped.obsm["X_mapped"].shape)        # (n_query, n_components)
print(labels.obs["cell_type_predicted"].value_counts())
```

`method="nn"` trains a small MLP on the anchors and the soft coupling, then
projects the query; `method="knn"` (the default) is non-parametric and
sufficient for most evaluation pipelines.

## Why the reference is built once

The expensive operation is constructing the Grassmann subspaces for every
reference cell. Those subspaces depend only on the reference atlas and on
`k`, `p`, `backend` and the coordinate dimension -- never on the query.
`GOTMap.fit(ref)` stores them in `mapper.U_ref` and validates them through
`GrassmannCache`; every later `fit(query)` / `transform(query)` calls
`GrassmannOT.fit_points(U_ref, V_query)` and only builds the query side.

## Using precomputed point lists

A rotate-batch loop needs each batch's subspaces exactly once. Build them
independently and feed the combined reference list directly into the solver:

```python
from grassmann_ot import cells_to_grassmann

all_points = []
for b, adata_b in enumerate(adata_list):
    H = adata_b.obsm["X_pca"].T                 # (dim, n_cells)
    all_points.append(cells_to_grassmann(H, k=30, p=3, backend="pca"))

for held_out in range(len(adata_list)):
    U_ref = [pt for i, pts in enumerate(all_points) if i != held_out
                for pt in pts]
    V_q   = all_points[held_out]

    mapper = GOTMap(ref_adata=ref_atlas, k=30, p=3, reg=0.1)
    mapper.fit_points(U_ref, V_q)               # no subspace construction at all
    mapped = mapper.transform(query_list[held_out], method="knn")
```

`fit_points` is the entry point used internally by
`benchmark_rotate_fast` in `gotmap-benchmark>=0.6.0`.

## Frozen references

`FrozenReference` carries the PCA loadings, gene means and coordinates of an
atlas so an unrelated query can be projected into the same space, with no
reference-side recomputation. As of 0.4.0 it can also carry a
`GrassmannCache`:

```python
from gotmap import GOTMap, FrozenReference

fr = FrozenReference(ref)
fr.attach_grassmann(mapper.U_ref, k=30, p=3, backend="pca")
fr.save("atlas_frozen/")

fr2 = FrozenReference.load("atlas_frozen/")
mapper2 = GOTMap.from_frozen(fr2, k=30, p=3, reg=0.1)
mapped  = mapper2.transform(query, method="knn")
# fr2.has_grassmann() == True  ->  reference Grassmann points are reused
```

## Backends

`cells_to_grassmann` and `GrassmannOT` accept the same `backend` keyword:

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

Extra options: `batch_size`, `subsample_rate`, `inner_backend`, `device`.

## API

### `GOTMap(ref_adata=None, use_rep='X_pca', k=30, p=3, reg=0.1, metric='cosine', backend='batched', ...)`
Mapper constructor. Parameters mirror `GrassmannOT`.

### `.fit(ref)` / `.fit(query)` / `.fit(ref, query)`
Build the reference subspaces and cache them; then build the query subspaces
and solve the coupling. See the docstring for the full dispatch rules.

### `.fit_points(U_list, V_list, ref_adata=None)`
Skip construction entirely and solve directly. `U_list` is one `(k, dim)`
array per reference cell; `V_list` is the same for the query.

### `.transform(query, method='knn', n_neighbors=15, ...)`
Return the mapped query (with `obsm['X_mapped']`) for `method` in
`{'knn', 'nn'}`.

### `.transfer_labels(query, label_key, min_confidence=0.0)`
Vote reference labels through the coupling. Results are stored as
`<label_key>_predicted` and `<label_key>_confidence`.

### `FrozenReference(adata, use_rep='X_pca', ensure_pca=True)`
A reference atlas in a reusable coordinate system.

### `.attach_grassmann(points, k, p, backend)` / `.has_grassmann()`
Add / inspect a serialisable Grassmann cache.

### `.project_query(query)` / `.save(path)` / `.load(path)`
Project an arbitrary query; persist the frozen atlas; restore it (cache
included) in another process.

### `GrassmannCache`
Validated container returned by `.grassmann_cache`. Use
`GrassmannCache.build(H, k, p, backend)` to construct, `.concatenate(other)`
to merge batches and `.save(path)` / `.load(path)` to persist.

## License

MIT
