Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,12 @@ importFrom(glmnet,
)
importFrom(stats,
coef,
density,
dnorm,
lm,
median,
predict,
rnorm,
setNames
)
importFrom(survival,
Expand Down
3 changes: 3 additions & 0 deletions NEWS
Original file line number Diff line number Diff line change
@@ -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

Expand Down
138 changes: 132 additions & 6 deletions R/getBimodality.R
Original file line number Diff line number Diff line change
Expand Up @@ -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"})
#'
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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()}}
#'
Expand All @@ -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)
}
)
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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))
}
51 changes: 48 additions & 3 deletions man/getBimodality.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

59 changes: 59 additions & 0 deletions tests/testthat/test-getBimodality.R
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})
Loading