From b3947e74791a99da5498a5cc7dd3836c8b9cb963 Mon Sep 17 00:00:00 2001 From: Muluh <127390183+0xMuluh@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:18:38 +0200 Subject: [PATCH] Add potential analysis to getBimodality --- DESCRIPTION | 2 +- NAMESPACE | 3 + NEWS | 3 + R/getBimodality.R | 138 ++++++++++++++++++++++++++-- man/getBimodality.Rd | 51 +++++++++- tests/testthat/test-getBimodality.R | 59 ++++++++++++ 6 files changed, 246 insertions(+), 10 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 35868ce..f444f21 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: miaTime Type: Package Title: Microbiome Time Series Analysis -Version: 1.3.5 +Version: 1.3.6 Authors@R: c(person(given = "Leo", family = "Lahti", role = c("aut"), email = "leo.lahti@iki.fi", diff --git a/NAMESPACE b/NAMESPACE index 9636e2b..761d2a9 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -59,9 +59,12 @@ importFrom(glmnet, ) importFrom(stats, coef, + density, + dnorm, lm, median, predict, + rnorm, setNames ) importFrom(survival, diff --git a/NEWS b/NEWS index 4f4a267..99e4207 100755 --- a/NEWS +++ b/NEWS @@ -1,3 +1,6 @@ +Changes in version 1.3.6 (2026-11-10) ++ getBimodality: method = "potential" gives the multimodality score of potential analysis + Changes in version 1.3.5 (2026-11-06) + getStepwiseDivergence: Option to select reference samples based on time lag diff --git a/R/getBimodality.R b/R/getBimodality.R index 8bec1a5..088e9f7 100644 --- a/R/getBimodality.R +++ b/R/getBimodality.R @@ -35,17 +35,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"}) #' @@ -54,6 +75,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 @@ -62,8 +96,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 @@ -79,6 +113,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()}} #' @@ -102,10 +142,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) } ) @@ -116,7 +158,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 @@ -129,7 +172,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 @@ -183,3 +229,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 eae66f5..fada703 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}. @@ -66,6 +88,15 @@ and kurtosis as follows The coefficient ranges from 0-1, where 1 means high bimodality. 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) @@ -73,8 +104,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 @@ -90,11 +121,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 2f9977d..d092dc1 100644 --- a/tests/testthat/test-getBimodality.R +++ b/tests/testthat/test-getBimodality.R @@ -79,3 +79,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)) +})