Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Short term change #94

Merged
merged 18 commits into from
Jan 27, 2025
10 changes: 6 additions & 4 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,20 @@ biocViews: Microbiome, Software, Sequencing
License: Artistic-2.0 | file LICENSE
Depends:
R (>= 4.4.0),
mia
ggplot2,
mia,
SummarizedExperiment
Imports:
dplyr,
methods,
S4Vectors,
SingleCellExperiment,
SummarizedExperiment,
TreeSummarizedExperiment
TreeSummarizedExperiment,
ggrepel,
reshape2
Suggests:
BiocStyle,
devtools,
ggplot2,
knitr,
lubridate,
miaViz,
Expand Down
13 changes: 13 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
# Generated by roxygen2: do not edit by hand

export(addBaselineDivergence)
export(addShortTermChange)
export(addStepwiseDivergence)
export(getBaselineDivergence)
export(getShortTermChange)
export(getStepwiseDivergence)
exportMethods(addBaselineDivergence)
exportMethods(addShortTermChange)
exportMethods(addStepwiseDivergence)
exportMethods(getBaselineDivergence)
exportMethods(getShortTermChange)
exportMethods(getStepwiseDivergence)
import(TreeSummarizedExperiment)
import(mia)
importFrom(SummarizedExperiment,colData)
importFrom(dplyr,"%>%")
importFrom(dplyr,arrange)
importFrom(dplyr,as_tibble)
importFrom(dplyr,group_by)
importFrom(dplyr,lag)
importFrom(dplyr,mutate)
importFrom(dplyr,summarize)
importFrom(dplyr,ungroup)
importFrom(ggplot2,aes)
importFrom(ggplot2,ggplot)
importFrom(ggrepel,geom_text_repel)
importFrom(mia,rarefyAssay)
importFrom(mia,transformAssay)
12 changes: 12 additions & 0 deletions R/AllGenerics.R
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,15 @@ setGeneric("getStepwiseDivergence", signature = c("x"), function(x, ...)
#' @export
setGeneric("addStepwiseDivergence", signature = "x", function(x, ...)
standardGeneric("addStepwiseDivergence"))

#' @rdname addShortTermChange
#' @export
setGeneric("addShortTermChange", signature = "x", function(x, ...)
standardGeneric("addShortTermChange"))

#' @rdname addShortTermChange
#' @export
setGeneric("getShortTermChange", signature = "x", function(x, ...)
standardGeneric("getShortTermChange"))


128 changes: 128 additions & 0 deletions R/getShortTermChange.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
#' @title Short term Changes in Abundance
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
#'
#' @description Calculates short term changes in abundance of taxa
#' using temporal Abundance data.
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
#'
#' @param x a \code{\link{SummarizedExperiment}} object.
#' @param assay.type \code{Character scalar}. Specifies the name of assay
#' used in calculation. (Default: \code{"counts"})
#' @param name \code{Character scalar}. Specifies a name for storing
#' short term results. (Default: \code{"short_term_change"})
#' @param ... additional arguments.
#'
#'
#' @return \code{getShortTermChange} returns \code{DataFrame} object containing
#' the short term change in abundance over time for a microbe.
#' \code{addShortTermChange}, on the other hand, returns a
#' \code{\link[SummarizedExperiment:SummarizedExperiment-class]{SummarizedExperiment}}
#' object with these results in its \code{metadata}.
#'
#' @details This approach is used by Wisnoski NI and colleagues
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
#' \url{https://github.com/nwisnoski/ul-seedbank}. Their approach is based on
#' the following calculation log(present abundance/past abundance).
#' Also a compositional version using relative abundance similar to
#' Brian WJi, Sheth R et al
#' \url{https://www.nature.com/articles/s41564-020-0685-1} can be used.
#' This approach is useful for identifying short term growth behaviors of taxa.
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
#'
#' @name addShortTermChange
#'
#'
#' @examples
#'
#' # Load time series data
#' data(minimalgut)
#' tse <- minimalgut
#'
#' short_time_labels <- c("74.5h", "173h", "438h", "434h", "390h")
#'
#' # Subset samples by Time_label and StudyIdentifier
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
#' tse <- tse[, !(tse$Time_label %in% short_time_labels)]
#' tse <- tse[, (tse$StudyIdentifier == "Bioreactor A")]
#'
#' # Get short term change
#' # Case of rarefying counts
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
#' tse <- transformAssay(tse, method = "relabundance")
#' getShortTermChange(tse, assay.type = "relabundance", time.col = "Time.hr")
#'
#' # Case of transforming counts
#' tse <- rarefyAssay(tse, assay.type = "counts")
#' getShortTermChange(tse, assay.type = "subsampled", time.col = "Time.hr")
NULL

#' @rdname addShortTermChange
#' @export
#' @importFrom dplyr arrange as_tibble summarize "%>%"
#' @importFrom ggplot2 ggplot aes
#' @importFrom ggrepel geom_text_repel
#' @importFrom mia rarefyAssay transformAssay
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
#' @importFrom SummarizedExperiment colData
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
setMethod("getShortTermChange", signature = c(x = "SummarizedExperiment"),
function(x, assay.type = "counts", ...){
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
############################## Input check #############################
# Check validity of object
if (nrow(x) == 0L){
stop("No data available in `x` ('x' has nrow(x) == 0L.)",
call. = FALSE)
}
# Check assay.type
.check_assay_present(assay.type, x)
########################### Growth Metrics ############################
grwt <- .calculate_growth_metrics(x, assay.type = assay.type, ...)
# Clean and format growth metrics
grs.all <- .clean_growth_metrics(grwt, ...)
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
return(grs.all)
}
)

#' @rdname addShortTermChange
#' @export
setMethod("addShortTermChange", signature = c(x = "SummarizedExperiment"),
function(x, assay.type = "counts", name = "short_term_change", ...){
# Calculate short term change
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
res <- getShortTermChange(x, ...)
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
# Add to metadata
x <- .add_values_to_metadata(x, name, res, ...)
return(x)
}
)

################################ HELP FUNCTIONS ################################

# wrapper to calculate growth matrix
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
.calculate_growth_metrics <- function(x, assay.type, time.col = NULL, ...) {
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved

TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
# Reshape data and calculate growth metrics
assay_data <- meltSE(x, assay.type = assay.type,
add.col = time.col, row.name = "Feature_ID")
assay_data <- assay_data %>%
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
arrange( !!sym(time.col) ) %>%
group_by(Feature_ID) %>%
mutate(
time_lag = !!sym(time.col) - lag( !!sym(time.col) ),
growth_diff =!!sym(assay.type) - lag(!!sym(assay.type)),
growth_rate = (!!sym(assay.type) - lag(!!sym(assay.type))) / lag(!!sym(assay.type)),
var_abund = (!!sym(assay.type) - lag(!!sym(assay.type))) / time_lag
)
return(assay_data)
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
}

.clean_growth_metrics <- function(grwt, time.col = NULL, ...) {
# Calculate max growth
maxgrs <- grwt %>%
summarize(max_growth = max(growth_diff, na.rm = TRUE))
# Merge growth data with max growth
grs.all <- merge(grwt, maxgrs, by = "Feature_ID")
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
# Add 'ismax' column indicating if the growth is the maximum
grs.all <- grs.all %>%
mutate(ismax = ifelse(growth_diff == max_growth, TRUE, FALSE))
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
# Clean and abbreviate FeatureID names
grs.all$Feature_IDabb <- toupper(abbreviate(grs.all$Feature_ID,
minlength = 3,
method = "both.sides"))
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
# Create 'Feature.time' column combining abbreviation and time information
grs.all$Feature_time <- paste0(grs.all$Feature_IDabb, " ",
grs.all[[time.col]], "h")
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved

return(grs.all)
}
1 change: 1 addition & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,4 @@
.check_assay_present <- mia:::.check_assay_present
.add_values_to_colData <- mia:::.add_values_to_colData
.check_and_get_altExp <- mia:::.check_and_get_altExp
.add_values_to_metadata <- mia:::.add_values_to_metadata
69 changes: 69 additions & 0 deletions man/addShortTermChange.Rd

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

4 changes: 2 additions & 2 deletions man/miaTime-package.Rd

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

25 changes: 25 additions & 0 deletions tests/testthat/test-getShortTermChange.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
test_that("getShortTermChange", {
library(SummarizedExperiment)
# Load dataset
data(minimalgut)
tse <- minimalgut
# Check if the function handles empty input
empty_se <- SummarizedExperiment()
expect_error(getShortTermChange(empty_se),
"No data available in `x`")

# Should still return a dataframe
short_time_labels <- c("74.5h", "173h", "438h", "434h", "390h")
# Subset samples by Time_label and StudyIdentifier
tse_filtered <- tse[, !(tse$Time_label %in% short_time_labels)]
tse_filtered <- tse_filtered[, (tse_filtered$StudyIdentifier == "Bioreactor A")]

expect_true(all(!(tse_filtered$Time_label %in% short_time_labels)))

result <- getShortTermChange(tse_filtered, time.col = "Time.hr")
# Expected output is a dataframe
expect_true(is.data.frame(result))
expect_true("growth_diff" %in% colnames(result))
# Test some expected properties (e.g., that growth_diff isn't all NAs)
expect_false(all(is.na(result$growth_diff)))
TuomasBorman marked this conversation as resolved.
Show resolved Hide resolved
})
Loading