CytoSignal provides quantitative inference on ligand-receptor interactions at cell/spot level within a single spatial transcriptomics dataset, with dedicated modeling to diffusion-dependent and contact-dependent molecules. This has been demonstrated in the basic tutorial.

In this tutorial, we showcase how to import data from other popular data container classes, such as Seurat (>=5.0), SingleCellExperiment, as well as AnnData stored within H5AD files. We also provide conversion functions to export CytoSignal objects to these formats so that users can perform downstream analyses or use their preferred ways of visualization.

library(cytosignal)

Example data

We utilize pre-constructed Seurat data provided with their extensional package SeuratData (click to see how to install). We will load the released dataset of sagittal mouse brain slices generated using the Visium v1 chemistry.

library(Seurat)
library(SeuratData)

InstallData("stxBrain")
brain <- LoadData("stxBrain", type = "anterior1")
brain
#> An object of class Seurat 
#> 31053 features across 2696 samples within 1 assay 
#> Active assay: Spatial (31053 features, 0 variable features)
#>  1 layer present: counts
#>  1 spatial field of view present: anterior1

Seurat <–> CytoSignal

To convert a Seurat object with spatial transcriptomics data to a CytoSignal object, users simply call SeuratToCS() on the Seurat object. As per Seurat object is designed, users might need to confirm the assay and layer being imported correspond to the spatial transcriptomics data. The spot/cell spatial coordinates will be fetched from the images slot, by default the first image associated with the selected assay. If the Seurat object contains labeling in metadata, it can be passed to argument cluster. Please see ?SeuratToCS for more details.

cs <- SeuratToCS(brain)
cs
#> An object of class CytoSignal
#> Number of cells: 2696 
#> Number of genes: 31053 
#> Number of clusters: 1 
#> Nearest neighbor imputation:  
#>   (default: )
#> LR scores:  
#>   (default: )
#> Parameters:
#> 

Here we perform some basic CytoSignal analyses in order to show how the result will be organized in an output Seurat object.

rownames(cs@raw.counts) <- toupper(rownames(cs@raw.counts))
cs <- addIntrDB(cs, g_to_u, db.diff, db.cont, inter.index)
cs <- removeLowQuality(cs, counts.thresh = 300)
cs <- changeUniprot(cs)
cs <- inferEpsParams(cs, scale.factor = 0.72)
cs <- findNN(cs)
cs <- imputeLR(cs)
cs <- inferIntrScore(cs)
cs <- inferSignif(cs, p.thresh = 0.05, reads.thresh = 100, sig.thresh = 100)
cs <- rankIntrSpatialVar(cs)

To convert a CytoSignal object to a Seurat object, we provide function csToSeurat(). Note that since only spatial coordinates are held in a CytoSignal object, the internal image object created within the output Seurat object will be forced to be of SlideSeq class, even if the original data came from Visium or other platforms.

seu <- csToSeurat(cs)
seu
#> An object of class Seurat 
#> 15226 features across 2696 samples within 2 assays 
#> Active assay: CytoSignal (607 features, 0 variable features)
#>  12 layers present: data.diffusion-Raw, data.diffusion-Raw_smooth, data.contact-Raw, data.contact-Raw_smooth, data.Raw-Raw, data.Raw-Raw_smooth, data.isSignif.diffusion-Raw_smooth.hq, data.isSignif.diffusion-Raw_smooth.spx, data.isSignif.contact-Raw_smooth.hq, data.isSignif.contact-Raw_smooth.spx, data.isSignif.Raw-Raw_smooth.hq, data.isSignif.Raw-Raw_smooth.spx
#>  1 other assay present: Spatial
#>  1 image present: csimage

The Seurat object being returned contains the following information at corresponding location:

  • Assay seu[['Spatial']] - The raw spatial transcriptomics counts data in layer "counts".
  • Metadata variable seu$clusters, if available - The cluster labeling used in the CytoSignal object.
  • Assay seu[['CytoSignal']] - The the same set of spots/cells in the feature space of LR-interactions. It contains the following layers:
    • LayerData(seu, "data.diffusion-Raw") - The LRscore of diffusion-dependent interactions. Similarly for the contact-dependent interactions.
    • LayerData(seu, "data.isSignif.diffusion-Raw_smmoth.spx") - An binary matrix indicating whether the interaction is tested to be significant at a cell/spot.
    • seu[["CytoSignal"]][[]] - The feature (interaction) metadata that contains:
      • rownames() - Unique IDs of the interactions.
      • name - Interpretable name of each interaction.
      • rank_* - The rank of the interaction, for various LRscore type and method used for ranking. (e.g. *.spx indicates ranking inferred by SPARK-X)

Users can then use Seurat commands to do visualization with the object.

library(ggplot2)
library(patchwork)
library(cowplot)
#> 
#> Attaching package: 'cowplot'
#> The following object is masked from 'package:patchwork':
#> 
#>     align_plots

top1_diff_intr <- names(which(seu[['CytoSignal']][["rank_diffusion-Raw_smooth_result.spx", drop = TRUE]] == 1))
top1_diff_intr_name <- seu[['CytoSignal']][["name"]][top1_diff_intr,]
p.intr <- SpatialFeaturePlot(seu, features = top1_diff_intr, pt.size.factor = 4) +
  guides(fill = guide_colorbar(title = "LRscore"))
seu$intr_is_signif <- FetchData(
  object = seu, 
  vars = top1_diff_intr, 
  layer = "data.isSignif.diffusion-Raw_smooth.spx"
) 
seu$intr_is_signif <- as.logical(seu$intr_is_signif)
p.isSignif <- SpatialDimPlot(
  object = seu, 
  group.by = "intr_is_signif", 
  pt.size.factor = 4,
  cols = c('FALSE' = "#D9D9D9", 'TRUE' = "#FF0000")
) +
  guides(fill = guide_legend(title = "Significant spots")) +
  theme(legend.position = "top")
# Note that the internal "image" object in the Seurat object is associated with
# the "CytoSignal" assay. To plot the gene expression of the ligand and receptor
# we need to assign the image to the "Spatial" assay.
seu[['csimage']]@assay <- "Spatial"
# Note that the interaction database is all based on Human data. For the actual
# orthologous genes in mouse, we should treat it as "CCK-CCKBR".
DefaultAssay(seu) <- "Spatial"
# seu <- NormalizeData(seu)
# `Seurat::NormalizeData()` is ridiculously slow, use the equivalent
raw <- LayerData(seu, "counts")
norm <- raw
norm@x <- log1p(norm@x / rep.int(colSums(norm), diff(norm@p)) * 1e4)
LayerData(seu, "data") <- norm
p.L <- SpatialFeaturePlot(seu, features = "CCK", pt.size.factor = 4)
p.R <- SpatialFeaturePlot(seu, features = "CCKBR", pt.size.factor = 4)

plot_grid(
  p.intr, p.isSignif, p.L, p.R, 
  nrow = 2
) +
  plot_annotation(title = "Top 1 interaction: CCKN-GASR (Cck-Cckbr)")

SingleCellExperiment <–> CytoSignal

SingleCellExperiment (SCE) has been another commonly seen data container for single-cell transcriptomics data, and it is set to be the standard for BioConductor. We noticed that BioConductor has developed a spatial-technology-specific extension class, SpatialExperiment, which is built on top of SCE. However, we have not seen any use case of it and there is no handy functions made for this class. Therefore, we only provide conversion functions for SCE objects, while users interested in SpatialExperiment can easily convert the SCE object to it.

library(SingleCellExperiment)
# Build the SCE object from pieces in the initial Seurat object
raw_counts <- GetAssayData(brain, assay = "Spatial", layer = "counts")
cell_location <- as.matrix(GetTissueCoordinates(brain, 'anterior1')[, c("x", "y")])

sce <- SingleCellExperiment(
  assays = list(counts = raw_counts),
  reducedDims = list(spatial = cell_location)
)

cs_from_sce <- SCEToCS(sce, coords = "spatial")
cs_from_sce
#> An object of class CytoSignal
#> Number of cells: 2696 
#> Number of genes: 31053 
#> Number of clusters: 1 
#> Nearest neighbor imputation:  
#>   (default: )
#> LR scores:  
#>   (default: )
#> Parameters:
#> 

We skip the analysis this time as it is exactly the same. Here we convert the previous analyzed CytoSignal object back to an SCE object.

sce_from_cs <- csToSCE(cs)
sce_from_cs
#> class: SingleCellExperiment 
#> dim: 14619 2696 
#> metadata(0):
#> assays(1): counts
#> rownames(14619): XKR4 SOX17 ... AC149090.1 CAAA01118383.1
#> rowData names(0):
#> colnames(2696): AAACAAGTATCTCCCA-1 AAACACCAATAACTGC-1 ...
#>   TTGTTTCACATCCAGG-1 TTGTTTCCATACAACT-1
#> colData names(1): clusters
#> reducedDimNames(1): spatial
#> mainExpName: RNA
#> altExpNames(3): diffusion-Raw_smooth contact-Raw_smooth Raw-Raw_smooth
altExp(sce_from_cs, "diffusion-Raw_smooth")
#> class: SingleCellExperiment 
#> dim: 525 2696 
#> metadata(0):
#> assays(3): lrscore isSignif.hq isSignif.spx
#> rownames(525): CPI-CC0041E1D30 CPI-CC0104F2A96 ... CPI-SS0FEEB187C
#>   CPI-SS0FF49C823
#> rowData names(3): intr.name result.hq result.spx
#> colnames(2696): AAACAAGTATCTCCCA-1 AAACACCAATAACTGC-1 ...
#>   TTGTTTCACATCCAGG-1 TTGTTTCCATACAACT-1
#> colData names(0):
#> reducedDimNames(1): spatial
#> mainExpName: NULL
#> altExpNames(0):

The SCE object comes with:

  • The main experiment for the spatial transcriptomics data
    • counts(sce) - The raw spatial transcriptomics counts data.
    • sce$clusters, if available - The cluster labeling used in the CytoSignal object
    • reducedDim(sce, "spatial") - The spatial coordinates of the spots/cells.
  • Alternative experiments holding the feature space of LR-interactions
    • sce_diff <- altExp(sce, "diffusion-Raw_smooth") - An internal SCE object holding the diffusion-dependent interactions. Similarly for contact-dependent interactions.
      • assay(sce_diff, "lrscore") - The LRscore of the diffusion-dependent interactions.
      • assay(sce_diff, "isSignif.spx") - A binary matrix indicating whether the interaction is tested to be significant at a cell/spot.
      • reducedDim(sce_diff, "spatial") - The duplicate of the spatial coordinates of the spots/cells, for convenience when being visualized.
      • rowData(sce_diff) - The feature (interaction) metadata that contains:
        • rownames() - Unique IDs of the interactions.
        • intr.name - Interpretable name of each interaction.
        • result.* - The rank of the interaction, for method used for ranking. (e.g. *.spx indicates ranking inferred by SPARK-X)

Note that in an SCE object, diffusion-dependent and contact-dependent interactions are stored in separate alternative experiments, different from how we manage it in a Seurat object. This is due to that Seurat V5 allows for mosaic feature/cell data storage.

Next we simply show how to interact with the SCE object and visualize the results.

library(scater)
#> Loading required package: scuttle

sce_from_cs <- logNormCounts(sce_from_cs)
p.L <- plotReducedDim(
  sce_from_cs, dimred = 'spatial', colour_by = 'CCK', 
  point_size = 0.1, point_alpha = 1
) +
  coord_fixed() + 
  theme_void()
p.R <- plotReducedDim(sce_from_cs, dimred = 'spatial', colour_by = 'CCKBR', 
  point_size = 0.1, point_alpha = 1
) +
  coord_fixed() + 
  theme_void()
diff.altExp <- altExp(sce_from_cs, "diffusion-Raw_smooth")
p.intr <- plotReducedDim(
  diff.altExp, 
  dimred = 'spatial', 
  colour_by = top1_diff_intr, 
  by_exprs_values = 'lrscore',
  point_size = 0.1, point_alpha = 1
) +
  coord_fixed() + 
  theme_void() +
  guides(colour = guide_colorbar(title = "LRscore"))
isSignif <- retrieveCellInfo(
  x = diff.altExp, 
  by = top1_diff_intr, 
  search = "assays", 
  exprs_values = "isSignif.spx"
)
diff.altExp$isSignif <- as.logical(isSignif$value)
p.isSignif <- plotReducedDim(
  diff.altExp,
  dimred = 'spatial',
  colour_by = "isSignif",
  point_size = 0.1, 
  point_alpha = 1
) +
  coord_fixed() + 
  theme_void() +
  guides(colour = guide_legend(title = "Significant spots")) +
  scale_color_manual(values = c('FALSE' = "#D9D9D9", 'TRUE' = "#FF0000"))
#> Scale for colour is already present.
#> Adding another scale for colour, which will replace the existing scale.
plot_grid(
  p.intr, p.isSignif, p.L, p.R, 
  nrow = 2, align = 'v', axis = 'lr'
) +
  plot_annotation(title = "Top 1 interaction: CCKN-GASR (Cck-Cckbr)")

AnnData (H5AD) <–> CytoSignal

AnnData is a widely used data container for single-cell transcriptomics data in Python. It is also the standard data container for Scanpy and Squidpy. Given the fact that it is often troublesome to interact between live R and Python sessions, we provide Python-free conversion function in this case to write a CytoSignal object to an H5AD file, file format designed for AnnData basing on HDF5. Users can later load the file to AnnData object in an R-free Python session. We also provide a function to read an H5AD file into a CytoSignal object.

Different than previous demonstration, this time we first write the analyzed CytoSignal object to an H5AD file, and then read it back to a CytoSignal object.

outfile <- tempfile(pattern = 'cs', fileext = '.h5ad')
# Optionally, if you want to save the data to customized location and have a 
# closer look.
# outfile <- "/your/own/path/to/cytosignal.h5ad"
csToH5AD(cs, filename = outfile, overwrite = TRUE)
#> Writing .X
#> Writing .var
#> Writing .obs
#> Writing .obsm['spatial']
#> Writing LR-score from diffusion-Raw to .obsm['diffusion-Raw_score']
#> Writing LR-score from diffusion-Raw_smooth to .obsm['diffusion-Raw_smooth_score']
#> Writing significant spot indication to .obsm['diffusion-Raw_smooth_signif_result']
#> Writing significant spot indication to .obsm['diffusion-Raw_smooth_signif_result.hq']
#> Writing significant spot indication to .obsm['diffusion-Raw_smooth_signif_result.spx']
#> Writing interaction metadata to .uns['CytoSignal']['diffusion-Raw_smooth']
#> Writing LR-score from contact-Raw to .obsm['contact-Raw_score']
#> Writing LR-score from contact-Raw_smooth to .obsm['contact-Raw_smooth_score']
#> Writing significant spot indication to .obsm['contact-Raw_smooth_signif_result']
#> Writing significant spot indication to .obsm['contact-Raw_smooth_signif_result.hq']
#> Writing significant spot indication to .obsm['contact-Raw_smooth_signif_result.spx']
#> Writing interaction metadata to .uns['CytoSignal']['contact-Raw_smooth']
#> Writing LR-score from Raw-Raw to .obsm['Raw-Raw_score']
#> Writing LR-score from Raw-Raw_smooth to .obsm['Raw-Raw_smooth_score']
#> Writing significant spot indication to .obsm['Raw-Raw_smooth_signif_result']
#> Writing significant spot indication to .obsm['Raw-Raw_smooth_signif_result.hq']
#> Writing significant spot indication to .obsm['Raw-Raw_smooth_signif_result.spx']
#> Writing interaction metadata to .uns['CytoSignal']['Raw-Raw_smooth']

The difference from Seurat and SCE is that, since a single AnnData object does not support alternative feature spaces, we simply save the interaction data in .obsm and .uns. Here is a detailed break down, assume you load the H5AD file to an AnnData object adata in Python:

  • adata.X - The raw spatial transcriptomics counts data.
  • adata.obs - The metadata of the spots/cells, including the cluster labeling if available.
  • adata.var - Empty pd.DataFrame, with only gene names.
  • adata.obsm['spatial'] - The spatial coordinates of the spots/cells.
  • adata.obsm['diffusion-Raw_smooth_score'] - The LRscore of the diffusion-dependent interactions. Similarly for contact-dependent interactions.
  • adata.obsm['diffusion-Raw_smooth_signif_result.spx'] - A binary matrix indicating whether the interaction is tested to be significant at a cell/spot. Identify this type of indication by key having the pattern "*_signif_result*".
  • adata.uns['CytoSignal'] - A dictionary primarily for metadata of the interactions.
    • adata.uns['CytoSignal']['diffusion-Raw_smooth'] - A pd.DataFrame containing the metadata of the diffusion-dependent interactions. Similarly for contact-dependent interactions.
      • adata.uns['CytoSignal']['diffusion-Raw_smooth']['name'] - Interpretable name of each interaction.
      • adata.uns['CytoSignal']['diffusion-Raw_smooth']['rank_*'] - The rank of the interaction, for various LRscore type and method used for ranking. (e.g. *.spx indicates ranking inferred by SPARK-X)

Below we show the visualization of the same set of information as previously shown in Seurat and SCE. Run in Python.

import scanpy as sc

# outfile = "/your/own/path/to/cytosignal.h5ad"
# top1_diff_intr = "CCK-CCKBR"
adata = sc.read_h5ad(outfile)
adata
#> AnnData object with n_obs × n_vars = 2696 × 14619
#>     obs: 'cluster'
#>     var: 'name'
#>     uns: 'CytoSignal'
#>     obsm: 'Raw-Raw_score', 'Raw-Raw_smooth_score', 'Raw-Raw_smooth_signif_result', 'Raw-Raw_smooth_signif_result.hq', 'Raw-Raw_smooth_signif_result.spx', 'contact-Raw_score', 'contact-Raw_smooth_score', 'contact-Raw_smooth_signif_result', 'contact-Raw_smooth_signif_result.hq', 'contact-Raw_smooth_signif_result.spx', 'diffusion-Raw_score', 'diffusion-Raw_smooth_score', 'diffusion-Raw_smooth_signif_result', 'diffusion-Raw_smooth_signif_result.hq', 'diffusion-Raw_smooth_signif_result.spx', 'spatial'
import matplotlib.pyplot as plt
import numpy as np

# Set 2x2 panels
fig, axs = plt.subplots(2, 2, figsize=(10, 10))

sc.pl.spatial(adata, color='CCK', spot_size=150, ax=axs[0,0], show=False)
sc.pl.spatial(adata, color='CCKBR', spot_size=150, ax=axs[0,1], show=False)

intr_index = np.where(adata.uns['CytoSignal']['diffusion-Raw_smooth'].index == top1_diff_intr)[0][0]
adata.obs['LRscore'] = adata.obsm['diffusion-Raw_smooth_score'][:,intr_index].A
sc.pl.spatial(adata, color='LRscore', spot_size=150, ax=axs[1,0], show=False)

adata.obs['isSignif'] = adata.obsm['diffusion-Raw_smooth_signif_result.spx'][:,intr_index].A == 1
adata.obs['isSignif'] = adata.obs['isSignif'].astype('category')
sc.pl.spatial(adata, color='isSignif', spot_size=150, ax=axs[1,1], 
              palette={False: '#D9D9D9', True: '#FF0000'}, 
              title='Significant spots', show=False)

plt.suptitle(f'Top 1 interaction: CCKN-GASR (Cck-Cckbr)', fontsize=16)
plt.tight_layout()
plt.show()

Finally, we show the command to read an H5AD file to a CytoSignal object. Unlike Seurat and SCE where the location of desired raw counts matrix is fixed, users will need to make sure to specify the correct layer name for the raw counts matrix in the H5AD file. Use "X" for adata.X, "raw/X" for adata.raw.X, or "layers/key" for adata.layers['key'].

cs_from_h5ad <- H5ADToCS(filename = outfile, layer = "X")
cs_from_h5ad
#> An object of class CytoSignal
#> Number of cells: 2696 
#> Number of genes: 14619 
#> Number of clusters: 1 
#> Nearest neighbor imputation:  
#>   (default: )
#> LR scores:  
#>   (default: )
#> Parameters:
#>