Skip to contents

Introduction

CytoSPACER provides seamless integration with the Seurat ecosystem, supporting both Seurat v4 and v5. This vignette demonstrates how to use CytoSPACER with Seurat objects for spatial transcriptomics analysis.

Workflow Overview

The Seurat integration workflow consists of:

  1. Load Seurat objects - scRNA-seq reference and spatial data
  2. Run CytoSPACER - Direct analysis from Seurat objects
  3. Add results - Integrate results back into Seurat object
  4. Visualize - Use Seurat’s spatial plotting functions

Loading Data

From Seurat Objects

# Load pre-processed Seurat objects
sc_seurat <- readRDS("path/to/scRNA_seurat.rds")
st_seurat <- readRDS("path/to/visium_seurat.rds")

# Check the objects
sc_seurat
st_seurat

From 10x Visium Output

# Load Visium data directly
visium_data <- read_visium_data(
  path = "path/to/spaceranger/output",
  use_seurat = TRUE
)

# Or load with Seurat
st_seurat <- Seurat::Load10X_Spatial("path/to/spaceranger/output")

Running CytoSPACER with Seurat

Direct Analysis

The run_cytospace_seurat() function handles data extraction automatically:

# Run CytoSPACER directly from Seurat objects
results <- run_cytospace_seurat(
  sc_seurat = sc_seurat,
  st_seurat = st_seurat,
  cell_type_col = "celltype",  # Column in metadata with cell type labels
  sc_assay = "RNA",            # Assay to use from scRNA-seq
  st_assay = "Spatial",        # Assay to use from spatial data
  mean_cells_per_spot = 5,
  distance_metric = "pearson",
  seed = 42
)

Using Idents

If cell types are stored as Idents:

# Set cell type identities
Idents(sc_seurat) <- sc_seurat$celltype

# Run without specifying cell_type_col (uses Idents)
results <- run_cytospace_seurat(
  sc_seurat = sc_seurat,
  st_seurat = st_seurat,
  cell_type_col = NULL  # Will use Idents(sc_seurat)
)

Adding Results to Seurat

Basic Integration

# Add CytoSPACER results to spatial Seurat object
st_seurat <- add_cytospace_to_seurat(st_seurat, results)

# Check new metadata columns
head(st_seurat@meta.data)

The function adds:

  • n_cells_cytospace: Number of cells assigned to each spot
  • dominant_celltype_cytospace: Most abundant cell type per spot
  • frac_*: Fractional abundance for each cell type

Visualizing with Seurat

# Spatial plot of dominant cell type
SpatialDimPlot(st_seurat, group.by = "dominant_celltype_cytospace")

# Spatial plot of cell counts
SpatialFeaturePlot(st_seurat, features = "n_cells_cytospace")

# Cell type fractions
SpatialFeaturePlot(st_seurat, features = c("frac_Tumor", "frac_Immune"))

Data Extraction Utilities

Extract scRNA-seq Data

# Extract data for external analysis
sc_data <- extract_seurat_data(
  seurat_obj = sc_seurat,
  assay = "RNA",
  cell_type_col = "celltype"
)

# Returns list with expression matrix and cell types
names(sc_data)
dim(sc_data$expression)
head(sc_data$cell_types)

Extract Spatial Data

# Extract spatial data
st_data <- extract_spatial_data(
  seurat_obj = st_seurat,
  assay = "Spatial",
  image_name = NULL  # Uses first image if NULL
)

# Returns list with expression and coordinates
names(st_data)
dim(st_data$expression)
head(st_data$coordinates)

Save to Files

# Save scRNA-seq data to files
extract_seurat_data(
  seurat_obj = sc_seurat,
  assay = "RNA",
  cell_type_col = "celltype",
  output_dir = "cytospace_input/",
  prefix = "scRNA_",
  sparse = FALSE
)

# Save spatial data to files
extract_spatial_data(
  seurat_obj = st_seurat,
  assay = "Spatial",
  output_dir = "cytospace_input/",
  prefix = "ST_"
)

Complete Workflow Example

library(CytoSPACER)
library(Seurat)

# 1. Load data
sc_seurat <- readRDS("scRNA_processed.rds")
st_seurat <- Load10X_Spatial("visium_output/")

# 2. Preprocess spatial data if needed
st_seurat <- SCTransform(st_seurat, assay = "Spatial", verbose = FALSE)

# 3. Run CytoSPACER
results <- run_cytospace_seurat(
  sc_seurat = sc_seurat,
  st_seurat = st_seurat,
  cell_type_col = "celltype",
  mean_cells_per_spot = 5,
  distance_metric = "pearson",
  n_workers = 4,
  seed = 42
)

# 4. Add results to Seurat object
st_seurat <- add_cytospace_to_seurat(st_seurat, results)

# 5. Visualize
p1 <- SpatialDimPlot(st_seurat, group.by = "dominant_celltype_cytospace")
p2 <- SpatialFeaturePlot(st_seurat, features = "n_cells_cytospace")

# 6. Save results
write_cytospace_results(results, output_dir = "cytospace_output/")
saveRDS(st_seurat, "st_seurat_with_cytospace.rds")

Working with Seurat v5

CytoSPACER automatically detects Seurat version and handles the differences:

# Seurat v5 uses layers instead of slots
# CytoSPACER handles this automatically

# Check Seurat version
packageVersion("Seurat")

# The same code works for both v4 and v5
results <- run_cytospace_seurat(
  sc_seurat = sc_seurat,
  st_seurat = st_seurat,
  cell_type_col = "celltype"
)

Tips and Best Practices

1. Cell Type Annotation Quality

Ensure your scRNA-seq reference has high-quality cell type annotations:

# Check cell type distribution
table(sc_seurat$celltype)

# Visualize reference
DimPlot(sc_seurat, group.by = "celltype", label = TRUE)

2. Gene Overlap

Check gene overlap between scRNA-seq and spatial data:

sc_genes <- rownames(sc_seurat)
st_genes <- rownames(st_seurat)
common_genes <- intersect(sc_genes, st_genes)

cat("scRNA-seq genes:", length(sc_genes), "\n")
cat("Spatial genes:", length(st_genes), "\n")
cat("Common genes:", length(common_genes), "\n")

3. Memory Management

For large datasets, consider subsetting:

# Subsample scRNA-seq reference
sc_subset <- subset(sc_seurat, downsample = 5000)

# Run with subset
results <- run_cytospace_seurat(
  sc_seurat = sc_subset,
  st_seurat = st_seurat,
  cell_type_col = "celltype"
)

Troubleshooting

Common Issues

1. Missing cell type column:

# Check available metadata columns
colnames(sc_seurat@meta.data)

# Ensure cell_type_col exists
if (!"celltype" %in% colnames(sc_seurat@meta.data)) {
  stop("Cell type column not found!")
}

2. No spatial image:

# Check available images
names(st_seurat@images)

# Specify image name if multiple exist
results <- run_cytospace_seurat(
  sc_seurat = sc_seurat,
  st_seurat = st_seurat,
  cell_type_col = "celltype",
  image_name = "slice1"
)

3. Assay not found:

# Check available assays
Assays(sc_seurat)
Assays(st_seurat)

# Specify correct assay names
results <- run_cytospace_seurat(
  sc_seurat = sc_seurat,
  st_seurat = st_seurat,
  cell_type_col = "celltype",
  sc_assay = "RNA",
  st_assay = "Spatial"
)

Session Info

sessionInfo()
#> R version 4.4.0 (2024-04-24)
#> Platform: aarch64-apple-darwin20
#> Running under: macOS 15.6.1
#> 
#> Matrix products: default
#> BLAS:   /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRblas.0.dylib 
#> LAPACK: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.0
#> 
#> locale:
#> [1] C
#> 
#> time zone: Asia/Shanghai
#> tzcode source: internal
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> loaded via a namespace (and not attached):
#>  [1] digest_0.6.39     desc_1.4.3        R6_2.6.1          fastmap_1.2.0    
#>  [5] xfun_0.56         cachem_1.1.0      knitr_1.51        htmltools_0.5.9  
#>  [9] rmarkdown_2.30    lifecycle_1.0.5   cli_3.6.5         sass_0.4.10      
#> [13] pkgdown_2.1.3     textshaping_1.0.4 jquerylib_0.1.4   systemfonts_1.3.1
#> [17] compiler_4.4.0    tools_4.4.0       ragg_1.5.0        bslib_0.9.0      
#> [21] evaluate_1.0.5    yaml_2.3.12       otel_0.2.0        jsonlite_2.0.0   
#> [25] rlang_1.1.7       fs_1.6.6          htmlwidgets_1.6.4