1 Introduction

The scECODA package provides functions for single-cell Exploratory COmpositional Data Analysis at the population scale. It enables users to explore their dataset by visualizing the sample structure and how groups of samples relate to each other by providing numerous convenient plotting and clustering functions. Additionally, it provides metrics to quantify how strongly groups of samples separate and which cell types are driving this separation (differential abundance analysis).

1.1 Motivation for Bioconductor Integration

While many tools exist for supervised comparative single-cell analysis, there is a distinct need for a standardized framework that handles unsupervised exploratory compositional data analysis (ECODA) specifically for large-scale cohorts. scECODA is motivated by the following goals for the Bioconductor ecosystem:

  • Interoperability: The package natively supports core Bioconductor classes, including SingleCellExperiment and SummarizedExperiment, allowing seamless integration into existing pipelines.
  • Infrastructure Synergy: It leverages the established Bioconductor tool DESeq2 for pseudobulk normalization.

2 Installation

You can install the latest stable release of scECODA from Bioconductor.

if (!require("BiocManager", quietly = TRUE))
    install.packages("BiocManager")

BiocManager::install("scECODA")
library(scECODA)

3 Create SummarizedExperiment objects for ECODA

You can create an SummarizedExperiment object from a single-cell data (Seurat or SingleCellExperiment object) or from a data frame containing cell counts or frequencies (in % per sample) with ecoda().

Based on the input, the following data and transformations will be automatically calculated:

  • Cell counts per sample (“counts”)
  • Relative abundance in % (“freq”)
  • Centered log-ratio (CLR) transformed abundance (“clr”)
  • Arc-sine square root transformed abundance (“asin_sqrt”)
  • Optionally: you can get the pseudobulk gene expression per sample, normalized with DESeq2 (“pb”)
  • Metadata

Additionally, it will calculate useful metrics, such as:

  • The variance of each cell type across all samples (in CLR value) in a data frame. It also contains their average abundance (in CLR) and cumulative variance explained.
  • The top n most highly variable cell types (HVCs) (“top_n_hvcs”). The number of HVCs (n) is automatically determined by selecting the most highly variable cell types explaining approximately 50% of the total variance (sum of variances of all cell types). Alternatively, the user can choose the number of cell types n or a variance explained threshold.
  • The names of the top n most highly variable cell types (HVCs) (“hvcs”)
  • The variance explained by the top_n_hvcs (“variance_explained”)
  • Sample distance matrix (“sample_distances”)

NOTE: To calculate CLR-transformed cell type abundances, zero counts or relative abundances are not allowed (log of zero is not defined). By default, scECODA adds a pseudocount of +0.5 to all values if a counts matrix is provided; when the input is a frequency matrix, we add 2/3 times the smallest frequency value as suggested in (Martín-Fernández, Barceló-Vidal, and Pawlowsky-Glahn 2003).

3.1 From SingleCellExperiment object

Load an example dataset from the scRNAseq BioC library.

# Loading an example SingleCellExperiment dataset
library(scRNAseq)

all.ds <- as.data.frame(surveyDatasets())
ds <- 1
sce_object <- fetchDataset(
  all.ds[["name"]][ds],
  all.ds[["version"]][ds]
)

names(colData(sce_object))
## [1] "sample"             "DevelopmentalStage" "DaysPostAmputation"
## [4] "cluster"            "CellCyclePhase"     "Lane"              
## [7] "Condition"          "batch"

To represent this dataset in terms of cell type composition, we will use the cell type labels provided by the authors and stored in the “cluster” metadata field. We will do this for each individual sample (“sample” metadata field). The ecoda() function will do this for you:

# Create ECODA object
se <- ecoda(
  sce_object,
  sample_col = "sample",
  celltype_col = "cluster"
)

The resulting object stores row counts, frequencies and several transformations for the cell type composition by sample. For instance, the clr assay contains centered log-ratio values for the cell types in each sample:

assay(se, "clr")[1:5,1:5]
##                             SIGAA5     SIGAA8    SIGAA10    SIGAA11     SIGAB5
## Alpha ionocyte          -1.4902081 -1.8109108  0.1697487 -1.4273711  0.7809205
## Anterior notochord       1.9437791  1.0223025 -2.6634647 -1.4273711 -2.5149163
## Beta ionocyte           -1.4902081 -0.2014729  1.5992152 -1.4273711  1.7477635
## Dermomyotome             0.1192298  0.1349993 -2.6634647 -0.3287588 -0.9054784
## Differentiating myocyte -1.4902081 -0.7122985 -2.6634647 -0.9165454 -2.5149163

3.2 From Seurat object

Alternatively, scECODA also supports generating compositional matrices from Seurat objects:

# Commented out because Seurat depends on igraph which has not been updated
# to work with R 4.6 yet.

# library(Seurat)
# 
# counts <- counts(sce_object)
# metadata <- as.data.frame(SummarizedExperiment::colData(sce_object))
# 
# seurat_object <- CreateSeuratObject(counts = counts, meta.data = metadata)
# 
# se <- ecoda(
#   seurat_object,
#   sample_col = "sample",
#   celltype_col = "cluster"
# )

3.3 From counts or frequency data frame

If you have a pre-calculated sample x cell type compositional matrix (either as counts or raw frequencies), you can use them directly as input to scECODA. Metadata can be optionally provided and used downstream for visualization.

In this example, we load the immune cell composition in samples from a breast cancer cohort (Zhang et al. 2021)

NOTES:

  • If you create an SummarizedExperiment ECODA object from a data frame containing relative abundances (in %), please use percentage values (e.g. 30 for 30%) and not as decimals (NOT 0.3 for 30%). If the relative abundances sum up to 100%, they will be automatically re-scaled to 100 and you will be informed with a message.
  • If you do add metadata, it is important to make sure that the counts/frequency and the metadata data frames have the same column names.
# Load example datasets
data(example_data)

Zhang <- example_data$Zhang
counts <- Zhang$cell_counts_lowresolution
freq <- calc_freq(counts)
metadata <- Zhang$metadata

se <- ecoda(data = counts, metadata = metadata)

se <- ecoda(data = freq, metadata = metadata)

4 Visualization and quantification of sample separation

4.1 PCA

For explorative analysis, Principal Component Analysis (PCA) can be very useful to find the major axes of variation between samples. You can plot a PCA of your se with plot_pca(se).

se <- ecoda(
  data = example_data$Zhang$cell_counts_lowresolution,
  metadata = example_data$Zhang$metadata,
)

plot_pca(
  se,
  label_col = "Tissue",
  title = "PCA based on cell type composition",
  n_hv_feat_show = 5 # Shows the most highly variable features (cell types)
)

Not all cell types have informative composition (some may be very rare, others constant across samples). It is often more robust to restrict the analysis on highly-variable cell types (HVCs); for example, PCA can be calculated on HVCs:

plot_pca(
  se,
  assay = "clr_hvc",
  label_col = "Tissue",
  title = "PCA based on highly variable cell types",
  n_hv_feat_show = nrow(metadata(se)$clr_hvc)
)

Optionally, we can also add an extra dimension and plot the first 3 principal components:

plot_pca3d(se, label_col = "Tissue")

4.2 Quantifying group separation

Sample separation (based on a user-defined grouping) can be quantified with different metrics, for example:

  • Analysis of similarities (ANOSIM)
  • Adjusted rand index (ARI)
  • Modularity score
  • Average silhouette score (not recommended as it expects gaussian cluster shapes and is not robust to outliers. ANOSIM and modularity are more robust.)
# You can get the separation scores like this:
dist_mat <- dist(assay(se, "clr"))
# Or use the pre-calculated distance matrix based on the CLR abundances:
dist_mat <- metadata(se)$sample_distances

labels <- colData(se)$Tissue

anosim_r_score <- calc_anosim(dist_mat, labels)
ari_score <- calc_ari(dist_mat, labels)
# modularity_score <- calc_modularity(dist_mat, labels)
silhouette_score <- calc_sil(dist_mat, labels)

print(paste("ANOSIM R:", anosim_r_score))
## [1] "ANOSIM R: 0.511"
print(paste("ARI:", ari_score))
## [1] "ARI: 0.639"
# print(paste("Modularity:", modularity_score))
print(paste("Silhouette:", silhouette_score))
## [1] "Silhouette: 0.226"

4.3 Box and bar plots

Box plots are another useful tool to visualize the distribution of cell types across samples:

plot_boxplot(se, title = "CLR Abundance by Cell Type")

If there are biological groupings of interest, we can directly perform statistical tests between the per-sample cell type compositions:

plot_boxplot(
  se,
  label_col = "Tissue",
  title = "CLR Abundance by Cell Type (with Wilcoxon Test)"
)