spatial-integrate
Load when removing batch effects from multi-batch spatial AnnData with PCA using Harmony, BBKNN, or Scanorama. Skip physical coordinate alignment (use spatial-register) and single-batch data (use spatial-domains).
- License 许可
- Apache-2.0
- 最近更新
- 2026-10-08
- Stars
- ★ 161
- Forks
- 27
01 前言 Front Matter
- name
- spatial-integrate
- tags
- [ "spatial", "integration", "batch-correction" ]
- trigger
- multi-sample integration, batch correction, Harmony, BBKNN, Scanorama
- description
- Load when removing batch effects from multi-batch spatial AnnData with PCA using Harmony, BBKNN, or Scanorama. Skip physical coordinate alignment (use spatial-register) and single-batch data (use spatial-domains).
02 资源文件 11
- 脚本_api.py4.7 KB
- 脚本examples/example_step.py1014 B
- 其他r_visualization/integration_publication_template.R1.4 KB
- 参考文档r_visualization/README.md1.4 KB
- 参考文档references/methodology.md8.5 KB
- 参考文档references/output_contract.md1.7 KB
- 参考文档references/parameters.md2.4 KB
- 脚本spatial_integrate.py37.8 KB
- 参考文档STRATEGY.json521 B
- 脚本tests/test_api.py1.3 KB
- 脚本tests/test_spatial_integrate.py14.7 KB
03 SKILL.md 正文
spatial-integrate
Use from a step
from skills._sdk.notebook import load_skill, read_input, write_output
library = load_skill("spatial-integrate")
adata = read_input("data/multi_sample.h5ad")
adata = library.integrate(adata, batch_key="sample")
write_output(adata, "intermediate/integrated.h5ad")
When to use
Correct expression-space batch effects after spatial-preprocess. Harmony and Scanorama add corrected PCA-based embeddings; BBKNN replaces the neighbor graph. None aligns tissue coordinates or changes the expression matrix.
Inputs & Outputs
Input: preprocessed AnnData with obsm["X_pca"] and at least two labels in
obs["batch"] (or the chosen batch_key). Functions return AnnData, tables and
figures without writing files; see API below.
CLI writes processed.h5ad, report.md, result.json, batch-size and
integration tables, and the comparison gallery. The complete file inventory
and generation conditions are in references/output_contract.md.
Harmony adds X_pca_harmony; Scanorama adds X_scanorama;
BBKNN changes obsp["distances"] and obsp["connectivities"].
Key CLI
python skills/spatial/spatial-integrate/spatial_integrate.py \
--input multi_sample.h5ad --output results/integration --method harmony --batch-key sample
python skills/spatial/spatial-integrate/spatial_integrate.py --demo --output /tmp/spatial_integrate
Use examples/example_step.py for load_skill, saved objects and replay.
references/parameters.md lists the CLI method flags.
Gotchas
X_pcamust exist before integration; no normalization is performed here.X_scanoramais a corrected PCA-based embedding, not corrected gene expression.batch_entropy_aftermeasures local mixing, not biological preservation; inspect condition and cell-type structure before choosing a correction.- The function's seed controls Harmony, neighbors, UMAP and Leiden. BBKNN's default Annoy matching and Scanorama's wrapper expose no seed here; cross-version matching can vary. The installed versions passed repeat CLI checks.
run_info(adata, keep=False)removes only library diagnostics. The CLI keeps its existinguns["spatial_integration"]summary.X_umap_before_integrationandX_umap_after_integrationpreserve both views.
API
<!-- api:begin generated from _api.py; regenerate with run.py api <skill dir> --write -->
integrate(adata, *, method: str='harmony', batch_key: str='batch', random_state: int=0, **parameters)
Integrate a multi-batch PCA representation in place, preserving expression.
:param adata: Preprocessed AnnData with X_pca and batch labels. :param method: harmony (default), bbknn (graph only), or scanorama. :param batch_key: Batch column in obs, default batch. :param random_state: Seed for Harmony, neighbors, UMAP and Leiden, default 0. BBKNN's default Annoy backend and Scanorama expose no seed here; their matching can vary across backend versions. :param parameters: Method keywords with original CLI defaults: Harmony theta=2, lamb=1, max_iter_harmony=10; BBKNN neighbors_within_batch=3, n_pcs=50, trim=None; Scanorama knn=20, sigma=15, alpha=0.1, batch_size=5000. :returns: The same AnnData with corrected embedding or graph, UMAP snapshots, per-spot batch entropy, and JSON run diagnostics. X is unchanged. :raises ValueError: Unknown method, missing batches/PCA, or invalid parameters. :raises ImportError: Missing backend; use install_skill_deps for that method.
run_info(adata, *, keep: bool=True) -> dict
Read the last integration summary.
:param adata: AnnData returned by integrate. :param keep: True retains diagnostics; False removes them for CLI serialization. :returns: Summary including seed and effective method parameters, or an empty dict.
mixing_table(adata) -> pd.DataFrame
Return per-spot entropy before and after correction.
:param adata: Integrated AnnData. :returns: observation, batch_entropy_before, batch_entropy_after and batch_entropy_delta. :raises KeyError: Integration entropy columns are absent.
embedding_figure(adata, *, batch_key: str='batch')
Compare the pre- and post-integration UMAP coordinates.
:param adata: Integrated AnnData with both UMAP snapshots. :param batch_key: Batch labels used for color, default batch. :returns: A matplotlib Figure; the caller saves and closes it. :raises KeyError: Batch labels or UMAP snapshots are absent.
<!-- api:end -->
Dependencies
anndata, bbknn, harmonypy, matplotlib, numpy, pandas, scanorama, scanpy, scipy, seaborn
Missing method packages raise ImportError with an install_skill_deps hint.
04 同仓库更多 Skills
demo-skill
A fixture skill for the skill environment tests. Use it for nothing else.
fake-domains
Test fixture for the golden deployment in tests/entry. Load never; it has no script.
replace-me-skill
Load when copying this directory to bootstrap a new OmicsClaw skill. Skip when an existing skill already covers the request.
spatial-velocity
Load when estimating RNA velocity on a spatial AnnData with `layers["spliced"]` + `layers["unspliced"]` via scVelo (stochastic / deterministic / dynamical) or veloVI (deep generative). Skip when input lacks the spliced/unspliced layers (must be quantified upstream by velocyto / kb-python / STARsolo); non-spatial scRNA velocity (use sc-velocity).
spatial-trajectory
Load when inferring pseudotime / lineage trajectories on a preprocessed spatial AnnData via DPT (default — diffusion pseudotime), CellRank (terminal-state + fate-probability), or Palantir (waypoint branch probabilities). Skip when the data has spliced/unspliced layers and you want velocity-driven dynamics (use spatial-velocity); non-spatial scRNA pseudotime (use sc-pseudotime).
spatial-statistics
Load when running spatial autocorrelation / hotspot / co-occurrence / neighbourhood-enrichment / Ripley K stats on a clustered spatial AnnData via squidpy. Skip when ranking spatially variable genes (use spatial-genes); tissue domain detection (use spatial-domains).