Skip to main content

gotmap-benchmark

Benchmark pipeline for gotmap — compare query-to-reference atlas mapping methods on real and synthetic single-cell data and get quantitative results and plots out of the box.

Positioning: this benchmark evaluates query → reference mapping quality, not symmetric batch mixing. It is designed for the gotmap use case (map a query onto a fixed atlas), not to compete with integration-tool comparisons.


Install

pip install gotmap-benchmark
# or, with optional baselines:
pip install "gotmap-benchmark[all]"

gotmap-benchmark depends on gotmap>=0.3.1 and grassmann-ot>=0.3.1. Method availability:

Method Extra dependency
gotmap_knn none (gotmap + grassmann-ot)
gotmap_nn torch
scArches scvi-tools
harmony_project harmonypy
BBKNN_align bbknn
direct_knn none

Quick start — fixed reference and query

import scanpy as sc
from gotmap_benchmark import BenchmarkPipeline

adata = sc.datasets.pbmc68k_reduced()
if "X_pca" not in adata.obsm:
    sc.pp.normalize_total(adata); sc.pp.log1p(adata); sc.pp.pca(adata, n_comps=30)

label_key = "bulk_labels" if "bulk_labels" in adata.obs.columns else "louvain"
if label_key not in adata.obs.columns:
    sc.tl.louvain(adata, resolution=0.8, key_added="louvain"); label_key = "louvain"

ref, query = sc.pp.train_test_split(adata, test_size=0.3, random_state=42,
                                    stratify=label_key)

bench = BenchmarkPipeline(ref, query, label_key=label_key, use_rep="X_pca",
                          methods=["gotmap_nn", "gotmap_knn", "direct_knn"])
bench.run()
bench.save_results("benchmark_metrics.csv")
bench.plot(save="benchmark_plot.png")

Quick start — rotate over batches (generic)

For any AnnData, hold out each batch in turn (that batch = query, the rest = reference), then map and evaluate:

import scanpy as sc
from gotmap_benchmark import rotate_batches

adata = sc.read_h5ad("my_data.h5ad")   # any organism / tissue

result = rotate_batches(
    adata,
    batch_key="donor_id",      # or sample, batch, technology, patient, ...
    label_key="cell_type",
    use_rep="X_pca",
    methods=["gotmap_nn", "gotmap_knn", "direct_knn"],
    subsample_reference=20000,
    outdir="./rotate_results",
)
print(result["aggregate"])     # per-method mean across all held-out batches
print(result["summary"])       # one row per (batch, method)

rotate_batches makes no dataset-specific assumptions: it only needs a batch column and (optionally) a cell-type column. It is the general form of the Tabula Sapiens and Human Immune Health Atlas pipelines shipped in earlier versions.

Command line

# fixed reference / query
gotmap-benchmark --ref ref.h5ad --query query.h5ad --label cell_type \
    --use-rep X_pca --methods gotmap_knn direct_knn \
    --output ./results

# rotate over batches (generic)
python -m gotmap_benchmark.rotate_batches \
    --h5ad my_data.h5ad --batch_key donor_id --label_key cell_type \
    --subsample_reference 20000 --output_dir ./results

Or use the bundled script:

python examples/benchmark_general.py \
    --h5ad my_data.h5ad \
    --batch_key donor_id \
    --label_key cell_type \
    --methods gotmap_knn direct_knn \
    --subsample_reference 20000

How gotmap is used (0.3.x lifecycle)

gotmap's reference construction is the expensive part: it builds Grassmann subspaces for every reference cell. BenchmarkPipeline and rotate_batches follow the 0.3.x pattern so that cost is paid once per atlas, not once per query:

from gotmap import GOTMap

# 1) Build and CACHE the reference Grassmann points.
mapper = GOTMap(ref_adata=ref, use_rep="X_pca", k=30, p=3, reg=0.1,
                backend="pca")
mapper.fit(ref)                 # U_ref is cached in mapper.U_ref

# 2) Map queries. The reference side is never recomputed: GrassmannOT
#    reuses U_ref via fit_points(), only the query side is built.
mapper.fit(query)
mapped_knn = mapper.transform(query, method="knn")
mapped_nn  = mapper.transform(query, method="nn",
                              hidden_dim=128, epochs=200)

# 3) Transfer labels. Confidence is written to <label_key>_confidence.
labels = mapper.transfer_labels(query, label_key="cell_type")

BenchmarkPipeline.run() follows the same sequence internally. When the same reference is queried repeatedly (for example, once per held-out batch in rotate_batches), the reference Grassmann cache is reused automatically; the result dictionary records this in info["reference_grassmann_cached"] and rotate_batches reports it at the end.

Reusing a frozen atlas across processes

For very large atlases, build the reference once and serialise it:

from gotmap import GOTMap, FrozenReference

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

fr = FrozenReference(ref, use_rep="X_pca")
fr._grassmann_points = mapper.U_ref   # freeze the cache
fr.save("frozen_atlas/")

# later, in another process:
fr2 = FrozenReference.load("frozen_atlas/")
mapper2 = GOTMap.from_frozen(fr2, use_rep="X_pca", k=30, p=3, reg=0.1)
mapped = mapper2.transform(query, method="knn")

FrozenReference stores the PCA loadings (varm["PCs"]), gene mean and the reference PCA coordinates, so a new query is projected into exactly the same space. Pass frozen= to the run_* wrappers in gotmap_benchmark.methods to skip reference Grassmann construction entirely.


Included methods

Key Method Notes
gotmap_nn gotmap, neural-network mapping anchors + gamma; requires PyTorch
gotmap_knn gotmap, kNN mapping non-parametric
scArches scVI + scArches reference model trained once, then load_query_data
harmony_project Harmony project pure-Python harmonypy, no R needed
BBKNN_align BBKNN symmetric graph correction, query slice extracted
direct_knn kNN (no correction) baseline

Pass method_kwargs for per-method tuning, for example {"gotmap_nn": {"epochs": 300, "hidden_dim": 256}, "scArches": {"max_epochs": 50}}.


Metrics reported

  • Label Transfer Accuracy / Weighted F1 — ground-truth label recovery
  • kNN Preservation (kNP) — overlap of reference-neighbourhoods before/after mapping
  • Cell-type Silhouette — separation of types in mapped space
  • Mean Confidence / Mapping Rate — placement certainty
  • Runtime (s)

When a cell type appears in the query but not the reference (or vice versa), that query cell is excluded from label-transfer metrics rather than being forced into a mismatched class — this is what _common_labels does in rotate_batches, and the same principle applies to one-off runs.


Output

  • benchmark_metrics.csv — one row per method (one-shot mode)
  • benchmark_plot.png — horizontal bar chart per metric
  • batch_<NAME>/benchmark_metrics.csv — one file per held-out batch
  • all_batches_summary.csv — long-form, one row per (batch, method)
  • per_method_mean.csv — per-method mean across batches
  • all_batches_benchmark.png — grouped bars, one panel per metric
  • bench.results_ — full per-method outputs (mapped AnnData, labels, confidence)

Project layout

gotmap-benchmark/
├── pyproject.toml
├── README.md
├── gotmap_benchmark/
│   ├── __init__.py
│   ├── cli.py                 # command-line entry point
│   ├── pipeline.py            # BenchmarkPipeline + plotting
│   ├── rotate_batches.py      # leave-one-batch-out evaluation
│   ├── methods.py             # method wrappers (gotmap lifecycle)
│   ├── metrics.py             # evaluation metrics
│   └── datasets.py            # dataset loaders + ref/query splitting
└── examples/
    ├── run_pbmc_benchmark.py  # fixed ref/query example
    └── benchmark_general.py   # CLI over any AnnData

License

MIT

Metadata

Release files for gotmap-benchmark 0.5.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gotmap-benchmark 0.5.3
File Size Uploaded Provenance Actions
gotmap_benchmark-0.5.3.tar.gz 22.5 kB Without provenance Details for gotmap_benchmark-0.5.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for gotmap-benchmark 0.5.3
File Interpreter ABI Platform Actions
gotmap_benchmark-0.5.3-py3-none-any.whl Python 3 none any Details for gotmap_benchmark-0.5.3-py3-none-any.whl

Total release size: 45.7 kB

Release files / gotmap_benchmark-0.5.3.tar.gz

Download URL gotmap_benchmark-0.5.3.tar.gz
Size 22.5 kB
Tags Source
SHA-256 checksum
How to use checksums
576ca99d111afac4bff7a1109effa1752d57035f11b0069137ee5461c438a864
BLAKE2b-256 checksum
How to use checksums
312dc87c29ef087b5e7426ab0b721f2a0ff046076c89ff1e1d44d3600ad725e7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.18

Release files / gotmap_benchmark-0.5.3-py3-none-any.whl

Download URL gotmap_benchmark-0.5.3-py3-none-any.whl
Size 23.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d461b8b82a7ae70cd5943014892f20d2d59126192974da848fa2553dcb0a12e1
BLAKE2b-256 checksum
How to use checksums
55f2c739f63e1748c4fce4c042d2fb74c5d2fe6698beae9fc2db55388080d473
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.18

Security for gotmap-benchmark 0.5.3

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page