Package 'betterChromVAR'

Title: Improved ChromVAR (Chromatin Variation Across Regions)
Description: A much faster analytical implementation of chromVAR, with additional features, used to infer TF activity from (bulk or single-cell) ATAC-seq data and motif annotations (or binding probabilities). The package also includes the CVnorm normalization method based on the chromVAR logic, and functions to investigate interactions (synergies or antagonisms) between motifs.
Authors: Pierre-Luc Germain [aut, cre] (ORCID: <https://orcid.org/0000-0003-3418-4218>)
Maintainer: Pierre-Luc Germain <[email protected]>
License: GPL (>= 3)
Version: 2.1.0
Built: 2026-11-24 06:19:06 UTC
Source: https://github.com/bioc/betterChromVAR

Help Index


addGCBias

Description

Add the bias column to the object's rowData, containing the regions' proportion of Gs and Cs.

Usage

addGCBias(object, genome)

Arguments

object

An object inheriting RangedSummarizedExperiment or GRanges.

genome

A BSgenome object or any other genome object supported by getSeq.

Value

object with the GC content in mcols(object)$bias (if GRanges) or rowData(object)$bias.

Examples

# not run:
# se <- addGCBias(se, genome)

Coerce bcvBackground to a list

Description

Coerce bcvBackground to a list

Show a bcvBackground object

Subsetting a bcvBackground

Usage

## S4 method for signature 'bcvBackground'
as.list(x)

## S4 method for signature 'bcvBackground'
show(object)

## S4 method for signature 'bcvBackground,ANY,ANY,ANY'
x[i, j, ..., drop = TRUE]

Arguments

x

A bcvBackground object.

object

A bcvBackground object.

i, j

Indices for subsetting (if j is provided, i is ignored).

...

Additional arguments.

drop

Logical, whether to drop dimensions.

Value

A list containing the slots of the object.

Nothing, prints an overview of the object.

An bcvBackground object.


Bin and background data for betterChromVAR (for internal use)

Description

Bin and background data for betterChromVAR (for internal use)


betterChromVAR

Description

A fast, analytic implementation of (and improvement over) chromVAR. This is a wrapper around the getBackgroundBins, computeBackgrounds, and computeDeviationsAnalytic steps. It additionally allows for multithreading. For more control or optimization, see the individual steps.

Usage

betterChromVAR(
  object,
  annotations,
  grouping = NULL,
  nthreads = NULL,
  verbose = FALSE,
  fpc = TRUE,
  ridge = NULL,
  ...
)

Arguments

object

A SummarizedExperiment (or SingleCellExperiment) with an assay 'counts', and with a 'bias' column in rowData(object). Note that the regions should have similar widths.

annotations

Peak annotation (sparse) matrix, with motifs as columns, or a SummarizedExperiment containing this in the first assay. Values should be either logical or between 0 and 1.

grouping

An optional factor or vector coercible to a factor indicating the groupings of the columns of object. This is optionally used to compute the base expectation such that rare cell types are given as much weight as abundant ones. In single-cell data, the grouping can for instance be the interaction of samples and cell types. This should either be a vector coercible to factor of length equal to ncol(object), or a character of length 1 specifying a column of colData(object).

nthreads

Either an integer scalar indicating the number of threads to use, or a BiocParallelParam object.

verbose

Logical; whether to output progress messages (default FALSE).

fpc

Logical; whether to apply the finite-population correction to the null variance used for the z-scores (default TRUE, see computeDeviationsAnalytic).

ridge

An optional positive number, enabling the decorrelation of motifs that share peaks (smaller values decorrelate more strongly; values of 1 to 3 are recommended). By default (NULL), motifs are not decorrelated. See computeDeviationsAnalytic for details.

...

Passed to getBackgroundBins.

Details

Contrarily to the original chromVAR, this function is entirely deterministic, and achieves higher precision and much higher efficiency through two changes:

  1. working with expected background sampling mean and variances, rather than actual permutations, and 2) computing expectations and variance at the level of bias bins, instead of in the peak-space. The function can additionally handles non-binary annotations (e.g. probability scores), a third bias dimension (fragment length bias, which should be stored in rowData(object)$flbias see getBackgroundBins for details), an adaptive kernel width, and ridge-based decorrelation of the motifs.

Value

A SummarizedExperiment containing the adjusted deviations and z-scores for each motif/sample. The rowData additionally contains the number of motif matches and their variability.

Author(s)

Pierre-Luc Germain

References

Schep A.N., Wu B., Buenrostro J.D., Greenleaf W.J. (2017) chromVAR: inferring transcription-factor-associated accessibility from single-cell epigenomic data, Nature Methods, doi: 10.1038/nmeth.4401

Examples

attach(getDummyData())
# if GC content not already in the object, use:
# counts <- addGCBias(counts, genome=YOUR_GENOME)
dev <- betterChromVAR(counts, motifMatches)
dev
# note that this is the exact equivalent of doing:
# bg <- getBackgroundBins(counts)
# bg <- computeBackgrounds(counts, bg)
# dev <- computeDeviationsAnalytic(counts, bg, motifMatches)

computeBackgrounds

Description

computeBackgrounds

Usage

computeBackgrounds(
  object,
  bins,
  grouping = NULL,
  expectation = NULL,
  verbose = FALSE
)

Arguments

object

A SummarizedExperiment (or SingleCellExperiment) with an assay 'counts', or a (sparse) matrix of counts.

bins

A bcvBackground object, as produced by getBackgroundBins.

grouping

An optional factor or vector coercible to a factor indicating the groupings of the columns of object. This is optionally used to compute the base expectation such that rare cell types are given as much weight as abundant ones. In single-cell data, the grouping can for instance be the interaction of samples and cell types. (The name of a colData column of object can also be provided.)

expectation

Optional vector of length equal to nrow(object) giving the expected counts. If NULL, defaults to mean counts (eventually grouped, see grouping and getExpectation).

verbose

Logical; whether to output progress messages.

Value

A bcvBackground object with bins*samples slots filled, for use with computeDeviationsAnalytic.

Examples

attach(getDummyData())
# if GC content not already in the object, use:
# counts <- addGCBias(counts, genome=YOUR_GENOME)

# we fist get the background bins:
bg <- getBackgroundBins(counts)
# then we can compute the backgrounds for each sample:
bg <- computeBackgrounds(counts, bg)
# for use in computeDeviationsAnalytic...

computeDeviationsAnalytic

Description

computeDeviationsAnalytic

Usage

computeDeviationsAnalytic(
  object,
  background,
  annotations,
  verbose = FALSE,
  retSE = TRUE,
  compute = c("deviations", "z", "variability"),
  denominator = c("global", "local", "none"),
  fpc = TRUE,
  ridge = NULL
)

Arguments

object

A SummarizedExperiment (or SingleCellExperiment) with an assay 'counts', and with a 'bias' column in rowData(object). Note that the regions should have similar widths.

background

A bcvBackground object with bins*samples slots filled, as produced by computeBackgrounds.

annotations

Peak annotation (sparse) matrix, with motifs as columns, or a SummarizedExperiment containing this in the first assay. Values should be either logical or between 0 and 1.

verbose

Logical; whether to output progress messages.

retSE

Logical; whether to return a SummarizedExperiment object.

compute

What to compute. Defaults to everything: deviations, z and motif variability.

denominator

The type of denominator to use for the deviations. Either 'global' (default), i.e. the global expectation (same as the original chromVAR), 'local' (background expectation of the cell/sample), or 'none' (denominator of 1). 'global' (default) is recommended.

fpc

Logical, whether to apply finite population correction (see details below). Disable (fpc=FALSE) to reproduce the behavior of the original chromVAR.

ridge

An optional positive number, enabling the decorrelation of motifs that share peaks (see details). Smaller values decorrelate more strongly; values of 1 to 3 are recommended. If NULL (default) or Inf, motifs are not decorrelated.

Details

As in the original chromVAR, the background of each motif is expressed relative to its own expected total accessibility, i.e. the expected counts of the background peaks are rescaled so that their global expectation equals that of the motif's peaks (the first-order equivalent of dividing each background set by its own expected total). This matters mostly in high-depth data such as bulk, where it makes the results closer to those of chromVAR (use fpc=FALSE and tol=NULL to emulate it).

fpc corrects correct the null variance used (as denominator) for the z-scores for the fact that the expectation of each cell is estimated from the cell's own counts, including in peaks containing the motif. This correlation between observed and expected counts reduces the variance of their difference in a way that depends on the proportion of peaks matching the motif. This is negligilbe for motifs matching few peaks, and especially affects prevalent motifs concentrated in a few background bins (e.g. GC-rich motifs). The correction typically has little effect on cell ranking within a motif.

Since peaks carry multiple motifs and some motif families are very similar, the deviations of motifs tend to be correlated, sometimes highly so. If ridge is given, the excess counts of the motifs are deconvoluted using the overlap between them (after background subtraction, and weighted by the expected accessibility of the peaks), with a ridge penalty proportional to ridge and to the size of each motif. Motifs that do not share peaks with others are unaffected, and the signal of nearly identical motifs is split between them. Note that this only removes what is due to shared peaks, and that strong decorrelation (e.g. ridge<1) reduces the signal of the motifs. The decorrelation additionally benefits from annotations that also capture weak matches (see getGradedMatches).

Value

A SummarizedExperiment (or a list if retSE=FALSE).

Examples

attach(getDummyData())
# if GC content not already in the object, use:
# counts <- addGCBias(counts, genome=YOUR_GENOME)

# we fist get the background bins:
bg <- getBackgroundBins(counts)
# then we compute the backgrounds for each sample:
bg <- computeBackgrounds(counts, bg)
# then we can compute the deviations:
dev <- computeDeviationsAnalytic(counts, bg, motifMatches)
dev

computeDeviationsFromKNNbg

Description

Computes analytical deviations using a nearest-neighbor background matrix while optionally excluding peaks containing the target motif from its own background pool.

Usage

computeDeviationsFromKNN(
  object,
  cBg,
  annotations,
  l = 1,
  chunkSize = 1000,
  fpc = TRUE,
  verbose = TRUE
)

Arguments

object

A SummarizedExperiment or sparse matrix of counts.

cBg

The peak-by-peak sparse kNN matrix, as produced by getBackgroundKNN.

annotations

Peak annotation (sparse) matrix, with motifs as columns, or a SummarizedExperiment containing this in the first assay. Values should be either logical or between 0 and 1.

l

Lambda parameter determining the weight by which background peaks containing the foreground motif are scaled in relative importance. Set to 1 to treat them normally (default), to 0 to exclude them entirely (potentially unstable, a small value such as 0.1 is instead recommended).

chunkSize

Number of cells to process simultaneously. Increasing this will increase speed, but also memory consumption.

fpc

Logical; whether to correct the null variance used for the z-scores for the fact that the expectation of each cell is estimated from the cell's own counts in the neighbors of the motif's peaks, some of which are themselves peaks of the motif (default TRUE, see Details and computeDeviationsAnalytic).

verbose

Logical; whether to print progress messages.

Details

This method combines the analytic strategy used by betterChromVAR with Ruochi Zhang's approach to use a continuous, multidimensional background space instead of background bins. If l<1 it downweighs (multiplying them by l) peaks harboring the tested motif from the corresponding motif's background.

Value

A SummarizedExperiment with 'deviations' and 'z' assays. If overall motif variability and their significance are additionally needed, see computeMotifVariability.

Examples

attach(getDummyData())
bg <- getBackgroundKNN(counts)
dev <- computeDeviationsFromKNN(object=counts, cBg=bg,
                                annotations=motifMatches)
dev

computeDeviationsWeighted

Description

A variant of computeDeviationsAnalytic enabling the computation of deviations from weighted foreground counts. Specifically, this functions handles the normalization of the difference in magnitude between the (weighted) foreground and background.

Usage

computeDeviationsWeighted(
  weightedMotifCounts,
  unweightedPeakCounts,
  annotations,
  bg = NULL,
  retSE = TRUE,
  fpc = TRUE,
  ...
)

Arguments

weightedMotifCounts

A matrix of weighted counts per motif (rows) and sample (columns), or a SummarizedExperiment containing this as first assay.

unweightedPeakCounts

A matrix of unweighted counts per peak (rows) and sample (columns), or a SummarizedExperiment containing this as first assay.

annotations

Peak annotation (sparse) matrix, with motifs as columns, or a SummarizedExperiment containing this in the first assay. Values should be either logical or between 0 and 1.

bg

Either a bcvBackground-class object as produced by computeBackgrounds, or a SummarizedExperiment of background peak counts (with bias data in rowData). If missing, will be created based on unweightedPeakCounts.

retSE

Logical; whether to return a SummarizedExperiment object.

fpc

Logical; whether to apply the finite-population correction to the null variance used for the z-scores (see computeDeviationsAnalytic).

...

Passed to getBackgroundBins (can for instance be used to pass bias info if not contained in the objects). Ignored if bg is a bcvBackground-class object.

Details

The background expectation of the (unweighted) peak counts is rescaled, for each motif, by the ratio between the mean weighted and mean unweighted counts of the motif, and its variance by the square of that ratio. This assumes that the weights are similar across the peaks of a motif: if the weights vary a lot between peaks (coefficient of variation CV), the variance of the weighted counts is larger, by a factor ~1+CV^2, than the variance used here, and the z-scores are overestimated accordingly. The finite-population correction (fpc) also assumes that the weighted counts are proportional to the unweighted counts of the same peaks, from which the expectation is estimated. Neither the z-scores nor the deviations depend on the overall magnitude of the weights.

Value

A SummarizedExperiment (or a list if retSE=FALSE). If overall motif variability and their significance are additionally needed, see computeMotifVariability.

See Also

computeDeviationsAnalytic()

Examples

attach(getDummyData())
# if GC content not already in the object, use:
# counts <- addGCBias(counts, genome=YOUR_GENOME)
# For the purpose of this example, we'll use standard (unweighted counts),
# although at this step we'd compute counts weighted in the desired fashion:
motifCounts <- Matrix::t(motifMatches) %*% assay(counts)
dev1 <- computeDeviationsWeighted(motifCounts, counts, motifMatches)
dev1
# in this case, the results are essentially identical to :
dev2 <- betterChromVAR(counts, motifMatches)
sapply(assayNames(dev1), function(a){
  cor(as.vector(assay(dev1, a)), as.vector(assay(dev2, a)))
})

computeMotifReliability

Description

Estimates the reliability of the single-cell deviations of each motif, i.e. the proportion of their variance across cells that is not noise, from the analytic noise variance of the deviations.

Usage

computeMotifReliability(
  dev,
  kappa = 1,
  cellWeights = TRUE,
  nBlocks = 20L,
  chunkSize = 250L
)

Arguments

dev

A SummarizedExperiment as produced by betterChromVAR or computeDeviationsAnalytic, with the assays 'deviations' and 'z'.

kappa

A scalar, a numeric vector (one value per motif), or the output of estimateNoiseKappa, by which the analytic noise variance of the deviations is multiplied, to calibrate (see estimateNoiseKappa). This should not be necessary anymore, and therefore defaults to 1 (no calibration).

cellWeights

Logical; whether to weigh the cells by the precision of their deviations (default TRUE), preventing noisy (e.g. low libsize) cells from dominating the estimates.

nBlocks

The number of blocks of cells used for the (jackknife) estimation of the standard error of the reliability.

chunkSize

The number of motifs processed at a time (this affects only memory usage).

Details

Motifs with a reliability close to 0 carry no cell-level information in the given dataset (and could be discarded for the purpose of analyses at the single-cell level). The p-value (reliability.pval) is that of a one-sided test of the null hypothesis that the deviations of the motif only vary across cells because of noise, i.e. that the reliability is zero. If this is the case, the deviations standardized by their noise standard deviation (and centered on their precision-weighted mean) have a variance of 1. We test whether the observed variance is larger, using the kurtosis-adjusted standard error of the log-variance of Bonett (2006), as in computeMotifVariability (the test does not depend on cellWeights). As it relies on the noise variance, it is sensitive to its calibration: with many cells, even a small underestimation of the noise variance leads to significant p-values for motifs with a negligible reliability, so that the p-value should be interpreted together with the reliability. Adjusted p-values use the Benjamini-Hochberg method.

The estimate is based on the accuracy of the analytic noise variance, which in our hands is excellent. Alternatively, the estimateNoiseKappa function estimates it empirically, but it is slower and based on a subset of the cells.

Value

A data.frame with one row per motif, and the columns reliability, reliability.se, reliability.pval and reliability.adjPval.

Examples

attach(getDummyData())
dev <- betterChromVAR(counts, motifMatches)
computeMotifReliability(dev, nBlocks=5)

computeMotifVariability

Description

computeMotifVariability

Usage

computeMotifVariability(
  z,
  confInt = 0.95,
  n = 100,
  method = c("bonett", "normal", "bootstrap")
)

Arguments

z

A matrix of z-scores (with motifs as rows), or a SummaziedExperiment object with such a matrix in assay z (as produced e.g. by computeDeviationsAnalytic).

confInt

The the confidence interval (a numeric scalar between 0 and 1, default 0.95).

n

The number of bootstrap samples. Ignored unless method="bootstrap".

method

The method used to compute the confidence interval. 'normal' computes it analytically, assuming that the z-scores are normally distributed. 'bonett' (default) adjusts this analytic estimate for kurtosis (based on Bonett, Computational Statistics & Data Analysis, 2006). 'bootstrap' uses bootstrapping, which does not scale very well.

Value

A data.frame containing the variability and confidence interval around it, as well as significance, for each motif. If z is a SummarizedExperiment, the data.frame will be stored in rowData(z).

See Also

computeMotifReliability.

Examples

# we generate random z-scores:
z <- matrix(rnorm(mean=rnorm(10), sd=runif(10, max=2), 200), nrow=10)
var <- computeMotifVariability

CVnorm: chromVAR-inspired ATAC-seq normalization

Description

Corrects ATAC peak counts by removing the effects of technical biases (GC/accessibility) using the chromVAR background binning approach and an optional variance-based bias shrinkage (inspired from the qsmooth package) to preserve group biological signal.

Usage

CVnorm(
  object,
  bias = NULL,
  grouping = NULL,
  smoothGrouping = grouping,
  shrinkMode = c("dampen", "qsmooth"),
  toAssay = "corrected",
  bs = NULL,
  w = 0.1,
  Z = FALSE,
  useWidthAdj = NULL,
  loo = TRUE,
  enforceZeros = TRUE,
  pseudoCount = 1,
  maxShare = 0.1
)

Arguments

object

A matrix of counts, or a SummarizedExperiment-like object with an assay named 'counts'.

bias

A vector of length equal to ncol(object) specifying the per-peak bias (i.e. GC content). If omitted, will try to get it from rowData(object)$bias.

grouping

Optional grouping for the baseline expectation (prevents bias toward more abundant groups). This should either be a vector coercible to factor of length equal to ncol(object), of a character of length 1 specifying a column of colData(object) (if object is a SummarizedExperiment).

smoothGrouping

Optional grouping to determine correction strength. If bias is consistent within these groups, correction is reduced. Accepts the same type of inputs as grouping, and by default takes the same values.

shrinkMode

The way to perform the group-based shrinkage. With shrinkMode="dampen" (default), no corrected is applied in bins when the bias is entirely explained by groups. shrinkMode="qsmooth" instead reproduces the logic of the qsmooth package: if variance in bias is chiefly explained by groups, between group bias will not be corrected, but within-group differences will be. Using this prior to differential analysis however leads to increase Type I error rate, and it should therefore not be used for downstream application.

toAssay

The name of the assay in which to store the corrected data (default 'corrected'). Ignored unless object is a SummarizedExperiment-like object.

bs

Number of bins per dimension (see getBackgroundBins).

w

Standard deviation of the Gaussian kernel for bin smoothing.

Z

Logical; whether to return standardized residuals (Z-scores) instead of the (default) corrected counts.

useWidthAdj

Whether to adjust for the different width of the regions. If omitted, will be TRUE if the average absolute difference to the median width is greater than 10% of the median width. If TRUE, will adjust for pmax(200L,width). If an integer scalar, will adjust for pmax(useWidthAdj,width).

loo

Logical; whether to compute the expectation of each peak without the peak itself (leave-one-out). This is recommended to avoid correcting away real signal from peaks that dominate their bias bin, but is a bit more memory-intensive.

enforceZeros

Logical; whether to enforce that zero counts should remain zeroes after correction (ignored if Z=TRUE).

pseudoCount

A pseudocount, in reads, added to both the observed and expected counts when computing the bias factor. This shrinks towards 1 (no correction) the factors of the bins whose neighborhood contains too few reads to estimate them.

maxShare

Passed to getBackgroundBins: the maximum share that a peak can have in the expectation of its own background.

Value

If object is a matrix, then a matrix of corrected counts of the same dimensions. If object is a SummarizedExperiment-like object, then the object is returned with an extra assay named based on toAssay.

Author(s)

Pierre-Luc Germain

References

  • Schep A.N., Wu B., Buenrostro J.D., Greenleaf W.J. (2017) chromVAR: inferring transcription-factor-associated accessibility from single-cell epigenomic data, Nature Methods, doi: 10.1038/nmeth.4401

  • Hicks SC, Okrah K, Paulson JN, Quackenbush J, Irizarry RA, Corrado Bravo H (2018). “Smooth quantile normalization.” Biostatistics 19 (2), doi: 10.1093/biostatistics/kxx028

Examples

counts_se <- getDummyData()$counts
# if GC content not already in the object, use:
# counts_se <- addGCBias(counts_se, genome=YOUR_GENOME)
counts_se <- CVnorm(counts_se)

discoverMotifInteractions

Description

Discover motifs interacting with a bait motif, based on the betterChromVAR package.

Usage

discoverMotifInteractions(
  dev,
  group,
  covar = c(),
  global = FALSE,
  weights = c("precision", "none")
)

Arguments

dev

A deviations SummarizedExperiment produced by getInteractionsDeviations

group

The column of colData(dev) containing the experimental groups of interest. To column will be coerced to a factor, and all comparisons will be made relative to the first level of the factor.

covar

Optional columns of colData(dev) containing covariates to correct for.

global

Logical; whether to test the contrasts globally, rather than individually. Has no effect when there is a single contrast (i.e. two-group comparison).

weights

The weights to use, either 'precision' (default; weights each sample by the inverse of the variance of the deviations under the null, which accounts for differences in set size and sequencing depth), or 'none' (no weights; not recommended).

Details

For each partner motif, the deviations of the three disjoint sets of sites (bait and partner, bait only, partner only; see getInteractionsDeviations) are combined in each sample in an interaction score, both - baitOnly - partnerOnly, i.e. the extent to which the deviation at sites with both motifs differs from what would be expected if the bait and the partner acted in an additive fashion on the accessibility deviations. This score is then regressed on group (and covar) with limma.

Note that the p-values are meant to be used for ranking rather than calibrated error rates. Moreover, since the classes of sites are aggregated, the p-values indicate reflect the reproducibility across replicates, rather than the generalization across sites. For a test that accounts for the variability across sites and produces calibrated p-values, see peakLevelMotifInteractions.

Value

A data.frame with, for each motif and contrast, the difference in interaction score between the groups, its moderated statistics, and the differences between groups in each of the sets (diff.both, diff.baitOnly, diff.partnerOnly.

Author(s)

Pierre-Luc Germain

Examples

attach(getDummyData())
dev <- getInteractionsDeviations(counts, motifMatches, bait="motif1",
                                 minCount=5)
dev$group <- rep(LETTERS[1:2], each=5)
discoverMotifInteractions(dev, "group")

estimateNoiseKappa

Description

Empirically calibrates, for each motif, the analytic estimate of the noise variance of the single-cell deviations, and estimates the reliability of the single-cell deviations of each motif. This is mostly for development and testing: for practical purposes the analytic estimates are sufficient.

Usage

estimateNoiseKappa(
  object,
  annotations,
  expectation = NULL,
  background = NULL,
  grouping = NULL,
  ncells = 3000L,
  pairs = NULL,
  fpc = TRUE,
  nthreads = NULL,
  chunkSize = 500L,
  cellWeights = TRUE,
  nBlocks = 20L,
  verbose = FALSE,
  ...
)

Arguments

object

A SummarizedExperiment (or SingleCellExperiment) with an assay 'counts', and with a 'bias' column in rowData(object) (as for betterChromVAR), or a (sparse) matrix of counts, in which case background is required.

annotations

Peak annotation (sparse) matrix, with motifs as columns, or a SummarizedExperiment containing this in the first assay.

expectation

Optional vector of expected counts per peak (as used for the computation of the deviations). If NULL, taken from background if available, otherwise computed from object using getExpectation (with grouping).

background

Optional bcvBackground object as produced by getBackgroundBins. If NULL, created from the expectation and the bias in rowData(object).

grouping

Optional grouping of the cells, used to compute the expectation (see betterChromVAR); ignored if expectation is given.

ncells

The (maximum) number of randomly-selected cells to use (default 3000). More cells increase the precision of the estimates (and the running time).

pairs

Logical; whether counts are Tn5 insertions (e.g. ArchR peak matrices), in which case a fragment with both ends in a peak contributes 2 and the read-splitting needs to keep such pairs together. If NULL (default), this is guessed from the data (pairs are assumed if more than half of all counts are in entries with an even value).

fpc

Logical; whether the finite-population correction was applied to the deviations whose noise is to be calibrated (see computeDeviationsAnalytic). This should match the setting used for the deviations passed to smoothDeviationsKNN.

nthreads

Either an integer scalar indicating the number of threads to use, or a BiocParallelParam object (default NULL, i.e. no parallelization). The cells are processed in chunks of chunkSize.

chunkSize

Number of cells processed at a time (per worker). Lower values reduce memory usage.

cellWeights

Logical; whether to weigh the cells by the precision of their deviations (default TRUE) rather than equally. Precision weighting prevents the (many) shallow, very noisy cells from dominating the estimates.

nBlocks

The number of blocks of cells used for the (jackknife) estimation of the standard error of the reliability.

verbose

Logical; whether to output progress messages.

...

Passed to getBackgroundBins (when background is NULL).

Details

The variance of the deviations computed analytically overestimates the noise for some motifs. This function first computes the proportion of the variance that is due to noise in each motif, using the difference between the deviations computed from two independent halves of the reads/fragments. This provides two pieces of information: first, it allows estimating, for each motif, the reliability of its single-cell deviations, understood as the proportion of their variance across cells that is not noise. Second, it enables computing a factor, kappa, that calibrates the analytic variance computed from the deviations (a value close to 1 means that the analytic variance is accurate).

The selection of the cells and the splitting of their reads are random: use set.seed before calling the function for reproducible results (if you provide a BiocParallelParam as nthreads, set its RNGseed).

Value

A data.frame with one row per motif and the columns kappa (to be given to smoothDeviationsKNN), reliability and reliability.se (a jackknife estimate of the standard error of the variability).

See Also

smoothDeviationsKNN

Examples

attach(getDummyData())
res <- estimateNoiseKappa(counts, motifMatches, pairs=FALSE)
res

exploreMotifInteraction

Description

We compare deviations in sites that harbor a single of the two motifs, or the pair of motifs at given distances from each other.

Usage

exploreMotifInteraction(
  counts,
  motifs,
  genome,
  bg = NULL,
  nDistQuantiles = 5L,
  maxDist = 500L,
  minDist = 5L,
  restrictToRegions = FALSE,
  ...
)

Arguments

counts

An object inheriting from RangedSummarizedExperiment, with a bias column in its rowData.

motifs

A named pair of motifs, in a format recognized by matchMotifs.

genome

A BSgenome or FaFile object.

bg

Optional pre-computed background (a bcvBackground object, as produced by computeBackgrounds). If given, the deviations are computed with computeDeviationsAnalytic from this background; otherwise (default) they are computed with betterChromVAR, which estimates it.

nDistQuantiles

The number of distance quantiles between the motif matches (up to maxDist)

maxDist

The maximum distance between matches.

minDist

The minimum distance between the centers of the matches. This excludes overlapping matches, which for similar motifs are not independent observations. To identify competitors (i.e. motifs that bind overlapping sites), this should be disabled by setting it to 0.

restrictToRegions

Logical; whether both motifs should be within the peaks (default FALSE, i.e. one of the matches can be up to maxDist outside of the peak, see motifCoOccurence).

...

Any further argument passed to betterChromVAR (or to computeDeviationsAnalytic if bg is given).

Details

Motif pairs are split according to the distance between their centers (between minDist and maxDist, default 5 to 500) into nDistQuantiles (default 5) similarly-populated quantiles. Deviations are reported for these different bins, as well as for sites harboring only a single motif (i.e. having a match for one of the motifs, and no match of the other within the peak or within maxDist). Peaks with both motifs but at a distance that falls outside of the range of distances are in neither of these sets. If the distances are heavily tied, fewer than nDistQuantiles bins are returned.

Value

A SummarizedExperiment object of deviations for different types of interactions between the motifs.

Author(s)

Pierre-Luc Germain


fitDeviations

Description

A wrapper to fit a model to motif deviations, using limma to estimate posterior variability from a trend with the (log) effective number of matches.

Usage

fitDeviations(
  dev,
  design,
  type = c("deviations", "norm", "z"),
  contrasts = NULL,
  robust = FALSE,
  ...
)

Arguments

dev

A SummarizedExperiment of motif deviations, as produced for instance by betterChromVAR.

design

The design matrix of the experiment, as produced for instance by model.matrix, or a formula (e.g. ~group) using colData columsn of dev.

type

The type of assay to use, either 'deviations' (default, background-adjusted motif deviations), 'z' (z-scores), or 'norm' (set size-normalized z-scores). Deviations is recommended unless the data is very sparse, in which case 'norm' could be better ('norm' and 'z' should give the same significance, but the effect sizes are only comparable across motifs when using 'norm').

contrasts

Optional contrasts, passed to contrasts.fit.

robust

Logical, passed to eBayes; whether the fit of the priors should be robust (not recommended).

...

Other parameters passed to lmFit.

Details

The prior variance of the empirical Bayes moderation is estimated as a function of the log of the effective number of matches of the motifs (Neff, or N for objects that lack it), consistent with the scaling used by normalizeDevsForSize. If there are fewer than 20 motifs, or no variation in set sizes, no trend is used.

Value

A fitted MArrayLM object, which can for instance be used with limma's topTable function to extract differential analysis results.

Examples

dd <- getDummyData()
dev <- betterChromVAR(dd$counts, dd$motifMatches)
dev$group <- rep(LETTERS[1:2], each=5)
fit <- fitDeviations(dev, ~group)
limma::topTable(fit)

# this is equivalent to:
design <- stats::model.matrix(~group, data=SummarizedExperiment::colData(dev))
fit <- fitDeviations(dev, design)
limma::topTable(fit)

getBackgroundBins

Description

Computes chromVAR-like background (i.e. bias) bins, as well as bin-to-bin selection probabilities needed for betterChromVAR.

Usage

getBackgroundBins(
  x,
  bias = NULL,
  flbias = NULL,
  w = 0.1,
  bs = NULL,
  maxShare = 0.1,
  maxWidthFactor = 4,
  pseudo = 0,
  tol = 0.001,
  verbose = TRUE
)

Arguments

x

A SummarizedExperiment containing a 'counts' assay, or a matrix of counts, or a vector of expected (e.g. mean) counts.

bias

A vector of length equal to ncol(object) specifying the per-peak bias (i.e. GC content). If omitted, will try to get it from rowData(x)$bias.

flbias

A vector of length equal to ncol(object) specifying the per-peak fragment length bias (e.g. log10-transformed median length of fragments overlapping each region). If omitted, will try to get it from rowData(object)$flbias. If absent, will use 2-dimensional bias bins (which is already pretty good).

w

Standard deviation of the Gaussian kernel.

bs

Number of bins per dimension. This can be a single integer (total bins = bs^2), or an integer vector of length 2 (if flbias=NULL) or 3 (in which case there are prod(bs) total bins). The values specify the number of bins for, in order: enrichment, GC and fragment length. By default, bs=50 if flbias is not provided (mimicking chromVAR), and bs=c(30, 30, 6) if it is.

maxShare

Optional maximum share that a peak can have in the expectation of its own background. If not NULL, the width of the kernel is increased (up to maxWidth times w) for the bins that would otherwise exceed it, so that sparsely-populated bins draw more from their neighbors.

maxWidthFactor

The maximum factor by which w can be multiplied when maxShare is used.

pseudo

Optional pseudocount to be added. This should not be needed with standard workflows.

tol

The tolerance of the balancing of the bin-to-bin probabilities i.e. the maximum deviation tolerated from 1 of the total weight with which each bin is used in the background of the others. Use tol=NULL to disable the balancing.

verbose

Whether to print processing info.

Details

The procedure underlying this function is the same as in chromVAR::getBackgroundPeaks, with the following differences:

  • Rather than producing a set of background peaks for each input peak, the function returns peak-to-bin mappings and bin-to-bin background selection probabilities, which enables an analytic background computation. It is, as such, entirely deterministic.

  • The function supports the optional use of a third bias dimension, provided through the flbias argument, meant for fragment length bias. This is still an experimental feature.

Value

A bcvBackground object, to be used with computeBackgrounds.

References

Schep A.N., Wu B., Buenrostro J.D., Greenleaf W.J. (2017) chromVAR: inferring transcription-factor-associated accessibility from single-cell epigenomic data, Nature Methods, doi: 10.1038/nmeth.4401

Examples

counts_se <- getDummyData()$counts
background <- getBackgroundBins(counts_se)

getBackgroundKNN

Description

Computes k-nearest neighbors for each peaks based on the continuous, multidimensional bias space. This is inpsired by Ruochi Zhang's approach in scPrinter.

Usage

getBackgroundKNN(
  se,
  expectation = NULL,
  bias = NULL,
  k = 50,
  weights = c("linear", "poly", "none"),
  pseudo = 0.1,
  ...
)

Arguments

se

A SummarizedExperiment containing a 'counts' assay, or a matrix of counts.

expectation

A vector of expectations. If NULL, will use the mean counts of se

bias

A data.frame of sources of bias (beside expectation) to consider (one per column), with the same nrow as se.

k

Number of nearest neighbors to use.

weights

How to weigh the different bias dimensions. If "none", they will not be re-weighted. If 'linear' (default), they are weighted by the absolute Pearson correlation with the over-dispersion. If "poly", by the R^2 of a 2nd degree polynomial fit of the over-dispersion.

pseudo

Pseudocount for log transformation.

...

Passed to findKNN.

Value

A sparse peak-by-peak kNN matrix.

Examples

SE <- getDummyData()$counts
bg <- getBackgroundKNN(SE)

Dummy data for testing purposes

Description

Dummy data for testing purposes

Usage

getDummyData(nRegions = 500, nSamples = 10, nMotifs = 5)

Arguments

nRegions

Number of regions to generate

nSamples

Number of samples to generate

nMotifs

Number of motifs to generate

Value

A list with the slots counts (a peak counts SummarizedExperiment) and matches (a sparse matrix of binary motif matches per peaks)

Examples

out <- getDummyData()
(counts <- out$counts)
matches <- out$motifMatches

getExpectation

Description

Computes expected counts (a glorified rowMeans)

Usage

getExpectation(counts, grouping = NULL, normalize = TRUE)

Arguments

counts

A count matrix, or object inheriting SummarizedExperiment with a 'counts' assay.

grouping

An optional vector of length equal to ncol(counts), indicating the grouping of the cells. If provided, cells will be averaged by group before averaging across groups.

normalize

Logical; whether to normalize data between averaging (but after grouping). Default TRUE and highly recommended if providing grouping.

Value

A vector of expectation for each row of counts

Examples

attach(getDummyData())
e <- getExpectation(counts)

getGradedMatches

Description

Scans regions for motif matches and returns graded (rather than binary) matches, in which weaker matches are given a weight between 0 and 1 according to their score. This is a wrapper around matchMotifs, which needs to be installed.

Usage

getGradedMatches(
  pwms,
  subject,
  genome = NULL,
  pCutoffs = c(5e-04, 5e-05),
  minWeight = 0.05,
  chunkSize = 100L,
  verbose = FALSE,
  ...
)

Arguments

pwms

The motifs, in any of the formats accepted by matchMotifs (e.g. a PWMatrixList).

subject

The regions in which to search for matches, in any of the formats accepted by matchMotifs (e.g. a GRanges, a RangedSummarizedExperiment, or a DNAStringSet).

genome

The genome (e.g. a BSgenome object), needed if subject does not contain the sequences.

pCutoffs

A numeric vector of length 2 indicating the p-value thresholds respectively below which a match starts to receive a weight (lenient threshold), and below which it receives a weight of 1 (stringent threshold).

minWeight

Weights below this value are set to 0 (keeps the annotation sparser).

chunkSize

The number of motifs processed at a time (this affects memory usage and not the results).

verbose

Logical; whether to output progress messages.

...

Passed to matchMotifs.

Details

For each motif and region, the weight is based on the score of the best match in the region: it is 0 at the score corresponding to the lenient threshold (pCutoffs[1]), and increases linearly with the (log-odds) score up to 1 at the score corresponding to the stringent threshold (pCutoffs[2], by default the default threshold of motifmatchr). Regions with a match passing the stringent threshold therefore have the same value as with binary matches.

The two score thresholds of a motif are taken as the lowest scores observed at each cutoff, so that subject should not be too small.

The result is considerably denser than binary matches (e.g. 30-50% non-zero). Graded matches are mostly useful in combination with the decorrelation of the motifs (see the ridge argument of betterChromVAR).

Value

A sparse matrix of weights between 0 and 1, with regions as rows and motifs as columns, which can be used as the annotations of betterChromVAR or computeDeviationsAnalytic.

Examples

# not run:
# matches <- getGradedMatches(pwms, se, genome=genome)
# dev <- betterChromVAR(se, matches, ridge=3)

getInteractionsDeviations

Description

Get betterChromVAR deviations for the sites of a bait motif, split according to whether they also harbor each of the other motifs.

Usage

getInteractionsDeviations(se, annotation, bait, minCount = 20, ...)

Arguments

se

An object inheriting SummarizedExperiment, containing a counts assay.

annotation

A (sparse) matrix or object inheriting SummarizedExperiment containing motif annotations for each row of se. Weighted annotations are binarized (any positive value is a match).

bait

The name of the bait motif (corresponding to a column of annotation), for which to search for interacting motifs.

minCount

The minimum number of sites in each of the sets (see Details) for a motif to be considered.

...

Passed to betterChromVAR. This includes the option to use the ridge argument.

Details

For each other motif (the 'partner'), three disjoint sets of sites are defined: the sites harboring both the bait and the partner (both), only the bait (baitOnly), or only the partner (partnerOnly). Deviations are computed for each, as well as for the bait motif as a whole. Because the sets are disjoint, their deviations can be compared without one containing the other. In addition to deviations and z, the returned object has a sd assay, which is the standard deviation of the deviations under the null (i.e. deviations/z), and is used by discoverMotifInteractions to weight the observations.

Value

A SummarizedExperiment of deviations for the bait and for the sets of sites defined by the intersection of the bait with each other motif. The rowData indicates the partner motif and the type of set of each row, as well as overlap statistics between the bait and the partner.

Examples

attach(getDummyData())
dev <- getInteractionsDeviations(counts, motifMatches, bait="motif1",
                                 minCount=5)
dev

motifCoOccurence

Description

Returns regions that have matches for given pairs of motifs within certain distances of each other.

Usage

motifCoOccurence(
  motifs,
  pairs,
  regions,
  genome,
  centerDist = TRUE,
  minDist = 5,
  maxDist = 50,
  exclusiveDist = TRUE,
  restrictToRegions = FALSE,
  nDistQuantiles = NULL,
  ignore.strand = TRUE
)

Arguments

motifs

A named PFMatrixList or PWMatrixList object containing motifs (only those specified in pairs will be used). If you're not familiar with these objects, see the TFBSTools package, and the universalmotif package on how to convert motifs.

pairs

A list of pairs of motifs for which to compute co-occurence. Specifically, this should be a (optionally named) list of character vectors of length 2, corresponding to names in motifs.

regions

The regions in which to search for motif matches.

genome

A genome object or path to a genome fasta file.

centerDist

Logical; whether to compute distances between the centers of the matches (default). If FALSE, the distance is that between the edges of the matches closest to each other (as in GenomicRanges::distanceToNearest), i.e. 0 for overlapping matches, and so independent of the width of the motifs.

minDist

The minimum distance between matches for a co-occurrence. This is primarily used to exclude interactions between highly-similar, overlapping motifs, and to focus on putative cooperative interactions between TFs. If interested in competing TFs, set this to 0. Also used (as the lower bound of the first bin) when using nDistQuantiles.

maxDist

The maximum distance between the matches for a co-occurence.

exclusiveDist

Logical; whether the co-occurences should be counted only for the smallest of the distance thresholds. Ignored if minDist and maxDist have a length of 1.

restrictToRegions

Logical; whether to restrict the search for motifs to regions. If FALSE (default), one of the motifs still needs to be within the regions, but the other can be +/- maxDist around the region.

nDistQuantiles

The number of distance quantiles to use. Disabled by default and requires exclusiveDist=TRUE. When a positive integer, the span from minDist to maxDist is split into nDistQuantiles number of quantiles for each pair of motifs (in each region, the shortest distance between matches of the two motifs is used).

ignore.strand

Logical; whether to ignore the strand for co-occurence (default TRUE).

Details

Note that both minDist and maxDist, rather than specifying a single threshold, can compute co-occurence for multiple thresholds (which is must faster than running the function multiple times). minDist and maxDist should have the same length, and the corresponding entries will be used together to produce multiple matrices. If exclusiveDist=TRUE, the distance threshold are exclusive, meaning that the higher threshold does not include co-occurences of the lower thresholds. When using multiple exclusive distance bins, it is also possible to have the bin boundaries adjusted for each pair of motifs so that each bin is equally populated by setting nDistQuantiles (the breaks used can be retrieved from attr(results, "breaks") ). If the distances are heavily tied, fewer bins than nDistQuantiles can result (the corresponding matrices are empty). Distances are between the centers of the matches (when centerDist=TRUE) or between their closest edges (otherwise), and a co-occurence is attributed only to the regions that contain one of the two matches (not to those lying in between). Also note that all matches are stored in memory, so using this function across the entire genome is not advisable (unless for very few motifs).

Value

A list of sparse logical matrices, with one matrix for each value of minDist/maxDist (or each quantile bin).

Author(s)

Pierre-Luc Germain


normalizeDevsForSize

Description

Normalizes the z-scores assay of a deviations object to make the scores comparable across motifs with different number of matches.

Usage

normalizeDevsForSize(dev)

Arguments

dev

A SummarizedExperiment object as produced by betterChromVAR or computeDeviationsAnalytic.

Details

If a TF changes the accessibility of all its motif matches by the same relative amount, the z-score of its motif increases with the square root of the effective number of matches, Neff (see the rowData of the object). Neff is smaller than the number of matches N for motifs matching a large share of the peaks in the bins in which they are found, since the expectation of the cells is estimated from the same peaks. The z-scores are multiplied by sqrt(median(Neff)/Neff). For objects without Neff (e.g. produced by earlier versions) N is used instead.

Value

The dev object with an additional assay named 'norm'.

Examples

attach(getDummyData())
dev <- betterChromVAR(counts, motifMatches)
dev <- normalizeDevsForSize(dev)
dev

NR3C1example

Description

A small example dataset of ATAC-seq data upon ligand-based activation of the glucocorticoid receptor (GCR, encoded by the NR3C1 gene) in A549 cells (a subset of the data from McDowell et al., 2018: three control and three treated samples). Loading it (data(NR3C1example)) provides four objects (see Format).

Format

Four objects:

  • peakSE: a RangedSummarizedExperiment of 19,143 peaks by 6 samples, with peak counts (assay counts), a bias column in the rowData and the group and depth columns in the colData.

  • motifMatches: a RangedSummarizedExperiment of 19,143 peaks by 29 motifs, with a logical assay (motifMatches) indicating the matches of each motif in each peak of peakSE.

  • motifs: a PFMatrixList of three motifs (GCR, JUND and CTCFL), for use with functions that need the motifs themselves (e.g. exploreMotifInteraction).

  • didevs: a list with the output of exploreMotifInteraction for the pairs GCR-JUND and GCR-CTCFL (precomputed on the hg38 genome, which is needed to run it).

Examples

data(NR3C1example)
peakSE
motifMatches

peakLevelMotifInteractions

Description

Tests the interaction between a bait motif and other motifs on the differential accessibility of peaks, using the peaks (rather than the samples) as units of inference.

Usage

peakLevelMotifInteractions(
  se,
  annotation,
  bait,
  group,
  covar = c(),
  minCount = 20,
  splineDF = 3,
  adjustWidth = FALSE,
  vif = TRUE,
  useAssay = "counts",
  lib.size = NULL,
  nthreads = NULL
)

Arguments

se

An object inheriting SummarizedExperiment, containing a counts assay (or useAssay), and optionally a bias column in its rowData (see getBackgroundBins).

annotation

A (sparse) matrix or object inheriting SummarizedExperiment containing motif annotations for each row of se.

bait

The name of the bait motif (corresponding to a column of annotation), for which to search for interacting motifs.

group

The column of colData(se) containing the experimental groups of interest. The column will be coerced to a factor, and all comparisons will be made relative to the first level of the factor.

covar

Optional columns of colData(se) containing covariates to correct for.

minCount

The minimum number of peaks in each of the sets (bait and partner, bait only, partner only) for a motif to be considered.

splineDF

The degrees of freedom of the splines used to adjust for accessibility and bias (set to 0 to disable).

adjustWidth

Logical; whether to additionally adjust for the (log-) width of the peaks (default FALSE), taken from rowRanges(se) (or from a width column of rowData(se)). See peakLevelMotifTests.

vif

Logical; whether to inflate the variance to account for the correlation between the peaks of a set (default TRUE).

useAssay

The assay containing the counts.

lib.size

Optional library sizes (default is the column sums of the counts), passed to voom.

nthreads

Either an integer scalar indicating the number of threads to use (the partners are distributed across them), or a BiocParallelParam object. Results do not depend on it.

Details

The differential accessibility between groups (log2-fold-change and its standard error) is first estimated for each peak using limma-voom, with group and covar in the model. For each partner motif and contrast, the log-fold-changes of all peaks are then modeled as a function of the presence of the bait motif, of the partner motif, and of their interaction, together with smooth functions (natural splines) of the peak's mean accessibility and bias. The interaction coefficient is the extent to which the response at sites with both motifs differs from the sum of the effects of each motif alone (on the log scale).

The regression is weighted by the inverse of the variance of the peak's log-fold-change, plus a between-peak variance (random effect) estimated separately for each of the four types of peaks, so that the heterogeneity of the response across sites is part of the uncertainty. In addition, as in camera, the variance of the coefficients is inflated to account for the average correlation between the residuals of the peaks of a same set (estimated across samples, after removing the component shared by all peaks, which cancels out of the contrasts). P-values use a t-distribution with the number of peaks harboring both motifs minus one as degrees of freedom.

The model is fitted separately for each partner, and treats the peaks as independent (beyond the correlation correction), so that very similar motifs matching the same sites cannot be distinguished from a true interaction.

This approach is related to motif activity response analysis (MARA, and its web implementation ISMARA; see the references), which models the signal of regulatory regions as a function of the motifs they harbor. It differs in that the bait and each partner are modeled separately from the other motifs (MARA fits all motifs jointly), that it includes an interaction term, and that it works on the differential accessibility between groups, with a random effect for the heterogeneity across sites and a correction for the correlation between peaks.

Value

A data.frame with, for each motif and contrast, the difference (interaction coefficient, in log2-fold-change), its standard error (se), t-value, p-value and adjusted p-value, the effects of the bait alone (bait.diff) and of the partner alone (partner.diff), and the estimated heterogeneity (tau.both, standard deviation of the true response across sites with both motifs) and excess correlation (rho.both) for the peaks with both motifs.

References

The FANTOM Consortium and the RIKEN Omics Science Center (2009) The transcriptional network that controls growth arrest and differentiation in a human myeloid leukemia cell line, Nature Genetics 41:553-562, doi: 10.1038/ng.375.

Balwierz P.J., Pachkov M., Arnold P., Gruber A.J., Zavolan M., van Nimwegen E. (2014) ISMARA: automated modeling of genomic signals as a democracy of regulatory motifs, Genome Research 24:869-884, doi: 10.1101/gr.169508.113

Examples

attach(getDummyData())
counts$group <- rep(LETTERS[1:2], each=5)
peakLevelMotifInteractions(counts, motifMatches, bait="motif1",
                           group="group", minCount=5)

peakLevelMotifTests

Description

Differential motif accessibility between groups based on the peaks' logFC between conditions. This is a peak-level alternative to the analysis of motif deviations (see fitDeviations).

Usage

peakLevelMotifTests(
  se,
  dea,
  annotation,
  design = NULL,
  minCount = 20,
  splineDF = 3,
  adjustWidth = FALSE,
  vif = TRUE,
  useAssay = "counts",
  lib.size = NULL,
  nthreads = NULL
)

Arguments

se

An object inheriting SummarizedExperiment containing the peak counts (in the counts assay, or useAssay), from which the differential analysis dea was obtained. It defines the peaks (rows), and provides the sample-level data used to estimate the correlation between peaks, as well as the bias column of rowData (see addGCBias), if present (which is very much recommended).

dea

The table of the results of a differential accessibility analysis of the peaks of se (or a named list of such tables, one for each contrast). Should accept major differential analysis packages (see Details for the format).

annotation

A (sparse) matrix or object inheriting SummarizedExperiment containing motif annotations for each row of se. Weighted annotations are binarized (any positive value is a match).

design

Optional design matrix (with a row for each column of se) of the model used for the differential analysis. It is used to estimate the correlation between the peaks (see vif) from the residuals of the model.

minCount

The minimum number of peaks with the motif (and without it) for a motif to be tested.

splineDF

The degrees of freedom of the splines used to adjust for accessibility and bias (set to 0 to disable).

adjustWidth

Logical; whether to additionally adjust for the (log-) width of the peaks (default FALSE), taken from rowRanges(se) (or from a width column of rowData(se)). This is useful when peaks have variable widths, since wider peaks are both more likely to contain a motif and have higher counts. Peaks of constant width are not affected. Alternatively, the peaks can be resized to a fixed width before counting.

vif

Controls the inflation of the variance to account for the correlation between the peaks of a set. Either TRUE (default; the correlation is estimated from the data of se, which requires design; if design is missing the inflation is disabled), FALSE (no inflation; not recommended for large motif sets), or a number between 0 and 1, which is the excess correlation assumed between the peaks of each motif (see Details).

useAssay

The assay of se containing the counts.

lib.size

Optional library sizes (default is the column sums of the counts), used to compute the log-counts-per-million from which the correlation between peaks is estimated.

nthreads

Either an integer scalar indicating the number of threads to use (the motifs are distributed across them), or a BiocParallelParam object. Results do not depend on it.

Details

The differential accessibility between groups (log2-fold-change and its standard error) is first estimated for each peak, using any method, and given as a table (dea) with the peaks of se as rows (matched to the rows of se through the row names if both have some, and otherwise in the same order). The table should contain the log-fold-change (column logFC or log2FoldChange), its standard error (column SE, se or lfcSE) or a statistic from which it can be derived (column t, stat, F or LR), and optionally the average accessibility (column AveExpr, logCPM, Amean, or baseMean; if missing, the mean log-counts-per-million of se is used), as given for instance by limma's topTable (with sort.by="none"), edgeR's topTags or DESeq2's results. Peaks with missing values are ignored. A bias column can be included to adjust for it (otherwise the bias column of the rowData of se is used, if present). The standard error should be the one of the log-fold-change itself (and not of another quantity).

For each motif and contrast, the log-fold-changes of all peaks are then modeled as a function of the presence of the motif, together with smooth functions (natural splines) of the peak's mean accessibility and bias (and optionally width, see adjustWidth). The coefficient of the motif is thus the extent to which peaks with the motif change more (or less) than comparable peaks without it, which is the peak-level analog of a motif deviation (that is, a competitive test).

The regression is weighted by the inverse of the variance of the peak's log-fold-change, plus a between-peak variance (random effect) estimated separately for peaks with and without the motif, so that the heterogeneity of the response across sites is part of the uncertainty. In addition, as in camera (Wu and Smyth 2012), the variance of the coefficients can be inflated to account for the average correlation between the residuals of the peaks of a same set (estimated across samples from the residuals of the model given by design, after removing the component shared by all peaks. If design is not given, an excess correlation can alternatively be assumed through vif.

Compared to the analysis of deviations, this test asks whether the sites of a motif change more than other sites (generalizing across sites), rather than whether the set changes reproducibly across samples, and does not rely on sampling a background. Its power depends on the number of sites of the motif and on how consistently they respond. Each motif is tested separately, so motifs that share sites are not distinguished (see stepwisePeakLevelMotifTests for a way to address this, or the ridge argument of betterChromVAR for decorrelation in the deviation-based analysis).

The model is fitted separately for each motif and contrast, which takes longer than the analysis of deviations when there are many peaks and motifs.

This approach is related in spirit to motif activity response analysis (MARA, and its web implementation ISMARA), which models the signal of regulatory regions as a function of the motifs they harbor. It differs in that motifs are tested separately (MARA fits all motifs jointly), and that it works on the differential accessibility between groups, with a random effect for the heterogeneity across sites and a correction for the correlation between peaks.

Value

A data.frame with, for each motif and contrast, the number of peaks with the motif (N), the difference (log2-fold-change of the peaks with the motif relative to the others), its standard error (se), t-value, p-value and adjusted p-value, and the estimated heterogeneity (tau, standard deviation of the true response across the sites of the motif) and excess correlation (rho) of its peaks.

Author(s)

Pierre-Luc Germain

References

The FANTOM Consortium and the RIKEN Omics Science Center (2009) The transcriptional network that controls growth arrest and differentiation in a human myeloid leukemia cell line, Nature Genetics 41:553-562, doi: 10.1038/ng.375 (motif activity response analysis, MARA).

Balwierz P.J., Pachkov M., Arnold P., Gruber A.J., Zavolan M., van Nimwegen E. (2014) ISMARA: automated modeling of genomic signals as a democracy of regulatory motifs, Genome Research 24:869-884, doi: 10.1101/gr.169508.113

Wu D, Smyth GK (2012). Camera: a competitive gene set test accounting for inter-gene correlation. Nucleic Acids Research 40, e133. doi: 10.1093/nar/gks461

Examples

attach(getDummyData())
counts$group <- rep(LETTERS[1:2], each=5)
# differential accessibility analysis of the peaks:
library(limma)
design <- model.matrix(~group, data=colData(counts))
y <- voom(assay(counts), design)
dea <- topTable(eBayes(lmFit(y, design)), coef=2, number=Inf, sort.by="none")
# peak-level motif tests:
peakLevelMotifTests(counts, dea, motifMatches, design=design, minCount=5)

sampleBackgroundPeaks

Description

Given a background generated by getBackgroundBins, samples background peaks for each input peak.

Usage

sampleBackgroundPeaks(background, niterations = 50)

Arguments

background

A bcvBackground produced by getBackgroundBins.

niterations

Number of background peaks to sample for each target peak.

Details

This function is not used by betterChromVAR, which is deterministic, but for other applications requiring an outputs similar to that of the original chromVAR::getBackgroundPeaks().

Value

A peaks x niterations matrix of integers representing the indices of the sampled background peaks.

Examples

counts_se <- getDummyData()$counts
background <- getBackgroundBins(counts_se)
bg_peaks <- sampleBackgroundPeaks(background, niterations=20)

smoothDeviationsKNN

Description

Adaptive smoothing of single-cell motif deviations across nearest-neighbors.

Usage

smoothDeviationsKNN(
  dev,
  knn,
  k = NULL,
  kappa = 1,
  tauScale = 3,
  retWeights = FALSE,
  blockSize = 250L,
  verbose = FALSE
)

Arguments

dev

A SummarizedExperiment as produced by betterChromVAR or computeDeviationsAnalytic, with the assays 'deviations' and 'z'.

knn

The k-nearest neighbors (kNN) of the cells, in the format returned by findKNN, i.e. a list with an index element (an integer matrix with one row per cell, in the same order as the columns of dev, and one column per neighbor, ordered by distance). The index matrix can also be given directly. The cell itself should not be included in its neighbors (any self-neighbor will be ignored). The kNN should be computed from an embedding that is independent of the motif deviations (e.g. an embedding of the peak counts).

k

The number of neighbors to use. If NULL (default), min(50, ncol(knn$index)) is used.

kappa

A scalar, a numeric vector (one value per motif), or the output of estimateNoiseKappa, by which the analytic noise variance of the deviations is multiplied, to calibrate (see estimateNoiseKappa). This should not be necessary anymore, and therefore defaults to 1 (no calibration).

tauScale

A multiplier applied to the estimated biological variance. Higher values mean less smoothing (default 3).

retWeights

Logical; whether to additionally return, as assay 'own.weight', the weight attributed to each cell's own value (0 to 1).

blockSize

The number of motifs processed at a time (this affects only memory usage).

verbose

Logical; whether to output progress messages.

Details

The deviation of each cell is shrunk towards the mean deviation of its k nearest neighbors, with the weight kept on the cell's own value being

λ=τ2+vτ2+v+σ2\lambda = \frac{\tau^2 + v}{\tau^2 + v + \sigma^2}

where σ2\sigma^2 is the noise variance of the cell's own deviation (obtained from deviations/z, and multiplied by kappa), vv the sampling variance of the neighbors' mean (the mean being weighted by the precision of each neighbor's deviation, i.e. cells with more information count more), and τ2\tau^2 the biological variance, specific to each motif, of the cells' activity around the mean of their neighborhood, which is estimated across all cells (method of moments). Cells with more information (i.e. smaller noise variance, such as the cells with the most fragments) and motifs that show real cell-to-cell variation are therefore smoothed less. Motifs with no detectable variation between neighboring cells are smoothed strongly.

The shrinkage assumes that neighboring cells have a similar motif activity. Effects that are specific to individual cells, and small relative to the noise, cannot be distinguished from the noise and therefore risk being smoothed out; tauScale can be increased to reduce this at the expense of less noise reduction.

Value

dev with the additional assays 'smoothed' (the smoothed deviations), 'smoothed.z' (the smoothed deviations divided by their standard deviation under the null hypothesis that the deviation is zero in the cell and its neighbors, using the calibrated noise variance), and optionally 'own.weight'. The tau2 (variance of the motif's activity around the mean of neighboring cells, on the scale of the deviations) is added to the rowData.

See Also

estimateNoiseKappa

Examples

attach(getDummyData())
dev <- betterChromVAR(counts, motifMatches)
# The kNN should be based on an embedding that is independent of the
# deviations, for instance a PCA. For simplicity, for this example we use
# the PCA on raw counts:
emb <- prcomp(t(log1p(assay(counts))))$x[,1:3]
knn <- BiocNeighbors::findKNN(emb, k=3)
dev <- smoothDeviationsKNN(dev, knn)
dev

stepwisePeakLevelMotifTests

Description

Stepwise (forward) selection of the motifs associated with differential accessibility, using peakLevelMotifTests. In each round, the motifs are tested while adjusting for the motifs already selected; the strongest significant motif is then added to the selected ones, until no motif is significant anymore. This addresses the signal that spills over to motifs that share sites with the truly responsive ones.

Usage

stepwisePeakLevelMotifTests(
  se,
  dea,
  annotation,
  design = NULL,
  alpha = 0.05,
  maxSteps = 20L,
  minCount = 20,
  splineDF = 3,
  adjustWidth = FALSE,
  vif = TRUE,
  useAssay = "counts",
  lib.size = NULL,
  nthreads = NULL
)

Arguments

se

An object inheriting SummarizedExperiment containing the peak counts (in the counts assay, or useAssay), from which the differential analysis dea was obtained. It defines the peaks (rows), and provides the sample-level data used to estimate the correlation between peaks, as well as the bias column of rowData (see addGCBias), if present (which is very much recommended).

dea

The table of the results of a differential accessibility analysis of the peaks of se (or a named list of such tables, one for each contrast). Should accept major differential analysis packages (see Details for the format).

annotation

A (sparse) matrix or object inheriting SummarizedExperiment containing motif annotations for each row of se. Weighted annotations are binarized (any positive value is a match).

design

Optional design matrix (with a row for each column of se) of the model used for the differential analysis. It is used to estimate the correlation between the peaks (see vif) from the residuals of the model.

alpha

The threshold on the adjusted p-values (FDR across the motifs tested in the round) for a motif to be selected.

maxSteps

The maximum number of motifs to select (per contrast).

minCount

The minimum number of peaks with the motif (and without it) for a motif to be tested.

splineDF

The degrees of freedom of the splines used to adjust for accessibility and bias (set to 0 to disable).

adjustWidth

Logical; whether to additionally adjust for the (log-) width of the peaks (default FALSE), taken from rowRanges(se) (or from a width column of rowData(se)). This is useful when peaks have variable widths, since wider peaks are both more likely to contain a motif and have higher counts. Peaks of constant width are not affected. Alternatively, the peaks can be resized to a fixed width before counting.

vif

Controls the inflation of the variance to account for the correlation between the peaks of a set. Either TRUE (default; the correlation is estimated from the data of se, which requires design; if design is missing the inflation is disabled), FALSE (no inflation; not recommended for large motif sets), or a number between 0 and 1, which is the excess correlation assumed between the peaks of each motif (see Details).

useAssay

The assay of se containing the counts.

lib.size

Optional library sizes (default is the column sums of the counts), used to compute the log-counts-per-million from which the correlation between peaks is estimated.

nthreads

Either an integer scalar indicating the number of threads to use (the motifs are distributed across them), or a BiocParallelParam object. Results do not depend on it.

Details

In the first round, each motif is tested as in peakLevelMotifTests. If any motif has an adjusted p-value below alpha, the one with the smallest p-value is selected, and its presence in each peak is added to the covariates of the regressions used to test the other motifs in the next round. The procedure is repeated, adding each time the top motif, until no remaining motif is significant (or maxSteps is reached). Each contrast is processed independently.

The effects of the selected motifs are then estimated jointly (all in the same model). Because the motif of a round is selected as the top among many, and the rounds are not independent, the p-values at selection are not calibrated error rates, and the procedure is heuristic; a conservative alpha is advisable. A motif that is (nearly) collinear with those selected cannot be tested, and is returned with missing values. Motifs are compared on their presence in peaks only, so motifs in strong linkage with a responsive one can neither be distinguished from it nor from each other if they share all the same sites.

See peakLevelMotifTests for the other details of the model.

Value

A list with two data.frames: selected, with one row for each selected motif and contrast, in order of selection (step), with the statistics of the motif at the time of its selection (i.e. adjusted for the previously-selected motifs; see peakLevelMotifTests for the columns), as well as the estimates when all the selected motifs are fitted jointly (joint.difference, joint.se, joint.P.Value); and remaining, with the statistics of the other motifs in the last round (i.e. adjusted for all the selected motifs).

Author(s)

Pierre-Luc Germain

Examples

attach(getDummyData())
counts$group <- rep(LETTERS[1:2], each=5)
library(limma)
design <- model.matrix(~group, data=colData(counts))
y <- voom(assay(counts), design)
dea <- topTable(eBayes(lmFit(y, design)), coef=2, number=Inf, sort.by="none")
stepwisePeakLevelMotifTests(counts, dea, motifMatches, design=design, 
                            minCount=5)