Package 'decontX'

Title: Decontamination of Single Cell Genomics Data
Description: This package contains implementation of DecontX (Yang et al. 2020) <doi:10.1186/s13059-020-1950-6>, a decontamination algorithm for single-cell RNA-seq, and DecontPro (Yin et al. 2024) <doi:10.1093/nar/gkad1032>, a decontamination algorithm for single cell protein expression data. DecontX is a novel Bayesian method to computationally estimate and remove RNA contamination in individual cells without empty droplet information. DecontPro is a Bayesian method that estimates the level of contamination from ambient and background sources in CITE-seq ADT dataset and decontaminate the dataset.
Authors: Yuan Yin [aut] (ORCID: <https://orcid.org/0000-0001-9261-6061>), Masanao Yajima [aut] (ORCID: <https://orcid.org/0000-0002-7583-3707>), Joshua Campbell [aut, cre] (ORCID: <https://orcid.org/0000-0003-0780-8662>)
Maintainer: Joshua Campbell <[email protected]>
License: MIT + file LICENSE
Version: 1.11.34
Built: 2026-11-13 21:59:38 UTC
Source: https://github.com/bioc/decontX

Help Index


The 'decontX' package.

Description

DecontX is a decontamination algorithm for single-cell RNA-seq data. DecontPro is a decontamination and background removal algorithm for single cell protein expression data such as CITE-seq or Total-seq.

See vignette("decontX", package = "decontX") and vignette("decontPro", package = "decontX") to get started, and citation("decontX") to cite the methods.

Value

None; this page documents the package.

References

Yang S, Corbett SE, Koga Y, Wang Z, Johnson WE, Yajima M, Campbell JD (2020). Decontamination of ambient RNA in single-cell RNA-seq with DecontX. Genome Biology, 21(1), 57. doi:10.1186/s13059-020-1950-6

Yin Y, Yajima M, Campbell JD (2024). Characterization and decontamination of background noise in droplet-based single-cell protein expression data with DecontPro. Nucleic Acids Research, 52(1), e4. doi:10.1093/nar/gkad1032

Stan Development Team (2022). RStan: the R interface to Stan. R package version 2.21.7. https://mc-stan.org


Decontaminate using decontPro

Description

Decontaminate using decontPro

Usage

decontPro(filtered_counts, cellType, ...)

## S4 method for signature 'SingleCellExperiment'
decontPro(
  filtered_counts,
  cellType,
  deltaSd = 2e-05,
  backgroundSd = 2e-06,
  background = NULL,
  ...,
  iter = 50000,
  seed = 12345,
  verbose = TRUE
)

## S4 method for signature 'Seurat'
decontPro(
  filtered_counts,
  cellType,
  deltaSd = 2e-05,
  backgroundSd = 2e-06,
  background = NULL,
  ...,
  iter = 50000,
  seed = 12345,
  verbose = TRUE
)

## S4 method for signature 'ANY'
decontPro(
  filtered_counts,
  cellType,
  deltaSd = 2e-05,
  backgroundSd = 2e-06,
  background = NULL,
  ...,
  iter = 50000,
  seed = 12345,
  verbose = TRUE
)

Arguments

filtered_counts

Count matrix NxM (feature x droplet) with only filtered droplets after cell calling, with at least 2 ADTs and 2 droplets. The counts must be non-negative whole numbers with no NA. If this is a SingleCellExperiment or a Seurat object, expect counts in the assay slot. Split counts layers of a Seurat v5 assay are joined first, so the droplets follow Cells().

cellType

Vector of length M giving the cell type of each droplet, with no NA. Any labels can be used, such as integers, character strings or a factor. The rows of r_est in the returned parameters follow the sorted labels, or a factor's levels with unused levels dropped. Alias: cell_type.

...

Only the aliases cell_type, delta_sd, background_sd and ambient_counts, which can be used in place of cellType, deltaSd, backgroundSd and background. Giving both names of an argument, or any other argument, stops with an error.

deltaSd

Standard deviation of the half-normal prior on how much the ambient contamination levels vary around each droplet's mean level. Smaller values keep the levels of a droplet closer together. Default 2e-5. Alias: delta_sd.

backgroundSd

Standard deviation of the half-normal prior on how much the levels of the model's background component vary around each ADT's mean level. This background is part of the model, not the background counts. Default 2e-6. Alias: background_sd.

background

Count matrix (feature x droplet) of empty droplets, used to estimate the ambient ADT profile; without it, the profile comes from filtered_counts. Only each ADT's total across these droplets (the row sums) is used, pooled into one ambient profile, so the droplets must be empty: remove the called cells of filtered_counts first. Similar to filtered_counts, if it is a wrapper object, expect counts in the assay slot. When both have row names, its rows are matched to the ADTs of filtered_counts by name: ADTs that aren't in filtered_counts are dropped, and every ADT of filtered_counts must be present. Otherwise the rows are matched by position. The ADTs used must have no NA or negative counts. Default NULL. Alias: ambient_counts.

iter

Maximum number of iterations of Stan's variational inference. The fit usually stops earlier, when it converges; each iteration takes longer on larger data. Default 50000.

seed

Seed for Stan's random number generator, a whole number from 0 to .Machine$integer.max. Default 12345.

verbose

Whether to print messages and Stan's progress. With FALSE, Stan's output is shown only if the fit fails. Default TRUE.

Value

A list. Each count of filtered_counts is split into three parts, which add up to it:

decontaminated_counts

The native part: the counts from the cell's own proteins. An ADT x droplet matrix with the row and column names of filtered_counts.

ambient_counts

The ambient part, a matrix like decontaminated_counts.

background_counts

The part from the model's background component, a matrix like decontaminated_counts.

parameters

A list of the model's estimates: delta_sd and background_sd, the values of deltaSd and backgroundSd used; r_est, the native ADT profile of each cell type (cell type x ADT, rows named by the cellType labels, each row summing to 1); p_est, the ambient ADT profile (one value per ADT, summing to 1, named by the row names of the matrix it comes from, if any); delta_est, the weight of the ambient profile in the non-background part of each ADT in each droplet, the native profile getting the rest (ADT x droplet); delta_mean_est, its mean level in each droplet; background_est, the background as a proportion of the droplet's total count (ADT x droplet); and background_mean_est, its mean level for each ADT. Except for p_est and the rows of r_est, these have no names: their ADTs and droplets follow the rows and columns of filtered_counts.

Examples

# Simulated counts of 10 ADTs (rows) in 8 droplets (columns)
set.seed(1)
counts <- matrix(rpois(80, lambda = 20), nrow = 10)

# The cell type of each droplet
cellTypes <- c("A", "A", "A", "A", "B", "B", "B", "B")

# Simulated counts of the same 10 ADTs in 8 empty droplets (optional)
emptyDroplets <- matrix(rpois(80, lambda = 2), nrow = 10)

# Decontaminate the counts
out <- decontPro(counts, cellTypes, background = emptyDroplets)

# The decontaminated counts
decontaminatedCounts <- out$decontaminated_counts

Contamination estimation with decontX

Description

Identifies contamination from factors such as ambient RNA in single cell genomic datasets.

Usage

decontX(x, ...)

## S4 method for signature 'SingleCellExperiment'
decontX(
  x,
  assayName = "counts",
  z = NULL,
  batch = NULL,
  background = NULL,
  bgAssayName = NULL,
  bgBatch = NULL,
  maxIter = 500,
  delta = c(10, 10),
  estimateDelta = TRUE,
  convergence = 0.001,
  iterLogLik = 10,
  varGenes = 5000,
  dbscanEps = 1,
  seed = 12345,
  legacyInit = FALSE,
  logfile = NULL,
  verbose = TRUE,
  embedding = TRUE,
  numThreads = 1
)

## S4 method for signature 'ANY'
decontX(
  x,
  z = NULL,
  batch = NULL,
  background = NULL,
  bgBatch = NULL,
  maxIter = 500,
  delta = c(10, 10),
  estimateDelta = TRUE,
  convergence = 0.001,
  iterLogLik = 10,
  varGenes = 5000,
  dbscanEps = 1,
  seed = 12345,
  legacyInit = FALSE,
  logfile = NULL,
  verbose = TRUE,
  embedding = TRUE,
  numThreads = 1
)

Arguments

x

A matrix of counts or a SingleCellExperiment with the matrix located in the assay slot under assayName. The matrix can be a numeric matrix, a sparse matrix from package Matrix or 'SparseArray', or a DelayedMatrix. Cells in each batch will be subsetted and converted to a sparse matrix of class dgCMatrix from package Matrix before analysis. Each batch needs at least 3 cells (15 with legacyInit = TRUE) for the embedding, or 2 with embedding = FALSE. This object should only contain filtered cells after cell calling. Empty cell barcodes (low expression droplets before cell calling) are not needed to run DecontX.

...

For the generic, further arguments to pass to each method.

assayName

Character. Name of the assay to use if x is a SingleCellExperiment.

z

Numeric, character or factor vector. Cell cluster labels, which the result's z returns as a factor of the same labels. If NULL, PCA will be used to reduce the dimensionality of the dataset initially, 'runUmap' from the 'scrapper' package will be used to further reduce the dataset to 2 dimensions and the 'dbscan' function from the 'dbscan' package will be used to identify clusters of broad cell types. If dbscan finds only one cluster, k-means on the PCA components (on all genes with legacyInit = TRUE) splits the cells into two. z needs at least two clusters in each batch, unless background is supplied: with background, one cluster is allowed, which fits only when the cells are a single cell type. Default NULL.

batch

Numeric or character vector. Batch labels for cells. If batch labels are supplied, DecontX is run on cells from each batch separately. Cells run in different channels or assays should be considered different batches. Labels must not be empty strings. Default NULL.

background

A matrix of counts or a SingleCellExperiment with the matrix located in the assay slot under assayName. It must be a SingleCellExperiment when x is one, and otherwise one of the matrix classes x accepts. It contains the empty droplets instead of cells. When supplied, empirical distribution of transcripts from these empty droplets will be used as the contamination distribution. When both have row names, its rows are matched to the genes of x by name: genes that aren't in x are dropped, and every gene of x must be present. Otherwise the rows are matched by position. Barcodes that are also in x are removed. With background, z may have a single cluster. Default NULL.

bgAssayName

Character. Name of the assay to use if background is a SingleCellExperiment. Default to same as assayName.

bgBatch

Numeric or character vector. Batch labels for background, one per column. Its unique values must be the same as those in batch, such that each batch of cells have their corresponding batch of empty droplets as background, pointed by this parameter: every batch needs at least one droplet, after barcodes that are also in x are removed. Labels must not be empty strings. It needs batch and background. Default to NULL.

maxIter

Integer. Maximum iterations of the EM algorithm. Default 500.

delta

Numeric Vector of length 2. Concentration parameters for the Dirichlet prior for the contamination in each cell. The first element is the prior for the native counts while the second element is the prior for the contamination counts. These essentially act as pseudocounts for the native and contamination in each cell. If estimateDelta = TRUE, this is only used to produce a random sample of proportions for an initial value of contamination in each cell. Then fit_dirichlet is used to update delta in each iteration. If estimateDelta = FALSE, then delta is fixed with these values for the entire inference procedure. Fixing delta and setting a high number in the second element will force decontX to be more aggressive and estimate higher levels of contamination at the expense of potentially removing native expression. Default c(10, 10).

estimateDelta

Boolean. Whether to update delta at each iteration.

convergence

Numeric. The EM algorithm will be stopped if the maximum difference in the contamination estimates between the previous and current iterations is less than this. Default 0.001.

iterLogLik

Integer. Calculate log likelihood every iterLogLik iteration. Default 10.

varGenes

Integer. The number of variable genes to use in dimensionality reduction before clustering. Variability is calculated using modelGeneVariances from the 'scrapper' package (or by the variance of the log-normalized counts when legacyInit = TRUE). If z is provided, it is used only for the UMAP stored in the results, and not at all with embedding = FALSE. Default 5000.

dbscanEps

Numeric. The clustering resolution parameter used in 'dbscan' to estimate broad cell clusters. Used only when z is not provided. Default 1.

seed

Integer. Seed for reproducibility: the estimation for each batch (including the EM algorithm) is wrapped in with_seed, and the 'scrapper' UMAP used for cell cluster initialization is seeded explicitly. A default value of 12345 is used. If NULL, no seeding is performed and results are not reproducible between runs (only the scrapper UMAP itself, which has fixed internal default seeds, stays deterministic).

legacyInit

Logical. Use the original scater/scuttle-based initialization (log-normalization and UMAP) to reproduce results from decontX 1.11.0 and earlier. This option requires the 'scater' package and may emit deprecation warnings from scater/scuttle, whose normalization functions were deprecated in favor of the 'scrapper' package. It is kept for backwards compatibility and will remain available as long as the upstream functions are still provided by scater/scuttle. If z is provided, it is used only for the UMAP stored in the results, and not at all with embedding = FALSE. Default FALSE.

logfile

Character. Messages will be redirected to a file named logfile. If NULL, messages will be printed to stdout. Default NULL.

verbose

Logical. Whether to print log messages. Default TRUE.

embedding

Logical. Whether to compute the low-dimensional embedding of the cells (currently a UMAP) that decontX uses to estimate the cell clusters and stores in the results. When z is provided, the embedding is used only for the stored results, so embedding = FALSE skips it, which saves most of the run time on large data sets; the decontamination is the same either way (except with legacyInit = TRUE and seed = NULL, where the legacy UMAP draws from the session's random numbers before the EM). Then no UMAP is stored, and plotDecontXContamination can plot the contamination on another embedding with reducedDimName. embedding = FALSE needs z. Default TRUE.

numThreads

Integer. Number of threads for computing the embedding (variable genes, PCA and UMAP). With more than one thread the PCA can differ in the last digits on large data sets, which can move the UMAP coordinates and change estimated clusters, so use the same numThreads to reproduce a run. With legacyInit = TRUE, only the UMAP uses the threads; it was the same with one and four threads on 8,000 simulated cells. Has no effect with embedding = FALSE. Default 1.

Value

If x is a matrix-like object, a list will be returned with the following items:

decontXcounts:

The decontaminated matrix, a sparse dgCMatrix whatever the class of x, or a DelayedMatrix when x is one. The DelayedMatrix holds the sparse result in memory, also when x is on disk (for example an HDF5Matrix); to keep it on disk, save it explicitly, for example with HDF5Array::writeHDF5Array(). Values obtained from the variational inference procedure may be non-integer. However, integer counts can be obtained by rounding, e.g. round(decontXcounts).

contamination:

The proportion of each cell's counts estimated to be contamination, between 0 and 1.

estimates:

List of estimated parameters for each batch, including the UMAP coordinates (UMAP), which are used to generate the cell cluster labels when z is not supplied. UMAP is NULL with embedding = FALSE. The columns of phi and eta are named by cluster label, in the order of the levels of the batch's z.

z:

Factor of the cell cluster labels used for analysis. A supplied z comes back with its own labels: a factor keeps its level order, without unused levels, and other vectors get sorted levels. Estimated clusters are numbered 1 to K in each batch. When batch is supplied, the labels are prefixed with the batch ("<batch>-<label>") for estimated clusters, and for a supplied z that has a label in more than one batch, since the same label may then name different clusters. Prefixed labels are ordered by the batch's first cell, then by label. The z in each batch's estimates has no prefix.

runParams:

List of arguments used in the function call. Its batch and batchBackground are the batch of each cell and of each background droplet used for the run. It always has batchBackground, which is NULL when background and bgBatch are both NULL.

batch:

Character vector of the batch of each cell used for the run, "all_cells" for every cell when batch is NULL.

If x is a SingleCellExperiment, then the decontaminated counts will be stored as an assay and can be accessed with decontXcounts(x). The contamination values and cluster labels will be stored in colData(x). estimates and runParams will be stored in metadata(x)$decontX. The UMAPs used to generated cell cluster labels will be stored in reducedDims slot in x, except with embedding = FALSE. Running decontX again on x replaces the assay, the colData columns and metadata(x)$decontX. A UMAP from an earlier run (decontX_UMAP or decontX_<batch>_UMAP) stays in reducedDims when the new run doesn't replace it, because the batches differ or the new run has embedding = FALSE, and it doesn't match the new results. When the counts are on disk, the decontXcounts assay is held in memory; save the object with, for example, HDF5Array::saveHDF5SummarizedExperiment() to keep it on disk.

Author(s)

Shiyi Yang, Yuan Yin, Joshua Campbell

Examples

# Generate matrix with contamination
s <- simulateContamination(seed = 12345)

library(SingleCellExperiment)
library(scater)
sce <- SingleCellExperiment(list(counts = s$observedCounts))
sce <- decontX(sce)

# Plot contamination on UMAP
plotDecontXContamination(sce)

# Plot decontX cluster labels on the UMAP
plotReducedDim(sce, dimred = "decontX_UMAP",
               colour_by = "decontX_clusters",
               text_by = "decontX_clusters")

# Plot percentage of marker genes detected
# in each cell cluster before decontamination
s$markers
plotDecontXMarkerPercentage(sce, markers = s$markers, assayName = "counts")

# Plot percentage of marker genes detected
# in each cell cluster after contamination
plotDecontXMarkerPercentage(sce, markers = s$markers,
                            assayName = "decontXcounts")

# Plot percentage of marker genes detected in each cell
# comparing original and decontaminated counts side-by-side
plotDecontXMarkerPercentage(sce, markers = s$markers,
                            assayName = c("counts", "decontXcounts"))

# Plot raw counts of indiviual markers genes before
# and after decontamination
plotDecontXMarkerExpression(sce, unlist(s$markers))

Get or set decontaminated counts matrix

Description

Gets or sets the decontaminated counts matrix from a a SingleCellExperiment object.

Usage

decontXcounts(object, ...)

decontXcounts(object, ...) <- value

## S4 method for signature 'SingleCellExperiment'
decontXcounts(object, ...)

## S4 replacement method for signature 'SingleCellExperiment'
decontXcounts(object, ...) <- value

Arguments

object

A SingleCellExperiment object.

...

For the generic, further arguments to pass to each method.

value

A matrix to save as an assay called decontXcounts

Value

If getting, the assay from object with the name decontXcounts will be returned. If setting, a SingleCellExperiment object will be returned with decontXcounts listed in the assay slot.

See Also

assay and assay<-

Examples

# Simulate contaminated counts and store them in a SingleCellExperiment
library(SingleCellExperiment)
sim <- simulateContamination(seed = 12345)
sce <- SingleCellExperiment(list(counts = sim$observedCounts))

# Run decontX with the known cell populations, skipping the UMAP
sce <- decontX(sce, z = sim$z, embedding = FALSE)

# Get the decontaminated counts
decontaminated <- decontXcounts(sce)
decontaminated[1:5, 1:5]

# Replace them, here with the counts rounded to whole numbers
decontXcounts(sce) <- round(decontaminated)

Boxplot of features grouped by cell type

Description

Boxplot of features grouped by cell type

Usage

plotBoxByCluster(
  counts,
  decontaminated_counts,
  cell_type,
  features,
  file = NULL
)

Arguments

counts

original count matrix of nADT x nDroplet.

decontaminated_counts

decontaminated count matrix.

cell_type

1xnDroplet vector of cell_type, one entry per droplet (column of counts).

features

names of ADT to plot. Each must be a rowname of both counts and decontaminated_counts.

file

file name to save the plot into as a pdf. ".pdf" is added unless file already ends in ".pdf". If omitted, return the plot.

Value

A patchwork object with one ggplot per feature, or, if file is given, the path of the saved pdf, invisibly.

Examples

# Simulate a dataset with 3 cells and 2 ADTs
counts <- matrix(c(60, 72, 52, 49, 89, 112),
  nrow = 2,
  dimnames = list(
    c("CD3", "CD4"),
    c(
      "CTGTTTACACCGCTAG",
      "CTCTACGGTGTGGCTC",
      "AGCAGCCAGGCTCATT"
    )
  )
)

decontaminated_counts <- matrix(c(58, 36, 26, 45, 88, 110),
  nrow = 2,
  dimnames = list(
    c("CD3", "CD4"),
    c(
      "CTGTTTACACCGCTAG",
      "CTCTACGGTGTGGCTC",
      "AGCAGCCAGGCTCATT"
    )
  )
)

plotBoxByCluster(
  counts,
  decontaminated_counts,
  c(1, 2, 1),
  c("CD3", "CD4")
)

Plots contamination on UMAP coordinates

Description

A scatter plot of the UMAP dimensions generated by DecontX, or of another reducedDim, with cells colored by the estimated proportion of contamination (between 0 and 1).

Usage

plotDecontXContamination(
  x,
  batch = NULL,
  colorScale = c("blue", "green", "yellow", "orange", "red"),
  size = 1,
  reducedDimName = NULL
)

Arguments

x

Either a SingleCellExperiment with decontX results stored in metadata(x)$decontX or the result from running decontX on a count matrix.

batch

Character. Batch of cells to plot. If NULL, then the first batch in the list will be selected, or every cell when reducedDimName is given. Default NULL.

colorScale

Character vector. Contains the color spectrum to be passed to scale_colour_gradientn from package 'ggplot2'. Default c("blue","green","yellow","orange","red").

size

Numeric. Size of points in the scatterplot. Default 1.

reducedDimName

Character. Name of a reducedDim of x to plot the contamination on instead of the decontX UMAP, for example after running decontX with embedding = FALSE. Its first two columns are used. Only when x is a SingleCellExperiment. With batch, the cells of the batch are found from the batches of the decontX run, so x needs the same cells, in the same order, as that run. Default NULL.

Value

Returns a ggplot object.

Author(s)

Shiyi Yang, Joshua Campbell

See Also

See decontX for a full example of how to estimate and plot contamination.

Examples

# Generate matrix with contamination
s <- simulateContamination(seed = 12345)

library(SingleCellExperiment)
library(scater)
sce <- SingleCellExperiment(list(counts = s$observedCounts))
sce <- decontX(sce)

# Plot contamination on UMAP
plotDecontXContamination(sce)

# Plot decontX cluster labels on the UMAP
plotReducedDim(sce, dimred = "decontX_UMAP",
               colour_by = "decontX_clusters",
               text_by = "decontX_clusters")

# Plot percentage of marker genes detected
# in each cell cluster before decontamination
s$markers
plotDecontXMarkerPercentage(sce, markers = s$markers, assayName = "counts")

# Plot percentage of marker genes detected
# in each cell cluster after contamination
plotDecontXMarkerPercentage(sce, markers = s$markers,
                            assayName = "decontXcounts")

# Plot percentage of marker genes detected in each cell
# comparing original and decontaminated counts side-by-side
plotDecontXMarkerPercentage(sce, markers = s$markers,
                            assayName = c("counts", "decontXcounts"))

# Plot raw counts of indiviual markers genes before
# and after decontamination
plotDecontXMarkerExpression(sce, unlist(s$markers))

Plots expression of marker genes before and after decontamination

Description

Generates a violin plot that shows the counts of marker genes in cells across specific clusters or cell types. Can be used to view the expression of marker genes in different cell types before and after decontamination with decontX.

Usage

plotDecontXMarkerExpression(
  x,
  markers,
  groupClusters = NULL,
  assayName = c("counts", "decontXcounts"),
  z = NULL,
  exactMatch = TRUE,
  by = "rownames",
  log1p = FALSE,
  ncol = NULL,
  plotDots = FALSE,
  dotSize = 0.1
)

Arguments

x

Either a SingleCellExperiment or a matrix-like object of counts.

markers

Character Vector or List. A character vector or list of character vectors with the names of the marker genes of interest.

groupClusters

List. A named list that allows cell clusters labels coded in z to be regrouped and renamed on the fly. For example, list(Tcells=c(1, 2), Bcells=7) would recode clusters 1 and 2 to "Tcells" and cluster 7 to "Bcells". The values are the labels in z, such as the labels of a z supplied to decontX. After a batched decontX run, the labels can have the batch as a prefix ("<batch>-<label>", such as "b1-1"); use the labels as they appear in z. Note that if this is used, clusters in z not found in groupClusters will be excluded. Default NULL.

assayName

Character vector. Name(s) of the assay(s) to plot if x is a SingleCellExperiment. If more than one assay is listed, then side-by-side violin plots will be generated. Default c("counts", "decontXcounts").

z

Character, Integer, or Vector. Indicates the cluster labels for each cell. If x is a SingleCellExperiment and z = NULL, then the cluster labels from decontX will be retrieved from the colData of x (i.e. colData(x)$decontX_clusters). If z is a single character or integer, then that column will be retrieved from colData of x. (i.e. colData(x)[,z]). If x is a counts matrix, then z will need to be a vector the same length as the number of columns in x that indicate the cluster to which each cell belongs. Default NULL.

exactMatch

Boolean. Whether to only identify exact matches for the markers or to identify partial matches using grep. See retrieveFeatureIndex for more details. Default TRUE.

by

Character. Where to search for the markers if x is a SingleCellExperiment. See retrieveFeatureIndex for more details. If x is a matrix, then this must be set to "rownames". Default "rownames".

log1p

Boolean. Whether to apply the function log1p to the data before plotting. This function will add a pseudocount of 1 and then log transform the expression values. Default FALSE.

ncol

Integer. Number of columns to make in the plot. Default NULL.

plotDots

Boolean. If TRUE, the expression of features will be plotted as points in addition to the violin curve. Default FALSE.

dotSize

Numeric. Size of points if plotDots = TRUE. Default 0.1.

Value

Returns a ggplot object.

Author(s)

Shiyi Yang, Joshua Campbell

See Also

See decontX for a full example of how to estimate and plot contamination.

Examples

# Generate matrix with contamination
s <- simulateContamination(seed = 12345)

library(SingleCellExperiment)
library(scater)
sce <- SingleCellExperiment(list(counts = s$observedCounts))
sce <- decontX(sce)

# Plot contamination on UMAP
plotDecontXContamination(sce)

# Plot decontX cluster labels on the UMAP
plotReducedDim(sce, dimred = "decontX_UMAP",
               colour_by = "decontX_clusters",
               text_by = "decontX_clusters")

# Plot percentage of marker genes detected
# in each cell cluster before decontamination
s$markers
plotDecontXMarkerPercentage(sce, markers = s$markers, assayName = "counts")

# Plot percentage of marker genes detected
# in each cell cluster after contamination
plotDecontXMarkerPercentage(sce, markers = s$markers,
                            assayName = "decontXcounts")

# Plot percentage of marker genes detected in each cell
# comparing original and decontaminated counts side-by-side
plotDecontXMarkerPercentage(sce, markers = s$markers,
                            assayName = c("counts", "decontXcounts"))

# Plot raw counts of indiviual markers genes before
# and after decontamination
plotDecontXMarkerExpression(sce, unlist(s$markers))

Plots percentage of cells cell types expressing markers

Description

Generates a barplot that shows the percentage of cells within clusters or cell types that have detectable levels of given marker genes. Can be used to view the expression of marker genes in different cell types before and after decontamination with decontX.

Usage

plotDecontXMarkerPercentage(
  x,
  markers,
  groupClusters = NULL,
  assayName = c("counts", "decontXcounts"),
  z = NULL,
  threshold = 1,
  exactMatch = TRUE,
  by = "rownames",
  ncol = round(sqrt(length(markers))),
  labelBars = TRUE,
  labelSize = 3
)

Arguments

x

Either a SingleCellExperiment or a matrix-like object of counts.

markers

List. A named list indicating the marker genes for each cell type of interest. Multiple markers can be supplied for each cell type. For example, list(Tcell_Markers=c("CD3E", "CD3D"), Bcell_Markers=c("CD79A", "CD79B", "MS4A1") would specify markers for human T-cells and B-cells. A cell will be considered "positive" for a cell type if it has a count greater than threshold for at least one of the marker genes in the list.

groupClusters

List. A named list that allows cell clusters labels coded in z to be regrouped and renamed on the fly. For example, list(Tcells=c(1, 2), Bcells=7) would recode clusters 1 and 2 to "Tcells" and cluster 7 to "Bcells". The values are the labels in z, such as the labels of a z supplied to decontX. After a batched decontX run, the labels can have the batch as a prefix ("<batch>-<label>", such as "b1-1"); use the labels as they appear in z. Note that if this is used, clusters in z not found in groupClusters will be excluded from the barplot. Default NULL.

assayName

Character vector. Name(s) of the assay(s) to plot if x is a SingleCellExperiment. If more than one assay is listed, then side-by-side barplots will be generated. Default c("counts", "decontXcounts").

z

Character, Integer, or Vector. Indicates the cluster labels for each cell. If x is a SingleCellExperiment and z = NULL, then the cluster labels from decontX will be retrieved from the colData of x (i.e. colData(x)$decontX_clusters). If z is a single character or integer, then that column will be retrieved from colData of x. (i.e. colData(x)[,z]). If x is a counts matrix, then z will need to be a vector the same length as the number of columns in x that indicate the cluster to which each cell belongs. Default NULL.

threshold

Numeric. Markers greater than or equal to this value will be considered detected in a cell. Default 1.

exactMatch

Boolean. Whether to only identify exact matches for the markers or to identify partial matches using grep. See retrieveFeatureIndex for more details. Default TRUE.

by

Character. Where to search for the markers if x is a SingleCellExperiment. See retrieveFeatureIndex for more details. If x is a matrix, then this must be set to "rownames".Default "rownames".

ncol

Integer. Number of columns to make in the plot. Default round(sqrt(length(markers)).

labelBars

Boolean. Whether to display percentages above each bar Default TRUE.

labelSize

Numeric. Size of the percentage labels in the barplot. Default 3.

Value

Returns a ggplot object.

Author(s)

Shiyi Yang, Joshua Campbell

See Also

See decontX for a full example of how to estimate and plot contamination.

Examples

# Generate matrix with contamination
s <- simulateContamination(seed = 12345)

library(SingleCellExperiment)
library(scater)
sce <- SingleCellExperiment(list(counts = s$observedCounts))
sce <- decontX(sce)

# Plot contamination on UMAP
plotDecontXContamination(sce)

# Plot decontX cluster labels on the UMAP
plotReducedDim(sce, dimred = "decontX_UMAP",
               colour_by = "decontX_clusters",
               text_by = "decontX_clusters")

# Plot percentage of marker genes detected
# in each cell cluster before decontamination
s$markers
plotDecontXMarkerPercentage(sce, markers = s$markers, assayName = "counts")

# Plot percentage of marker genes detected
# in each cell cluster after contamination
plotDecontXMarkerPercentage(sce, markers = s$markers,
                            assayName = "decontXcounts")

# Plot percentage of marker genes detected in each cell
# comparing original and decontaminated counts side-by-side
plotDecontXMarkerPercentage(sce, markers = s$markers,
                            assayName = c("counts", "decontXcounts"))

# Plot raw counts of indiviual markers genes before
# and after decontamination
plotDecontXMarkerExpression(sce, unlist(s$markers))

Density of each ADT, raw counts overlapped with decontaminated counts

Description

Both curves of an ADT are smoothed with the same bandwidth, computed from the raw and decontaminated counts together, so their heights can be compared.

Usage

plotDensity(counts, decontaminated_counts, features, file = NULL)

Arguments

counts

original count matrix of nADT x nDroplet.

decontaminated_counts

decontaminated count matrix.

features

names of ADT to plot. Each must be a rowname of both counts and decontaminated_counts.

file

file name to save the plot into as a pdf. ".pdf" is added unless file already ends in ".pdf". If omitted, return the plot.

Value

A patchwork object with one ggplot per feature, or, if file is given, the path of the saved pdf, invisibly.

Examples

# Simulate a dataset with 3 cells and 2 ADTs
counts <- matrix(c(60, 72, 52, 49, 89, 112),
  nrow = 2,
  dimnames = list(
    c("CD3", "CD4"),
    c(
      "CTGTTTACACCGCTAG",
      "CTCTACGGTGTGGCTC",
      "AGCAGCCAGGCTCATT"
    )
  )
)

decontaminated_counts <- matrix(c(58, 36, 26, 45, 88, 110),
  nrow = 2,
  dimnames = list(
    c("CD3", "CD4"),
    c(
      "CTGTTTACACCGCTAG",
      "CTCTACGGTGTGGCTC",
      "AGCAGCCAGGCTCATT"
    )
  )
)

plotDensity(
  counts,
  decontaminated_counts,
  c("CD3", "CD4")
)

Retrieve row index for a set of features

Description

This will return indices of features among the rownames or rowData of a data.frame, matrix, or a SummarizedExperiment object including a SingleCellExperiment. Partial matching (i.e. grepping) can be used by setting exactMatch = FALSE.

Usage

retrieveFeatureIndex(
  features,
  x,
  by = "rownames",
  exactMatch = TRUE,
  removeNA = FALSE
)

Arguments

features

Character vector of feature names to find in the rows of x. Features that are NA never match.

x

A data.frame, matrix, or SingleCellExperiment object to search.

by

A single character string. Where to search for features in x. If set to "rownames" then the features will be searched for among rownames(x). If x inherits from class SummarizedExperiment, then by can be one of the fields in the row annotation data.frame (i.e. one of colnames(rowData(x))). Default "rownames".

exactMatch

Boolean. Whether to only identify exact matches or to identify partial matches using grep. Default TRUE.

removeNA

Boolean. If set to FALSE, features not found in x will be given NA and the returned vector will be the same length as features. If set to TRUE, then the NA values will be removed from the returned vector. Default FALSE.

Value

A vector of row indices for the matching features in x.

Author(s)

Yusuke Koga, Joshua Campbell

See Also

'retrieveFeatureInfo' from package 'scater' and regex for how to use regular expressions when exactMatch = FALSE.

Examples

# A small count matrix with 20 genes and 10 cells
counts <- matrix(seq_len(200), nrow = 20, ncol = 10,
                 dimnames = list(paste0("Gene_", 1:20),
                                 paste0("Cell_", 1:10)))

# Find genes by their exact names
retrieveFeatureIndex(c("Gene_1", "Gene_5"), counts)

# Find genes by part of their names
retrieveFeatureIndex(c("ne_5", "ne_7"), counts, exactMatch = FALSE)

Simulate contaminated count matrix

Description

This function generates a list containing two count matrices – one for real expression, the other one for contamination, as well as other parameters used in the simulation which can be useful for running decontamination.

Usage

simulateContamination(
  C = 300,
  G = 100,
  K = 3,
  NRange = c(500, 1000),
  beta = 0.1,
  delta = c(1, 10),
  numMarkers = 3,
  seed = 12345
)

Arguments

C

Integer. Number of cells to be simulated. Default 300.

G

Integer. Number of genes to be simulated. Default 100.

K

Integer. Number of cell populations to be simulated, at least 2, since the contamination comes from the other populations. With few cells, fewer populations may be drawn; at least 2 are still needed. Default 3.

NRange

Integer vector. A vector of length 2 that specifies the lower and upper bounds of the number of counts generated for each cell. Default c(500, 1000).

beta

Numeric. Concentration parameter for Phi. Default 0.1.

delta

Numeric or Numeric vector. Concentration parameter for Theta. If input as a single numeric value, symmetric values for beta distribution are specified; if input as a vector of length 2, the two values will be the shape1 and shape2 parameters of the beta distribution respectively. Default c(1, 10).

numMarkers

Integer. Number of markers for each cell population. Default 3.

seed

Integer. Passed to with_seed. For reproducibility, a default value of 12345 is used. If NULL, no calls to with_seed are made.

Value

A list with the following items:

nativeCounts:

Matrix of the native (real) counts, genes by cells.

observedCounts:

Matrix of the observed counts: the native counts plus the contamination. Both count matrices have gene and cell names.

NByC:

Integer vector. The total observed counts of each cell.

z:

Integer vector. The cell population of each cell.

eta:

Matrix of the contamination distribution of each population, genes by populations.

phi:

Matrix of the native expression distribution of each population, genes by populations.

markers:

List of the marker gene names of each population.

numMarkers:

The number of markers for each population.

contamination:

Numeric vector. The true proportion of contamination in each cell.

Author(s)

Shiyi Yang, Yuan Yin, Joshua Campbell

Examples

contaminationSim <- simulateContamination(K = 3, delta = c(1, 10))