Batch integration (SCT + RPCA / Harmony / BBKNN)#
trackcell separates SCT normalization for integration from the downstream correction method. All paths share the same Seurat v4 front end:
Per-batch
SCTransform(sctransform,vst.flavor='v2')SelectIntegrationFeatures(default 2000 genes)PrepSCTIntegration→ anchor-gene Pearson residuals inobsm['X_sct_prep']
After step 3 you can run RPCA (Seurat default), Harmony, BBKNN, or any method that consumes a cells × genes embedding matrix.
API overview#
Function |
Role |
Output |
|---|---|---|
|
Per-batch SCT only |
|
|
Steps 1–3 (SCT + features + prep) |
|
|
Helper: matrix + gene names |
|
|
Seurat RPCA anchors + IntegrateData |
|
|
Explicit post-prep memory release (opt-in) |
Drops |
|
Convenience: |
Both prep and integrated matrices |
Method combinations#
Workflow |
Best for |
trackcell calls |
|---|---|---|
SCT + RPCA |
Seurat v4 parity; reference mapping; ≤10 batches |
|
SCT + Harmony |
Many slices / batches; fast linear correction in PC space |
|
SCT + BBKNN |
Batch-aware neighbour graph for clustering / UMAP |
|
SCT only |
Custom integrators (scVI, Scanorama, …) |
|
When to choose which method#
SCT + RPCA — closest to Seurat FindIntegrationAnchors(reduction='rpca') +
IntegrateData. Use when you need anchor-based correction or must match a Seurat
reference workflow. Anchor finding scales as O(B²) pairwise comparisons; for
dozens of spatial slices prefer Harmony or BBKNN on the prep matrix.
SCT + Harmony — recommended default for multi-slice spatial data: one PCA on shared anchor residuals, then Harmony removes batch effects in embedding space. Does not materialise a full integrated expression matrix; downstream clustering / UMAP uses the Harmony embedding.
SCT + BBKNN — builds a batch-balanced kNN graph directly on X_sct_prep (or
PCA thereof). Good when the goal is clustering / neighbourhood rather than a
corrected expression matrix.
tcl.tl.integrate_sct_rpcaConvenience:
run_sct_integration+integrate_rpcaBoth prep and integrated matrices
Seurat parity first#
RPCA results matching Seurat take priority. trackcell uses the same pipeline as Seurat v4:
Sample-tree merging (not fixed-reference shortcuts)
n_trees=50for anchor findingFor benchmark-grade parity on IntegrateData, also set
n_trees_weight=50andintegration_dtype='float64'
Nothing in uns is deleted automatically. Memory trade-offs are always
user-initiated (see below).
SCT + RPCA (Seurat v4)#
One-shot#
import trackcell as tcl
tcl.tl.integrate_sct_rpca(
adata,
batch_key="orig.ident",
layer="counts",
n_features=2000,
dims=30,
run_sct=True,
copy=False,
)
# adata.obsm["X_sct_prep"] — anchor residuals (input to other methods)
# adata.obsm["X_sct_integrated"] — RPCA-corrected residuals
Split API (reuse prep for Harmony / RPCA)#
import trackcell as tcl
tcl.tl.run_sct_integration(
adata,
batch_key="orig.ident",
layer="counts",
n_features=2000,
sct_batch_n_jobs=4, # parallel SCT per batch / slice
)
# --- explicit memory release (optional; does NOT change RPCA output) ---
# Pick ONE level after prep is final:
# (A) Drop per-batch HVG residual caches only (~largest win):
for _batch, entry in adata.uns["sct"]["batch_models"].items():
entry.pop("scale_data", None)
# (B) Drop all batch_models (keep uns['sct']['params']):
# del adata.uns["sct"]["batch_models"]
# (C) Drop entire SCT uns block (prep in obsm is enough for RPCA):
# del adata.uns["sct"]
# Or use the helper (same as A/B/C):
# tcl.tl.release_sct_integration_cache(adata, what="scale_data")
# Option A: RPCA correction (Seurat sample tree)
tcl.tl.integrate_rpca(
adata,
batch_key="orig.ident",
dims=30,
n_trees=50, # anchors — keep 50 for Seurat parity
n_trees_weight=50, # integrate — 50 for parity; 10 for speed
integration_dtype="float64", # float64 for parity; float32 saves RAM
)
# Option B: export prep for external tools
matrix, genes = tcl.tl.sct_prep_matrix(adata)
SCT + Harmony#
Requires harmonypy (pip install "trackcell[integration]" or pip install harmonypy).
import scanpy as sc
import trackcell as tcl
tcl.tl.run_sct_integration(
adata,
batch_key="slice_id",
layer="counts",
sct_batch_n_jobs=-1,
)
sc.pp.pca(adata, use_rep="X_sct_prep", n_comps=30)
sc.external.pp.harmony_integrate(
adata,
key="X_pca",
basis="X_pca_harmony",
groupby="slice_id",
)
sc.pp.neighbors(adata, use_rep="X_pca_harmony")
sc.tl.umap(adata)
For spatial clustering that already supports Harmony (tcl.tl.spatial_cluster),
see Spatial Clustering (YardCluster) — that path applies Harmony to spatial embeddings,
not SCT prep residuals. For multi-slice spatial domain discovery, prefer
spatial_cluster(..., expression_source='sct_prep') after run_sct_integration
(see Spatial Clustering (YardCluster)). Use the Harmony recipe below when integrating
expression across slices before standard scRNA-seq-style analysis.
SCT + BBKNN#
Requires bbknn (pip install "trackcell[integration]" or pip install bbknn).
import scanpy as sc
import trackcell as tcl
tcl.tl.run_sct_integration(adata, batch_key="slice_id", layer="counts")
# On prep residuals directly, or PCA first for speed:
sc.pp.pca(adata, use_rep="X_sct_prep", n_comps=30)
sc.external.pp.bbknn(adata, batch_key="slice_id", use_rep="X_pca")
sc.tl.umap(adata)
Spatial multi-slice tips#
Set
batch_keyto your slice / capture-area column (e.g.slice_id,orig.ident).Use
sct_batch_n_jobsto parallelise per-slice SCT (-1= all CPUs).For >10 slices where Seurat parity is not required, consider SCT + Harmony instead of RPCA.
Prep matrix size ≈
n_cells × n_features × 4bytes (float32 inobsm). 30 slices × 10k cells × 2000 genes ≈ 2.4 GB forX_sct_prepalone.
Explicit memory release (opt-in)#
After run_sct_integration, adata.uns['sct']['batch_models'] may hold large
per-slice scale_data caches (full HVG residual matrices). RPCA and Harmony
only need obsm['X_sct_prep'] — you may delete caches manually before
merge to save RAM.
Important
trackcell never removes uns entries automatically. You must run one of
the commands below (or release_sct_integration_cache) yourself.
Level |
Manual command |
Changes RPCA vs Seurat? |
|---|---|---|
A |
|
No (prep already in |
B |
|
No |
C |
|
No |
Helper (equivalent to A/B/C):
tcl.tl.release_sct_integration_cache(adata, what="scale_data") # level A
tcl.tl.release_sct_integration_cache(adata, what="batch_models") # level B
tcl.tl.release_sct_integration_cache(adata, what="sct_uns") # level C
When you cannot release yet
You still need to change
anchor_featuresand re-runprep_sct_integration(missing genes are recomputed from counts +model_pars— slower withoutscale_data, same numerics).You have not finished
run_sct_integration/ prep (noX_sct_prepyet).
What we do not do (Seurat parity)
No automatic cache trimming inside
integrate_sct_rpcaorintegrate_rpca.No
reference_batch/ fixed-reference merge shortcuts that alter Seurat’s sample-tree correction path.
Performance knobs (RPCA path)#
Parameter |
Default |
Effect |
|---|---|---|
|
|
Parallel per-batch SCT when |
|
|
Annoy trees for anchor finding (keep high for parity) |
|
|
Annoy trees for IntegrateData weight PCA. Use ``50`` for Seurat
parity; |
|
|
Halves PCA / correction workspace. Use ``float64`` for Seurat parity |
|
|
Chunk size for weight matrix construction (lower = less RAM) |
Benchmark / Seurat parity mode — pass n_trees_weight=50,
integration_dtype='float64'. See SCT + RPCA integration evaluation.
Explicit SCT v2 backend#
SCT v2 uses the bundled pure-Python NB offset fitter by default. The optional
pyglmGamPoi backend is used only when explicitly selected:
tcl.tl.integrate_sct_rpca(
adata,
batch_key="orig.ident",
sct_v2_backend="pyglmGamPoi",
)
If pyglmGamPoi is not installed, explicit selection raises an error. Trackcell
does not automatically switch backends, so results remain reproducible across
environments. Existing R exports are used only by the offline benchmark suite.
Further reading#
SCT + RPCA integration evaluation — Python vs Seurat RPCA benchmark
SCTransform v2 evaluation — SCTransform v2 single-sample benchmark
Spatial Clustering (YardCluster) — YardCluster (spatial domains; separate from SCT integration)