diff --git a/NAMESPACE b/NAMESPACE index c9a40db..55cba20 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -63,9 +63,12 @@ importFrom(glmnet, ) importFrom(stats, coef, + density, + dnorm, lm, median, predict, + rnorm, setNames ) importFrom(survival, diff --git a/NEWS b/NEWS index e89d810..ffa3b69 100755 --- a/NEWS +++ b/NEWS @@ -1,3 +1,6 @@ +Changes in version 1.5.x ++ getBimodality: method = "potential" gives the multimodality score of potential analysis + Changes in version 1.5.2 (2026-12-03) + Added getRankShift and addRankShift diff --git a/R/getBimodality.R b/R/getBimodality.R index 18e858f..c3f75b2 100644 --- a/R/getBimodality.R +++ b/R/getBimodality.R @@ -36,17 +36,38 @@ #' coefficient was introduced in the paper Shade A et al. 2014, where they used #' bimodality and abundance to determine conditionally rare taxa (CRT). #' +#' With \code{method = "potential"}, the score comes from potential analysis +#' (Livina et al. 2010), repeated on bootstrap resamples as in Lahti et al. +#' (2014). In each resample, the abundances of a feature are smoothed with a +#' Gaussian kernel density, and the maxima of the density that are high and +#' well separated by minima count as modes. The score is the share of +#' resamples with more than one mode, from 0 (unimodal) to 1. Missing values +#' are ignored. Small random noise separates tied values, so set a seed for +#' reproducible scores. +#' #' @references #' #' Shade A, et al. (2014) #' Conditionally Rare Taxa Disproportionately Contribute to Temporal Changes in #' Microbial Diversity. doi: 10.1128/mbio.01371-14 #' +#' Livina V, et al. (2010) +#' Potential analysis reveals changing number of climate states during the +#' last 60 kyr. Climate of the Past 6, 77-82. +#' +#' Lahti L, et al. (2014) +#' Tipping elements in the human intestinal ecosystem. +#' Nature Communications 5, 4344. +#' #' @return #' \code{DataFrame} or \code{x} with results added to its \code{rowData}. #' #' @inheritParams addBaselineDivergence #' +#' @param method \code{Character scalar}. The score: the coefficient of +#' bimodality (\code{"coefficient"}) or the multimodality score of potential +#' analysis (\code{"potential"}). (Default: \code{"coefficient"}) +#' #' @param name \code{Character scalar}. Specifies a column name for storing #' bimodality results. (Default: \code{"bimodality"}) #' @@ -55,6 +76,19 @@ #' \item \code{group}: \code{Character scalar}. Specifies a name of the column #' from \code{colData} that identifies the grouping of the samples. #' (Default: \code{NULL}) +#' \item \code{peak.threshold}: \code{Numeric scalar}. For +#' \code{method = "potential"}, how much higher than its neighbouring +#' minima a maximum must be to count as a mode, in units of the kernel +#' height. (Default: \code{1}) +#' \item \code{bw.adjust}: \code{Numeric scalar}. For +#' \code{method = "potential"}, multiplies the bandwidth of the density. +#' (Default: \code{1}) +#' \item \code{bs.iter}: \code{Integer scalar}. For +#' \code{method = "potential"}, the number of bootstrap resamples. +#' (Default: \code{100}) +#' \item \code{min.density}: \code{Numeric scalar}. For +#' \code{method = "potential"}, the lowest density of a mode, in units of +#' the kernel height. (Default: \code{1}) #' } #' #' @examples @@ -63,8 +97,8 @@ #' data(SilvermanAGutData) #' tse <- SilvermanAGutData #' -#' # In this example, we are only interested on vessel 1. -#' tse <- tse[, tse[["Vessel"]] == 1] +#' # In this example, we are only interested on vessel 1, in samples with reads. +#' tse <- tse[, tse[["Vessel"]] == 1 & colSums(assay(tse, "counts")) > 0] #' tse <- transformAssay(tse, method = "relabundance") #' #' # Calculate bimodality @@ -80,6 +114,12 @@ #' crt <- intersect(bimodal_taxa, abundant) #' head(crt) #' +#' # Multimodality from potential analysis, for the abundant taxa +#' set.seed(1) +#' p <- getBimodality(tse[abundant, ], assay.type = "relabundance", +#' method = "potential", bs.iter = 20) +#' head(p[order(-p[[1]]), , drop = FALSE]) +#' #' @seealso #' \code{\link[mia:getAbundant]{mia::getConditionallyLowAbundant()}} #' @@ -103,10 +143,12 @@ setMethod("addBimodality", signature = c(x = "SummarizedExperiment"), #' @rdname getBimodality #' @export setMethod("getBimodality", signature = c(x = "SummarizedExperiment"), - function(x, assay.type = "counts", ...){ + function(x, assay.type = "counts", + method = c("coefficient", "potential"), ...){ x <- .check_and_get_altExp(x, ...) .check_assay_present(assay.type, x) - res <- .calculate_bimodality(x, assay.type, ...) + method <- match.arg(method) + res <- .calculate_bimodality(x, assay.type, method, ...) return(res) } ) @@ -117,7 +159,8 @@ setMethod("getBimodality", signature = c(x = "SummarizedExperiment"), #' @importFrom dplyr group_by across all_of summarize #' @importFrom tidyr pivot_wider .calculate_bimodality <- function( - tse, assay.type, name = "bimodality", group = NULL, ...){ + tse, assay.type, method = "coefficient", name = "bimodality", + group = NULL, ...){ # This following line is to suppress "no visible binding for" messages # in cmdcheck .data <- b <- NULL @@ -130,7 +173,10 @@ setMethod("getBimodality", signature = c(x = "SummarizedExperiment"), res <- df |> group_by(across(all_of(c(group, "FeatureID")))) |> summarize( - b = .calculate_bimodality_coefficient(.data[[assay.type]], ...), + b = switch(method, + coefficient = .calculate_bimodality_coefficient( + .data[[assay.type]], ...), + potential = .calculate_multimodality(.data[[assay.type]], ...)), .groups = "drop" ) # If grouping was used, put data to wide format so that columns include @@ -185,3 +231,83 @@ setMethod("getBimodality", signature = c(x = "SummarizedExperiment"), kurtosis <- numerator / denominator return(kurtosis) } + +# Multimodality score of one feature: the share of bootstrap resamples with +# more than one mode in the potential analysis (as in microbiome). +#' @importFrom stats rnorm +.calculate_multimodality <- function( + x, peak.threshold = 1, bw.adjust = 1, bs.iter = 100, + min.density = 1, ...){ + x <- x[!is.na(x)] + if( length(unique(x)) <= 1L ){ + return(0) + } + # Small noise separates tied values + x <- x + rnorm(length(x), sd = sd(x) / 100) + n_modes <- vapply(seq_len(bs.iter), function(i){ + xb <- x[sample(length(x), replace = TRUE)] + length(.potential_maxima(xb, peak.threshold, bw.adjust, min.density)) + }, numeric(1)) + return(1 - mean(n_modes <= 1)) +} + +# Modes of the kernel density of x: maxima that are dense enough and well +# separated by minima. +#' @importFrom stats density dnorm +.potential_maxima <- function(x, peak.threshold, bw.adjust, min.density){ + de <- density(x, bw = "nrd", adjust = bw.adjust, kernel = "gaussian", + n = floor(0.2 * length(x)), from = min(x), to = max(x), cut = 3) + f <- de[["y"]] / sum(diff(de[["x"]][seq_len(2)]) * de[["y"]]) + height <- dnorm(0, sd = de[["bw"]]) / length(f) + maxima <- .find_maxima(f) + maxima <- maxima[f[maxima] >= min.density * height] + minima <- .between_minima(f, maxima, .find_maxima(-f)) + # Drop maxima that rise less than the threshold above a neighbouring + # minimum, together with the higher of their two minima + drop_max <- logical(length(maxima)) + drop_min <- logical(length(minima)) + for( j in seq_along(maxima) ){ + right <- minima[minima > maxima[j] & !drop_min] + left <- minima[minima < maxima[j] & !drop_min] + i1 <- if( length(right) ) min(right) else if( length(left) ) + max(left) + i2 <- if( length(left) ) max(left) else i1 + if( !is.null(i1) && + min(f[maxima[j]] - f[i1], f[maxima[j]] - f[i2]) < + peak.threshold * height ){ + drop_max[j] <- TRUE + drop_min[minima == if( f[i1] > f[i2] ) i1 else i2] <- TRUE + } + } + return(maxima[!drop_max]) +} + +# Indices of local maxima of f; a flat top gives its middle index. +.find_maxima <- function(f){ + d <- sign(diff(c(-Inf, f, -Inf))) + # Plateaus take the direction of the next change + for( i in rev(which(d == 0)) ){ + d[i] <- d[i + 1L] + } + ends <- which(diff(d) < 0) + starts <- vapply(ends, function(e){ + s <- e + while( s > 1L && f[s - 1L] == f[e] ){ + s <- s - 1L + } + s + }, numeric(1)) + return(round((starts + ends) / 2)) +} + +# The lowest minimum between each pair of consecutive maxima. +.between_minima <- function(f, maxima, minima){ + if( length(maxima) < 2L ){ + return(integer(0)) + } + res <- lapply(seq_along(maxima)[-1L], function(i){ + m <- minima[minima > maxima[i - 1L] & minima < maxima[i]] + if( length(m) ) round(mean(m[f[m] == min(f[m])])) + }) + return(unlist(res)) +} diff --git a/man/getBimodality.Rd b/man/getBimodality.Rd index f1dc159..3c892a6 100644 --- a/man/getBimodality.Rd +++ b/man/getBimodality.Rd @@ -13,7 +13,12 @@ addBimodality(x, ...) \S4method{addBimodality}{SummarizedExperiment}(x, name = "bimodality", ...) -\S4method{getBimodality}{SummarizedExperiment}(x, assay.type = "counts", ...) +\S4method{getBimodality}{SummarizedExperiment}( + x, + assay.type = "counts", + method = c("coefficient", "potential"), + ... +) } \arguments{ \item{x}{A @@ -25,6 +30,19 @@ object.} \item \code{group}: \code{Character scalar}. Specifies a name of the column from \code{colData} that identifies the grouping of the samples. (Default: \code{NULL}) +\item \code{peak.threshold}: \code{Numeric scalar}. For +\code{method = "potential"}, how much higher than its neighbouring +minima a maximum must be to count as a mode, in units of the kernel +height. (Default: \code{1}) +\item \code{bw.adjust}: \code{Numeric scalar}. For +\code{method = "potential"}, multiplies the bandwidth of the density. +(Default: \code{1}) +\item \code{bs.iter}: \code{Integer scalar}. For +\code{method = "potential"}, the number of bootstrap resamples. +(Default: \code{100}) +\item \code{min.density}: \code{Numeric scalar}. For +\code{method = "potential"}, the lowest density of a mode, in units of +the kernel height. (Default: \code{1}) }} \item{name}{\code{Character scalar}. Specifies a column name for storing @@ -32,6 +50,10 @@ bimodality results. (Default: \code{"bimodality"})} \item{assay.type}{\code{Character scalar}. Specifies which assay values are used in the dissimilarity estimation. (Default: \code{"counts"})} + +\item{method}{\code{Character scalar}. The score: the coefficient of +bimodality (\code{"coefficient"}) or the multimodality score of potential +analysis (\code{"potential"}). (Default: \code{"coefficient"})} } \value{ \code{DataFrame} or \code{x} with results added to its \code{rowData}. @@ -67,6 +89,15 @@ The coefficient ranges from 0-1, where 1 means high bimodality (two equally frequent values). A uniform distribution gives 5/9. The coefficient was introduced in the paper Shade A et al. 2014, where they used bimodality and abundance to determine conditionally rare taxa (CRT). + +With \code{method = "potential"}, the score comes from potential analysis +(Livina et al. 2010), repeated on bootstrap resamples as in Lahti et al. +(2014). In each resample, the abundances of a feature are smoothed with a +Gaussian kernel density, and the maxima of the density that are high and +well separated by minima count as modes. The score is the share of +resamples with more than one mode, from 0 (unimodal) to 1. Missing values +are ignored. Small random noise separates tied values, so set a seed for +reproducible scores. } \examples{ library(miaTime) @@ -74,8 +105,8 @@ library(miaTime) data(SilvermanAGutData) tse <- SilvermanAGutData -# In this example, we are only interested on vessel 1. -tse <- tse[, tse[["Vessel"]] == 1] +# In this example, we are only interested on vessel 1, in samples with reads. +tse <- tse[, tse[["Vessel"]] == 1 & colSums(assay(tse, "counts")) > 0] tse <- transformAssay(tse, method = "relabundance") # Calculate bimodality @@ -91,11 +122,25 @@ abundant <- getAbundant( crt <- intersect(bimodal_taxa, abundant) head(crt) +# Multimodality from potential analysis, for the abundant taxa +set.seed(1) +p <- getBimodality(tse[abundant, ], assay.type = "relabundance", + method = "potential", bs.iter = 20) +head(p[order(-p[[1]]), , drop = FALSE]) + } \references{ Shade A, et al. (2014) Conditionally Rare Taxa Disproportionately Contribute to Temporal Changes in Microbial Diversity. doi: 10.1128/mbio.01371-14 + +Livina V, et al. (2010) +Potential analysis reveals changing number of climate states during the +last 60 kyr. Climate of the Past 6, 77-82. + +Lahti L, et al. (2014) +Tipping elements in the human intestinal ecosystem. +Nature Communications 5, 4344. } \seealso{ \code{\link[mia:getAbundant]{mia::getConditionallyLowAbundant()}} diff --git a/tests/testthat/test-getBimodality.R b/tests/testthat/test-getBimodality.R index 1c2b72d..88ab284 100644 --- a/tests/testthat/test-getBimodality.R +++ b/tests/testthat/test-getBimodality.R @@ -83,3 +83,62 @@ test_that("addBimodality: errors", { addBimodality(tse, name = c("test", "test2")) |> expect_error() addBimodality(tse, name = TRUE) |> expect_error() }) + +test_that("potential analysis gives the multimodality score of microbiome", { + data(SilvermanAGutData) + tse <- SilvermanAGutData[, colSums(assay(SilvermanAGutData, "counts")) > 0] + tse <- transformAssay(tse, method = "relabundance") + a <- assay(tse, "relabundance") + # microbiome::multimodality(x, peak.threshold = 0, bs.iter = 30) with + # set.seed(7) gives these scores + expected <- c(seq_3 = 7 / 30, seq_5 = 9 / 30, seq_9 = 18 / 30) + for( feature in names(expected) ){ + set.seed(7) + score <- .calculate_multimodality(as.numeric(a[feature, ]), + peak.threshold = 0, bs.iter = 30) + expect_equal(score, expected[[feature]]) + } + # Modes where shallow maxima are dropped and neighbours merged; the + # positions are those of microbiome:::potential_univariate() + expect_equal(.potential_maxima(as.numeric(a["seq_16", ]), 1, 1, 1), + c(4, 30, 65, 99)) + expect_equal(.potential_maxima(as.numeric(a["seq_1", ]), 1, 1, 1), + c(12, 40)) +}) + +test_that("getBimodality(method = 'potential') separates one and two modes", { + set.seed(3) + x <- rbind( + one = rnorm(200), + two = c(rnorm(100, mean = 0), rnorm(100, mean = 6)), + flat = rep(1, 200)) + se <- SummarizedExperiment(assays = list(counts = x), + colData = DataFrame(g = rep(c("a", "b"), 100))) + res <- getBimodality(se, method = "potential", bs.iter = 50) + expect_s4_class(res, "DataFrame") + expect_identical(rownames(res), rownames(x)) + expect_lt(res["one", 1], 0.3) + expect_gt(res["two", 1], 0.9) + expect_equal(res["flat", 1], 0) + # Missing values are ignored + x_na <- x + x_na["two", 1:5] <- NA + se_na <- SummarizedExperiment(assays = list(counts = x_na)) + expect_false(anyNA(getBimodality(se_na, method = "potential", + bs.iter = 5)[[1]])) + # One column per group, and stored in rowData by addBimodality + res_g <- getBimodality(se, method = "potential", bs.iter = 10, group = "g") + expect_identical(colnames(res_g), c("bimodality_a", "bimodality_b")) + se <- addBimodality(se, method = "potential", bs.iter = 10, name = "pot") + expect_true("pot" %in% colnames(rowData(se))) + expect_error(getBimodality(se, method = "other")) +}) + +test_that("a higher peak.threshold keeps fewer modes", { + set.seed(5) + x <- c(rnorm(100), rnorm(100, mean = 3)) + n_modes <- vapply(c(0, 1, 10), function(t){ + length(.potential_maxima(x, t, 1, 1)) + }, numeric(1)) + expect_identical(n_modes, c(2, 1, 1)) +})