Introduction

This vignette demonstrates how to annotate Xenium spatial transcriptomics data using RCTD, followed by purification with SPLIT.

Overview

In this vignette, we:

  1. Run RCTD Annotation
    • We begin by running RCTD annotation on a Xenium sample, using matched Chromium data from a public 10x Genomics dataset as the reference.
  2. Apply Default SPLIT Purification
    • The default SPLIT purification method is then applied to clean the annotated Xenium sample, refining the initial annotations.
  3. Apply Spatially-Aware SPLIT
    • We apply spatially-aware SPLIT, which purifies cells showing signs of contamination based on local spatial diffusion patterns.
  4. Apply SPLIT-Shift
    • Finally, SPLIT-shift is applied to swap primary and secondary labels based on transcriptomic neighborhood heterogeneity, improving the accuracy of cell type assignments.

This pipeline assumes that cell type assignments — originally derived from the Chromium reference — are refined and reliable for downstream analysis.

if(!requireNamespace("spacexr", quietly = TRUE)){
  remotes::install_github("dmcable/spacexr") ## or remotes::install_github("jpromeror/spacexr@HD") for implementation of the doublet mode.
}
library(spacexr)

if(!requireNamespace("SPLIT", quietly = TRUE)){
  remotes::install_github("bdsc-tds/SPLIT") 
}
library(SPLIT)

library(dplyr)
library(Seurat)
library(readxl)
library(SingleCellExperiment)
library(httr)
library(ggplot2)

Load Data

For this vignette, we use a publicly available Xenium dataset from the 10x Genomics database, originating from:

Janesick, A., Shelansky, R., Gottscho, A.D. et al.
High resolution mapping of the tumor microenvironment using integrated single-cell, spatial and in situ analysis.
Nature Communications 14, 8353 (2023).
https://doi.org/10.1038/s41467-023-43458-x

This dataset provides high-resolution spatial transcriptomics data suitable for downstream analysis with RCTD and SPLIT.


Load Chromium Dataset (Reference)

We manually load metadata for the Chromium single-cell dataset and metadata from the same study, which will serve as the reference for RCTD annotation.

# read metadata
url <- "https://static-content.springer.com/esm/art%3A10.1038%2Fs41467-023-43458-x/MediaObjects/41467_2023_43458_MOESM4_ESM.xlsx"
temp_file <- tempfile(fileext = ".xlsx")
GET(url, write_disk(temp_file, overwrite = TRUE))
Response [https://static-content.springer.com/esm/art%3A10.1038%2Fs41467-023-43458-x/MediaObjects/41467_2023_43458_MOESM4_ESM.xlsx]
  Date: 2026-06-29 07:31
  Status: 200
  Content-Type: application/octet-stream
  Size: 39.2 MB
<ON DISK>  /tmp/RtmpAJlyop/file624a6227b1e2d.xlsx
chrom_metadata <- read_excel(temp_file, sheet = 1) %>% as.data.frame()
rownames(chrom_metadata) <- chrom_metadata$Barcode

Manually load Chromium from 10x

# read Chromium 
url <- "https://cf.10xgenomics.com/samples/cell-exp/7.0.1/Chromium_FFPE_Human_Breast_Cancer_Chromium_FFPE_Human_Breast_Cancer/Chromium_FFPE_Human_Breast_Cancer_Chromium_FFPE_Human_Breast_Cancer_count_sample_filtered_feature_bc_matrix.h5"
temp_file <- tempfile(fileext = ".h5")
GET(url, write_disk(temp_file, overwrite = TRUE))
Response [https://cf.10xgenomics.com/samples/cell-exp/7.0.1/Chromium_FFPE_Human_Breast_Cancer_Chromium_FFPE_Human_Breast_Cancer/Chromium_FFPE_Human_Breast_Cancer_Chromium_FFPE_Human_Breast_Cancer_count_sample_filtered_feature_bc_matrix.h5]
  Date: 2026-06-29 07:35
  Status: 200
  Content-Type: binary/octet-stream
  Size: 91.6 MB
<ON DISK>  /tmp/RtmpAJlyop/file624a65162f218.h5
chrom_counts <- Read10X_h5(temp_file)
chrom <- CreateSeuratObject(counts = chrom_counts, assay = "RNA", meta.data = chrom_metadata)

chrom$QC <- !is.na(chrom$Annotation)
chrom$is_hybrid <- grepl("Hybrid", chrom$Annotation, ignore.case = TRUE)
chrom <- subset(chrom, subset = QC == TRUE & is_hybrid == FALSE) # remove not annotated cells that cells that have sign of doublets

Load Xenium Dataset

We load the Xenium spatial transcriptomics data using the STexampleData package, which provides convenient access to example spatial datasets for analysis and demonstration.

if(!requireNamespace("STexampleData", quietly = TRUE))
  remotes::install_github("lmweber/STexampleData")
xe_full_seu <- STexampleData::Janesick_breastCancer_Xenium_rep1() 

## Convert to Seurat to stay consistent with chromium object
sp_coords <- spatialCoords(xe_full_seu)
colnames(sp_coords) <- c("ST_1", "ST_2")

xe_full <- CreateSeuratObject(
  counts = counts(xe_full_seu),
  assay = "Xenium",
  meta.data = as.data.frame(colData(xe_full_seu))
)

xe_full[["spatial"]] <- CreateDimReducObject(sp_coords, assay = "Xenium", key = "ST_")

xe_full$x <- sp_coords[,1]
xe_full$y <- sp_coords[,2]
rm(xe_full_seu)

Downsample Xenium Dataset for Faster RCTD (Optional)

Running RCTD can be time-consuming, especially on large datasets like Xenium. To speed up computation during this tutorial, we optionally provide code to downsample the dataset. We recommend spatial cropping (rather than random sampling) to preserve neighborhood structure, which is important for downstream analysis.

That said, downsampling is not required , we provide precomputed RCTD results below so you can skip running RCTD altogether if desired.

DO_subset_xe <- FALSE 
X_lim <- c(6000, Inf) # cropping area 
Y_lim <- c(4000, Inf) # cropping area 

if(DO_subset_xe){
  xe <- subset(xe_full, subset = x > min(X_lim) & x < max(X_lim) & y > min(Y_lim) & y < max(Y_lim))
} else {
  xe <- xe_full
}

RCDT annotation

Run RCTD Annotation on Xenium Running RCTD on large datasets can be computationally intensive and may take several hours. To streamline the workflow, we provide the full code for reproducibility. However, we recommend loading a pre-computed RCTD object by setting DO_run_RCTD <- FALSE.

📝 Note: SPLIT does not depend on RCTD specifically — it accepts deconvolution results from any tool via a cells × cell-types weight matrix and a genes × cell-types reference matrix. See ?purify and the annotation-method agnostic quick start for details.

A significantly faster Python implementation of RCTD (py-RCTD)[https://github.com/p-gueguen/rctd-py] is available for large datasets. SPLIT provides a convenience wrapper reconstruct_rctd_from_rctdpy() to load py-RCTD outputs directly into purify(). See ?reconstruct_rctd_from_rctdpy for details.

DO_run_RCTC <- FALSE # FALSE to load pre-computed results

common_genes <- intersect(rownames(xe), rownames(chrom))
ref_labels <- chrom$Annotation %>% as.factor()

ref.obj <- Reference(GetAssayData(chrom, "RNA", "counts")[common_genes, ],
                     cell_types = ref_labels, min_UMI = 10, require_int = TRUE)

test.obj <- SpatialRNA(coords = xe@reductions$spatial@cell.embeddings %>% as.data.frame(),
                       counts = GetAssayData(xe, assay = "Xenium", layer = "counts")[common_genes, ],
                       require_int = TRUE)

if(!exists("class_df")) 
  class_df <- NULL

RCTD <- create.RCTD(
  test.obj, 
  ref.obj, 
  UMI_min = 10, 
  counts_MIN = 10, 
  UMI_min_sigma = 100,
  max_cores = BiocParallel::multicoreWorkers() - 1, 
  CELL_MIN_INSTANCE = 25,
  class_df = class_df # highly recommended 
  )

              B_Cells          CD4+_T_Cells          CD8+_T_Cells                DCIS 1                DCIS 2           Endothelial 
                 1450                  2883                  1839                  1861                  2159                  1053 
       Invasive_Tumor             IRF7+_DCs            LAMP3+_DCs         Macrophages_1         Macrophages_2            Mast_Cells 
                 4554                   210                   103                  2960                   760                    92 
        Myoepi_ACTA2+         Myoepi_KRT15+     Perivascular-Like Prolif_Invasive_Tumor               Stromal 
                 1234                   603                   280                  1329                  2598 
if(DO_run_RCTC){
  RCTD <- run.RCTD(RCTD, doublet_mode = "doublet")
  saveRDS(RCTD, "~/precomp_rctd_class_aware.rds")
} else {
  message("reading precomp RCTD results")
  
  # Install googledrive if you haven't already
  if (!requireNamespace("googledrive", quietly = TRUE)) {
    install.packages("googledrive")
  }
  library(googledrive)
  drive_deauth()
  # Define the file ID from the Google Drive link
  file_id <- "1pTUKq49JbUFwVk7vttjZIFqkx-AKznRF" #"1DCalFIZJywOvrSGBSPqrHh9QINeQp8aq"
  local_path <- tempfile(fileext = ".rds")
  drive_download(as_id(file_id), path = local_path, overwrite = TRUE)
  RCTD <- readRDS(local_path)
  
}

Visualize RCTD Annotation Post-process RCDT output and add results into Xenium object

RCTD <- SPLIT::run_post_process_RCTD(RCTD)
xe <- AddMetaData(xe, RCTD@results$results_df)
xe <- subset(xe, subset = nCount_Xenium >= 10)

cat("Proprtion of spot classes")
Proprtion of spot classes
(xe$spot_class %>% table())/ncol(xe)*100 
.
           reject doublet_uncertain   doublet_certain           singlet 
         1.412805          1.725610         17.479878         79.289634 
xe <- xe %>% SCTransform(assay = "Xenium", verbose = FALSE) %>% RunPCA(verbose = FALSE) %>% RunUMAP(dims = 1:50, verbose = FALSE)
p1 <- UMAPPlot(xe, group.by = "first_type", label = T, repel = T, cols = pal) + theme_void() + theme(aspect.ratio = 1, legend.position = "none")
p2 <- UMAPPlot(xe, group.by = "second_type", cols = pal) + theme_void() + theme(aspect.ratio = 1, legend.position = "bottom")
p3 <- UMAPPlot(xe, group.by = "spot_class") + theme_void() + theme(aspect.ratio = 1, legend.position = "right")
 
p1 | p2 | p3

Spatial Visualization

DimPlot(xe, reduction = "spatial", group.by = "first_type", raster = TRUE, cols = pal) + coord_fixed()

Purification

SPLIT (default)

This section runs the default SPLIT purification and visualizes purified data.

# Run SPLIT purification
# Make sure you have run `RCTD <- SPLIT::run_post_process_RCTD(RCTD)` so that RCTD result is SPLIT-compatible.

res_split <- SPLIT::purify(
  counts = GetAssayData(xe, assay = 'Xenium', layer = 'counts'), # or any gene x cells counts matrix
  rctd = RCTD,
  DO_purify_singlets = TRUE, # Recommended
  DO_remove_residual_contamination = TRUE # New 🚀 see https://github.com/bdsc-tds/SPLIT/blob/main/vignettes/Residual_Contamination_Removal.Rmd
  )
              B_Cells          CD4+_T_Cells          CD8+_T_Cells                DCIS 1                DCIS 2           Endothelial 
                0.040                 0.041                 0.041                 0.048                 0.042                 0.040 
       Invasive_Tumor             IRF7+_DCs            LAMP3+_DCs         Macrophages_1         Macrophages_2            Mast_Cells 
                0.029                 0.055                 0.038                 0.031                 0.035                 0.033 
        Myoepi_ACTA2+         Myoepi_KRT15+     Perivascular-Like Prolif_Invasive_Tumor               Stromal 
                0.052                 0.054                 0.033                 0.031                 0.041 
# Create a purified Seurat object
xe_purified <- CreateSeuratObject(
  counts = res_split$purified_counts,
  meta.data = res_split$cell_meta,
  assay = "Xenium"
)

xe_purified <- AddMetaData(xe_purified, xe@meta.data %>% select(spot_class))

# Optional: Filter, normalize and visualize
xe_purified <- subset(xe_purified, subset = nCount_Xenium > 5)
xe_purified <- xe_purified %>%
  SCTransform(assay = "Xenium", verbose = FALSE) %>%
  RunPCA(verbose = FALSE) %>%
  RunUMAP(dims = 1:20, verbose = FALSE)

#UMAPPlot(xe_purified, group.by = c("first_type"), label = T, repel = T) + theme_void() + theme(aspect.ratio = 1, legend.position = "none")

Visually compare results of Raw and SPLIT-Purified data

p1 <- UMAPPlot(xe, group.by = c("first_type"), label = T, repel = T, cols = pal) + theme_void() + theme(aspect.ratio = 1, legend.position = "none") + ggtitle("Raw Xenium data")

p2 <- UMAPPlot(xe_purified, group.by = c("first_type"), label = T, repel = T, cols = pal) + theme_void() + theme(aspect.ratio = 1, legend.position = "right") + ggtitle("SPLIT-purified Xenium data")

p3 <- UMAPPlot(xe_purified, group.by = c("spot_class")) + theme_void() + theme(aspect.ratio = 1, legend.position = "bottom") + ggtitle("SPLIT-purified Xenium data colored by spot class")
p4 <- UMAPPlot(xe_purified, group.by = c("purification_status")) + theme_void() + theme(aspect.ratio = 1, legend.position = "bottom") + ggtitle("SPLIT-purified Xenium data colored by purification status")


(p1|p2) 

(p3|p4)

Spatially-aware SPLIT

SPLIT can leverage spatial information to assess the abundance of secondary signals in the local neighborhood (i.e., local diffusion potential), enabling selective decomposition only when contamination is likely. This spatially informed strategy helps prevent overcorrection of phenotypes that may be underrepresented or absent in the reference. Specifically, we first compute the spatial neighborhood for each cell, then identify and purify cells that have sign of local diffusion of the secondary cell type.

sp_nw <- SPLIT::build_spatial_network(
  xe, 
  reduction = "spatial",
  dims = 1:2, 
  DO_prune = TRUE, 
  rad_pruning = 15, # remove connections further than 15um
  k_knn = 20
  )

sp_nw <- SPLIT::add_spatial_metric(spatial_neighborhood = sp_nw, rctd = RCTD)
sp_neigh_df <- SPLIT::neighborhood_analysis_to_metadata(sp_nw)

xe <- AddMetaData(xe, sp_neigh_df)

#rm(sp_nw, sp_neigh_df)

Visualize local diffusion of secondary cell type

The score neighborhood_weights_second_type corresponds to the average weight of the secondary cell type in cell’s spatial neighborhood.

# Plot magnitude of local diffusion on UMAP
FeaturePlot(xe, features = c("neighborhood_weights_second_type")) + theme_void() + theme(aspect.ratio = 1)

# Plot distribution of local diffusion value
hist(xe$neighborhood_weights_second_type)

# Plot distribution of local diffusion value per `spot_class`
xe@meta.data %>% filter(!is.na(spot_class)) %>% 
  ggplot(aes(x = spot_class, y = neighborhood_weights_second_type, color = spot_class)) + geom_boxplot() + labs(title = "Local neighbohood diffusion by spot class") + theme_minimal() 

We now purify cells that have secondary signal in their spatial neighborhood (e.g., neighborhood_weights_second_type) and keep other cells unchanged

xe_purified_balanced_score <- SPLIT::balance_raw_and_purified_data_by_score(
  xe_raw = xe,
  xe_purified = xe_purified,
  default_assay = "Xenium", # should be param, but can wait 
  spot_class_key = "spot_class",
  threshold = 0.05, # lower -> more cells will be purified
  score_name = "neighborhood_weights_second_type"
)

# Optional: Filter, normalize and visualize
xe_purified_balanced_score <- subset(xe_purified_balanced_score, subset = nCount_Xenium > 5)
xe_purified_balanced_score <- xe_purified_balanced_score %>%
  SCTransform(assay = "Xenium", verbose = FALSE) %>%
  RunPCA(verbose = FALSE) %>%
  RunUMAP(dims = 1:20, verbose = FALSE)

p5 <- UMAPPlot(xe_purified_balanced_score, group.by = c("first_type"), label = T, repel = T, cols = pal) + theme_void() + theme(aspect.ratio = 1, legend.position = "none") + ggtitle("Spatially-aware SPLIT-purified Xenium data")
p6 <- UMAPPlot(xe_purified_balanced_score, group.by = c("purification_status")) + theme_void() + theme(aspect.ratio = 1, legend.position = "bottom")

p5|p6

SPLIT-shift

In some cases, the contamination signal is so strong that RCTD assigns the cell to its secondary cell type. To address this, we introduce SPLIT-shift—an approach that refines phenotype assignments by swapping the primary and secondary cell type labels based on transcriptional neighborhood homogeneity.

For this, we need to compute transcriptomics neighborhood

tr_nw <- build_transcriptomics_network(
  xe,
  DO_prune = FALSE,
  k_knn = 100
)
tr_nw <- add_transcriptomics_metric(transcriptomics_neighborhood = tr_nw, rctd = RCTD) 
tr_neigh_df <- neighborhood_analysis_to_metadata(tr_nw)
xe <- AddMetaData(xe, tr_neigh_df)

rm(tr_nw, tr_neigh_df)

And then, we set DO_swap_lables = TRUE to allow SPLIT-shift

xe_split_shift <- SPLIT::balance_raw_and_purified_data_by_score(
  xe_raw = xe,
  xe_purified = xe_purified,
  default_assay = "Xenium",
  spot_class_key = "spot_class",
  threshold = 0.05, # to be consistent with spatially-aware SPLIT results
  score_name = "neighborhood_weights_second_type",
  DO_swap_lables = TRUE
)

# Optional: Filter, normalize and visualize
xe_split_shift <- subset(xe_split_shift, subset = nCount_Xenium > 5)
xe_split_shift <- xe_split_shift %>%
  SCTransform(assay = "Xenium", verbose = FALSE) %>%
  RunPCA(verbose = FALSE) %>%
  RunUMAP(dims = 1:20, verbose = FALSE)

Visualize SPLIT-shift

p7 <- UMAPPlot(xe_split_shift, group.by = c("first_type"), label = T, repel = T, cols = pal) + theme_void() + theme(aspect.ratio = 1, legend.position = "none") + ggtitle("SPLIT-shift-purified Xenium data")
p8 <- UMAPPlot(xe_split_shift, group.by = c("purification_status")) + theme_void() + theme(aspect.ratio = 1, legend.position = "bottom")
p9 <- UMAPPlot(xe_split_shift, group.by = c("swap")) + theme_void() + theme(aspect.ratio = 1, legend.position = "bottom")

p7|p8|p9

# Visualize results faceted by swapping status
p10 <- UMAPPlot(xe_split_shift, group.by = c("first_type"), split.by = "swap", raster = F, cols = pal) + theme_void() + theme(aspect.ratio = 1, legend.position = "bottom") + ggtitle("SPLIT-shift-purified Xenium data faceted by lable swapping status")
p10

Summary

To run SPLIT, you need a single-cell reference with reliable cell type labels, which is used to annotate Xenium data using RCTD in doublet mode.
We strongly recommend providing a broader-level mapping of the reference cell types to higher-level classes. This helps RCTD produce more robust results and reduces the number of rejected cells, which are excluded from downstream analysis.

After annotation, SPLIT can be run in several combinable modes to purify the data:

  1. Default SPLIT purifies all doublets_certain, all doublets_uncertain, and—if DO_purify_singlets = TRUE — singlets that show signs of a secondary cell type.
    Rejected cells are always removed as unreliable.

  2. Spatially-aware SPLIT purifies any cells that show signs of contamination based on local spatial diffusion — i.e., having secondary signal in their spatial neighborhood.

  3. SPLIT-shift allows swapping the primary and secondary cell type labels based on transcriptional neighborhood homogeneity.

p1 | p2+theme(legend.position = "bottom") | p5 | p7

Bonus: Pie visualization

We can visualize individual cells as pie charts, where colors represent the primary and secondary cell types, and sector areas are proportional to their respective weights.

In this example, we display a randomly selected T cell that exhibits strong local diffusion of its secondary cell type (ie., there is high signal of secondary cell type in its spatial neighborhood). The plot includes this cell and all neighboring cells within a 50μm radius.

pie_df <- get_pieplot_df(rctd = RCTD)
cois <- xe@meta.data %>% filter(neighborhood_weights_second_type > .2, first_type %in% c("CD4+_T_Cells", "CD8+_T_Cells"), spot_class != "reject") %>% rownames()

p <- plot_pie_around_cell(pie_df, cell_id = cois[1], radius = 50, cols = pal)
[1] 240.9595
[1] 848.4798
plot(p)

The border color of each pie indicates the primary cell type. Additional markers within the pies reflect RCTD spot class (ie., annotation confidence):

  • A black dot indicates a doublet_uncertain cell.
  • A colored dot (matching the secondary cell type) indicates a doublet_certain.
  • A cross (×) marks a reject cell.
  • Pies with no internal symbol represent confidently assigned singlet cells.