Spatial Clustering (YardCluster)#
TrackCell provides YardCluster, a lightweight CPU spatial clustering method for
Visium HD cell segmentation and other spatial omics data in AnnData format.
YardCluster combines ideas from three widely used pipelines:
BANKSY — neighborhood mean (and optional gradient) feature augmentation with a mixing parameter
lambdaDECIPHER — separate identity (cell-intrinsic) and context (neighborhood) embedding channels before clustering
Space Ranger — optional DE-guided cluster merging after Leiden
Unlike Space Ranger graphclust (expression-only PCA + Louvain), YardCluster uses spatial coordinates when building neighborhood features, which typically yields more spatially coherent tissue domains on single-cell HD data.
Prerequisites#
Install TrackCell and clustering dependencies:
pip install "trackcell[clustering]"
Optional (multi-sample Harmony integration):
pip install "trackcell[integration]"
End-to-End Workflow#
The typical workflow loads Space Ranger cell segmentation data, optionally runs
scanpy QC, clusters with YardCluster, and visualizes with tcl.pl.spatial_cell.
import scanpy as sc
import trackcell as tcl
# 1. Load Visium HD cell segmentation (Space Ranger v4)
adata = tcl.io.read_hd_cellseg(
datapath="path/to/segmented_outputs",
sample="sample1",
)
# 2. Basic QC (scanpy)
sc.pp.filter_cells(adata, min_genes=10)
sc.pp.filter_genes(adata, min_cells=3)
# 3. YardCluster — includes HVG / normalize / log / scale by default
tcl.tl.spatial_cluster(adata, mode="auto")
# 4. Visualize domains and cell-type-oriented clusters
tcl.pl.spatial_cell(adata, color="yardcluster_domain", figsize=(10, 10))
tcl.pl.spatial_cell(adata, color="yardcluster_celltype", figsize=(10, 10))
Quick Start (One Function)#
tcl.tl.spatial_cluster() runs the full YardCluster pipeline:
tcl.tl.spatial_cluster(
adata,
mode="auto", # celltype + domain in one call
k_spatial=15, # spatial neighbors for M/G features
resolution=1.0, # Leiden resolution
key_added="yardcluster",
)
Warning
With preprocess=True (default) the function modifies ``adata`` in
place: it normalizes/logs adata.X, selects highly variable genes
(subsetting adata.var), and scales the matrix. Keep a copy of your
counts (or use copy=True) if you need the original genes/counts later.
HVG selection uses seurat_v3 on raw counts when scikit-misc is
installed, otherwise it falls back to seurat on log-normalized data.
Clustering modes#
|
|
Output column(s) |
Use case |
|---|---|---|---|
|
0.2 (default) |
|
Cell typing; emphasizes own expression |
|
0.8 (default) |
|
Tissue domains / niches; emphasizes neighborhood |
|
both |
|
Explore both views in one run (gradient on by default) |
Mode-aware defaults (spatial_cluster)#
When parameters are left at their default None:
use_gradient=None→Trueformode='domain'/mode='auto',Falseformode='celltype'merge_clusters=None→ DE-guided merge for domain clustering only (Space Ranger-style); celltype run skips merge
Override globally with use_gradient=False or merge_clusters=True, or
per-mode with merge_clusters_celltype / merge_clusters_domain.
Step-by-Step (with scanpy)#
For teaching or fine-grained control, call each stage separately. This mirrors how you would combine scanpy preprocessing with trackcell spatial tools:
import scanpy as sc
import trackcell as tcl
# --- scanpy preprocessing ---
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
# Use flavor="seurat_v3" on *raw counts* before normalization if you have
# scikit-misc installed; on log-normalized data use flavor="seurat".
sc.pp.highly_variable_genes(adata, n_top_genes=2000, flavor="seurat")
adata = adata[:, adata.var.highly_variable].copy()
sc.pp.scale(adata, max_value=10)
# --- YardCluster stages ---
tcl.tl.spatial_neighbors(adata, k=15, batch_key=None)
tcl.tl.neighborhood_features(
adata,
k_spatial=15,
use_gradient=False, # set True for gradient channel G
gradient_mode="cosphi", # or "regression"
key_added="yard",
)
tcl.tl.yard_embed(adata, lam=0.2, n_pcs=20, key_added="yard")
tcl.tl.yard_cluster(
adata,
use_rep="X_yard_mixed",
resolution=1.0,
key_added="yardcluster",
)
# --- optional scanpy visualization on the mixed embedding ---
sc.pp.neighbors(adata, use_rep="X_yard_mixed")
sc.tl.umap(adata)
sc.pl.umap(adata, color="yardcluster")
Function Reference (Summary)#
Function |
Description |
|---|---|
|
One-shot pipeline; recommended entry point |
|
Build within-batch spatial kNN graph ( |
|
Compute neighborhood mean |
|
Dual-channel PCA + |
|
Leiden clustering on a chosen embedding |
See the API page for full parameter lists.
Outputs Stored in AnnData#
After spatial_cluster(..., mode='auto', key_added='yardcluster'):
Cluster labels (``obs``)
yardcluster_celltype— low-lambda(cell typing)yardcluster_domain— high-lambda(domains)
Embeddings (``obsm``) — internal prefix yardcluster_features when using one-shot:
X_yardcluster_features_identity— identity channel PCAX_yardcluster_features_context— context channel PCAX_yardcluster_features_mixed— sqrt-weighted mix used for Leiden
Graphs (``obsp``)
spatial_connectivities/spatial_distances— physical neighborhood graphyardcluster_celltype_connectivities— expression kNN for celltype runyardcluster_domain_connectivities— expression kNN for domain run
Parameters (``uns``)
yardcluster_params— run configuration recap
Visualizing Results#
Polygon visualization (Visium HD cell segmentation):
tcl.pl.spatial_cell(
adata,
color="yardcluster_domain",
figsize=(12, 12),
legend_loc="right margin",
)
Compare with Space Ranger graphclust (pre-computed at load time):
# SR labels are in obs['classification'] after read_hd_cellseg()
tcl.pl.spatial_cell(adata, color="classification", figsize=(12, 12))
tcl.pl.spatial_cell(adata, color="yardcluster_domain", figsize=(12, 12))
Side-by-side with scanpy UMAP on the YardCluster embedding:
sc.pp.neighbors(adata, use_rep="X_yardcluster_features_mixed")
sc.tl.umap(adata)
sc.pl.umap(adata, color=["yardcluster_domain", "classification"])
Multi-Sample and Batch Handling#
Spatial neighbors are never drawn across batches (different tissue slices have incompatible coordinate systems). Expression integration is controlled separately.
SCT + YardCluster (multi-slice, recommended)#
For multiple tissue slices, integrate expression with SCT before YardCluster so neighborhood features use batch-corrected Pearson residuals instead of raw log-normalized counts:
import trackcell as tcl
# 1. SCT prep across slices (see :doc:`batch_integration`)
tcl.tl.run_sct_integration(
adata,
batch_key="slice_id",
layer="counts",
sct_batch_n_jobs=-1,
)
tcl.tl.release_sct_integration_cache(adata, what="scale_data")
# 2. YardCluster on SCT anchor residuals
tcl.tl.spatial_cluster(
adata,
batch_key="slice_id",
expression_source="sct_prep",
mode="auto",
integrate="joint", # optional Harmony on embedding channels
)
expression_source='sct_prep' reads obsm['X_sct_prep'] (2000 anchor genes by
default). Built-in preprocessing is skipped automatically.
# Cluster each sample independently (labels prefixed: "sampleA_0", …)
tcl.tl.spatial_cluster(
adata,
batch_key="sample_id",
integrate="separate",
mode="domain",
)
# Joint integration via Harmony (requires harmonypy)
tcl.tl.spatial_cluster(
adata,
batch_key="sample_id",
integrate="joint",
mode="celltype",
)
|
Behavior |
|---|---|
|
Single sample, or pooled without batch correction on the clustering graph (default) |
|
Per-batch clustering; requires |
|
Harmony on identity/context embeddings; requires |
|
Batch-balanced kNN on the mixed embedding (requires |
Clustering graph (graph_mode)#
Controls how Leiden builds its neighbor graph on the mixed embedding:
# Default: expression kNN only
tcl.tl.spatial_cluster(adata, graph_mode="expr")
# Spatial coherence: cluster on the physical neighbor graph
tcl.tl.spatial_cluster(adata, mode="domain", graph_mode="spatial")
# Weighted combination (alpha → more spatial weight)
tcl.tl.spatial_cluster(adata, mode="domain", graph_mode="hybrid", hybrid_alpha=0.4)
Platform presets#
tcl.tl.spatial_cluster(adata, platform="sto", mode="auto")
# Fills k_spatial / n_pcs / resolution when left as None
tcl.tl.spatial_cluster(adata, platform="sto", k_spatial=10) # explicit override
Advanced Options#
DE-Guided Cluster Merging#
Space Ranger merges sibling clusters when no genes are differentially expressed. YardCluster offers a similar optional post-processing step:
tcl.tl.spatial_cluster(
adata,
mode="domain",
merge_clusters=True,
merge_adj_p=0.05,
merge_max_de_tests=2000, # cap on pairwise DE tests (default 2000)
)
Large Datasets (Sketch Mode)#
For very large cell counts (>500k by default), YardCluster can cluster a random subsample and assign remaining cells to the nearest cluster medoid in embedding space:
tcl.tl.spatial_cluster(
adata,
sketch=True,
sketch_n=500_000,
sketch_threshold=500_000,
)
Gradient Features#
- Neighborhood mean
Mis always computed. Optional gradientG augments the context channel:
tcl.tl.neighborhood_features(
adata,
use_gradient=True,
gradient_mode="cosphi", # fast BANKSY-like approximation (default)
# gradient_mode="regression", # local linear regression magnitude
k_gradient=30, # default: 2 * k_spatial
)
Preprocessing Control#
By default (preprocess=True), spatial_cluster runs NormalizeTotal →
Log1p → HVG → Scale before clustering. Fine-tune or skip:
tcl.tl.spatial_cluster(
adata,
mode="auto",
preprocess=True, # default: run standard scanpy pipeline
n_top_genes=2000, # HVG count (default 2000)
hvg_by_batch=True, # run HVG per batch when batch_key is set
scale_by_batch=False, # scale each batch independently
)
# If data is already log-normalised and scaled
tcl.tl.spatial_cluster(adata, preprocess=False, mode="auto")
# Use a pre-computed layer (e.g. scVI denoised) instead of adata.X
tcl.tl.spatial_cluster(adata, layer="denoised", preprocess=False, mode="domain")
# Use SCT prep residuals after run_sct_integration (multi-slice)
tcl.tl.spatial_cluster(
adata,
expression_source="sct_prep",
batch_key="slice_id",
mode="auto",
)
# Use adata.raw.X instead of adata.X
tcl.tl.spatial_cluster(adata, use_raw=True, mode="celltype")
Harmony Integration (per-channel)#
When integrate='joint', Harmony is run on both identity and context
embeddings before mixing. You can also enable Harmony independently of the
integrate parameter:
tcl.tl.spatial_cluster(
adata,
batch_key="sample_id",
harmony_integrate=True, # Harmony on each embedding channel
integrate="none", # no separate/joint mode
mode="domain",
)
This differs from integrate='joint' in that harmony_integrate only
corrects the embedding channels, while integrate='joint' also triggers
Harmony during the embedding stage.
Return-Copy Mode#
Set copy=True to leave the original adata untouched and return a
modified copy:
result = tcl.tl.spatial_cluster(adata, mode="auto", copy=True)
Automatic Resolution Selection#
Instead of hand-tuning resolution, pass resolution="auto" (or
resolution_celltype/resolution_domain) to select the resolution by
clustering stability. YardCluster sweeps a resolution grid, runs Leiden several
times with different seeds, and picks the resolution with the highest mean
pairwise ARI across runs:
tcl.tl.spatial_cluster(
adata,
mode="domain",
resolution="auto",
n_resolution_runs=5, # repeats per resolution (default 5)
)
# Standalone sweep / selection
sweep = tcl.tl.sweep_resolutions(
adata, use_rep="X_yard_mixed", resolutions=[0.2, 0.4, 0.6, 0.8], n_runs=5
)
best_res, sweep = tcl.tl.select_resolution(adata, use_rep="X_yard_mixed")
The sweep table (obs/uns yardcluster_resolution_sweep) records
resolution, n_clusters and stability for each candidate.
Multi-Hop Neighborhood Aggregation#
CellCharter-style multi-hop aggregation expands the context channel from the
1-hop mean to a concatenation of hop-1..``n_layers`` means (W^k @ X), which
captures larger tissue structures — useful for domain mode:
tcl.tl.spatial_cluster(adata, mode="domain", n_layers=3)
# or stage-by-stage
tcl.tl.neighborhood_features(adata, k_spatial=15, n_layers=3)
Gaussian-Mixture Clustering (alternative backend)#
Besides Leiden, yard_cluster can fit a Gaussian mixture (sklearn) on the
mixed embedding, with soft assignments and BIC-based automatic k:
tcl.tl.yard_cluster(
adata,
use_rep="X_yard_mixed",
method="gmm",
n_clusters=None, # None -> pick k by BIC; or pass an int
)
Topology and Neighborhood Enrichment (post-analysis)#
After clustering, resolve spatially disconnected regions and quantify cluster-cluster interactions (CellCharter-style, dependency-free):
# Split each cluster into connected components of the spatial graph
tcl.tl.connected_components(adata, cluster_key="yardcluster_domain", min_cells=250)
# Observed vs expected (configuration-model) links between clusters
tcl.tl.nhood_enrichment(adata, "yardcluster_domain", log_fold_change=True)
# Differential enrichment between conditions (sample-level permutation p-values)
tcl.tl.diff_nhood_enrichment(
adata,
"yardcluster_domain",
"condition",
("Case", "Ctr"),
library_key="sample_id",
pvalues=True,
n_perms=1000,
)
# Visualize the enrichment matrices (diverging heatmaps, stars = p < 0.05)
tcl.pl.nhood_enrichment(adata, "yardcluster_domain")
tcl.pl.diff_nhood_enrichment(adata, "yardcluster_domain", "condition", ("Case", "Ctr"))
# Components are obs labels: overlay them on the tissue like any cluster
tcl.pl.spatial_cell(adata, color="component", figsize=(10, 10))
Long-edge trimming is also available to prevent kNN edges from bridging tissue gaps:
trimmed = tcl.tl.remove_long_links(
adata.obsm["spatial"], adata.obsp["spatial_connectivities"], 99.0
)
When to Use YardCluster vs Space Ranger graphclust#
Aspect |
Space Ranger graphclust |
YardCluster |
|---|---|---|
Uses spatial coordinates |
No |
Yes (neighborhood M/G) |
Pre-computed in SR output |
Yes ( |
No — run on demand |
Clustering backend |
Louvain + DE merge |
Leiden (+ optional DE merge) |
GPU required |
No |
No |
Best for |
Quick look at SR defaults |
HD cell-level domains, re-clustering, custom |
If you already have satisfactory classification labels from Space Ranger, you
can use them directly. Run YardCluster when you need spatially informed domains,
different lambda trade-offs, or to re-cluster after QC/subsetting.
Compare SR vs YardCluster manually when both are available:
from sklearn.metrics import adjusted_rand_score
ari = adjusted_rand_score(
adata.obs["classification"],
adata.obs["yardcluster_domain"],
)
print(f"ARI (SR graphclust vs YardCluster domain): {ari:.3f}")
Troubleshooting#
``ImportError`` for Leiden
Install leidenalg and python-igraph (see Prerequisites).
Too many / too few clusters
Adjust resolution (e.g. 0.5–1.5) or mode-specific
resolution_celltype / resolution_domain.
Out of memory on large gene panels
Neighborhood aggregation uses gene chunks (default 500 genes). Reduce
n_top_genes during preprocessing or increase chunk_size if you have RAM.
``integrate=’joint’`` fails
Install harmonypy and ensure batch_key has ≥2 batches with sufficient
cells per batch.
Already preprocessed data
If adata is already log-normalized and scaled, disable built-in preprocessing:
tcl.tl.spatial_cluster(adata, preprocess=False, mode="auto")
See Also#
Reading SpaceRanger Output — loading Visium HD and Xenium data
Visualization —
tcl.pl.spatial_cellplotting optionsComputing Distances to a Label — distance to label after clustering
API — autogenerated API reference