Metadata-Version: 2.4
Name: gotmap-benchmark
Version: 0.5.3
Summary: Benchmark pipeline for gotmap (query-to-reference atlas mapping) vs baselines.
Author: gotmap developers
License: MIT
Project-URL: Homepage, https://github.com/ZengFLab/gotmap-benchmark
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: gotmap>=0.3.1
Requires-Dist: grassmann-ot>=0.3.1
Requires-Dist: matplotlib>=3.5
Requires-Dist: seaborn>=0.11
Provides-Extra: all
Requires-Dist: torch>=1.12; extra == "all"
Requires-Dist: scvi-tools>=0.20; extra == "all"
Requires-Dist: harmonypy>=0.0.6; extra == "all"
Requires-Dist: bbknn>=1.5; extra == "all"

# 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

```bash
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

```python
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:

```python
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

```bash
# 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:

```bash
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:

```python
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:

```python
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
