GOTMap
Query-to-Reference Atlas Mapping via Grassmann Optimal Transport
GOTMap maps query single-cell data into a fixed reference atlas using 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
pip install grassmann-ot scanpy torch
pip install gotmap
Quick start
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
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:
fit(ref)— build and cache the reference Grassmann points. Calltransform(query)afterwards to obtain the coupling.fit(query=query)— reuse the cachedU_refand runfit_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:
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)
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.
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:
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
- Grassmann subspaces — For each cell, a local PCA neighborhood
defines a point on the Grassmann manifold (dimension
p). - Optimal transport — Sinkhorn OT computes a soft coupling
gamma(n_ref × n_query) and hard anchors between reference and query cells. - Mapping — Anchors (+ gamma-sampled soft pairs) supervise a neural network that projects query cells into reference PCA space.
- 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
Metadata
Release files for gotmap 0.3.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| gotmap-0.3.1.tar.gz | 23.2 kB | Without provenance | Details for gotmap-0.3.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| gotmap-0.3.1-py3-none-any.whl | Python 3 | none | any | Details for gotmap-0.3.1-py3-none-any.whl |
Total release size: 47.5 kB
Release files / gotmap-0.3.1.tar.gz
| Download URL | gotmap-0.3.1.tar.gz |
|---|---|
| Size | 23.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
90225d34aeddccfd05b90337cdd2f4e612539f13d378ce7d9e02833e1d2ee649
|
|
BLAKE2b-256 checksum How to use checksums |
2cc8452571280c8b68c8f7ddd1a601fa43b4600aad8f78cf834fda1a8b8ed0d2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.10.18
|
Release files / gotmap-0.3.1-py3-none-any.whl
| Download URL | gotmap-0.3.1-py3-none-any.whl |
|---|---|
| Size | 24.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
24aa1a1f45870eef4fca5a89686fe474f0683240284e9519bb1b139789df8e5f
|
|
BLAKE2b-256 checksum How to use checksums |
6d853c0541f45bf20231c6ec75e2b85c70a4f3b5912284a6749b4774f50739b0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.10.18
|
Security for gotmap 0.3.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.