From 753cf8d39849b7817fb1b179defa5c895d4d689d 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 getAutocorrelation --- DESCRIPTION | 2 +- NAMESPACE | 6 + NEWS | 3 + R/AllGenerics.R | 10 ++ R/getAutocorrelation.R | 167 +++++++++++++++++++++++ _pkgdown.yml | 1 + man/getAutocorrelation.Rd | 101 ++++++++++++++ tests/testthat/test-getAutocorrelation.R | 67 +++++++++ 8 files changed, 356 insertions(+), 1 deletion(-) create mode 100644 R/getAutocorrelation.R create mode 100644 man/getAutocorrelation.Rd create mode 100644 tests/testthat/test-getAutocorrelation.R 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..3563b45 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,11 +1,13 @@ # Generated by roxygen2: do not edit by hand +export(addAutocorrelation) export(addBaselineDivergence) export(addBimodality) export(addShortTermChange) export(addStability) export(addStepwiseDivergence) export(addSurvival) +export(getAutocorrelation) export(getBaselineDivergence) export(getBimodality) export(getSamplingSummary) @@ -13,12 +15,14 @@ export(getShortTermChange) export(getStability) export(getStepwiseDivergence) export(getSurvival) +exportMethods(addAutocorrelation) exportMethods(addBaselineDivergence) exportMethods(addBimodality) exportMethods(addShortTermChange) exportMethods(addStability) exportMethods(addStepwiseDivergence) exportMethods(addSurvival) +exportMethods(getAutocorrelation) exportMethods(getBaselineDivergence) exportMethods(getBimodality) exportMethods(getSamplingSummary) @@ -58,9 +62,11 @@ importFrom(glmnet, glmnet ) importFrom(stats, + acf, coef, lm, median, + na.pass, predict, setNames ) diff --git a/NEWS b/NEWS index 4f4a267..a324fc1 100755 --- a/NEWS +++ b/NEWS @@ -1,3 +1,6 @@ +Changes in version 1.3.6 (2026-11-10) ++ Added getAutocorrelation and addAutocorrelation + Changes in version 1.3.5 (2026-11-06) + getStepwiseDivergence: Option to select reference samples based on time lag diff --git a/R/AllGenerics.R b/R/AllGenerics.R index cfb760a..3568ebd 100644 --- a/R/AllGenerics.R +++ b/R/AllGenerics.R @@ -65,3 +65,13 @@ setGeneric("addSurvival", signature = "x", function(x, ...) #' @export setGeneric("getSamplingSummary", signature = "x", function(x, ...) standardGeneric("getSamplingSummary")) + +#' @rdname getAutocorrelation +#' @export +setGeneric("getAutocorrelation", signature = "x", function(x, ...) + standardGeneric("getAutocorrelation")) + +#' @rdname getAutocorrelation +#' @export +setGeneric("addAutocorrelation", signature = "x", function(x, ...) + standardGeneric("addAutocorrelation")) diff --git a/R/getAutocorrelation.R b/R/getAutocorrelation.R new file mode 100644 index 0000000..047d420 --- /dev/null +++ b/R/getAutocorrelation.R @@ -0,0 +1,167 @@ +#' @name +#' getAutocorrelation +#' +#' @export +#' +#' @title +#' Autocorrelation of features over time +#' +#' @description +#' Calculates the autocorrelation of each feature within each subject at +#' lags of one or more time steps. +#' +#' @details +#' The samples of each subject must lie on a regular grid of time steps. The +#' step is the shortest time between two samples of a subject. Grid points +#' without a sample are treated as missing, and replicated samples at the +#' same time are averaged. The autocorrelation is computed with +#' \code{\link[stats:acf]{acf}}, passing missing values through. +#' +#' For irregularly sampled data, where samples do not lie on a common grid, +#' use \code{getVariogram()}, which estimates how +#' fast communities change at arbitrary time lags. +#' +#' @return +#' \code{getAutocorrelation} returns a \code{DataFrame} with one row per +#' feature, subject and lag, and the columns \code{FeatureID}, \code{group} +#' (when given), \code{lag} (in time steps), \code{time.lag} (in the units of +#' \code{time.col}), \code{acf} and \code{n.pairs} (the pairs of samples that +#' contribute to the estimate). \code{addAutocorrelation} returns \code{x} +#' with the table in its \code{metadata}. +#' +#' @inheritParams addBaselineDivergence +#' +#' @param max.lag \code{NULL} or \code{Integer scalar}. The largest lag, in +#' time steps. If \code{NULL}, the default of \code{acf}. +#' (Default: \code{NULL}) +#' +#' @param name \code{Character scalar}. Specifies a name for storing the +#' results. (Default: \code{"autocorrelation"}) +#' +#' @param ... additional arguments. +#' +#' @examples +#' library(miaTime) +#' +#' # Artificial gut with four vessels sampled every hour +#' data(SilvermanAGutData) +#' tse <- SilvermanAGutData +#' tse <- tse[, tse$SampleType == "Hourly" & +#' tse$Normal_Noise_Sample == "Normal"] +#' # Samples named by day and hour, with reads +#' tse <- tse[, grepl("^T\\.+[0-9]+d\\.[0-9]+h", colnames(tse)) & +#' colSums(assay(tse, "counts")) > 0] +#' # Hours since inoculation, from the sample names +#' days <- as.numeric(sub("^T\\.+([0-9]+)d.*", "\\1", colnames(tse))) +#' hours <- as.numeric(sub("^T\\.+[0-9]+d\\.([0-9]+)h.*", "\\1", colnames(tse))) +#' tse$hour <- days * 24 + hours +#' +#' tse <- transformAssay(tse, method = "relabundance") +#' df <- getAutocorrelation(tse, time.col = "hour", group = "Vessel", +#' assay.type = "relabundance", max.lag = 24) +#' +#' # Mean autocorrelation of the five most abundant taxa over the vessels +#' top <- getTop(tse, top = 5, assay.type = "relabundance") +#' df <- df[df[["FeatureID"]] %in% top, ] +#' aggregate(acf ~ FeatureID + time.lag, data = as.data.frame(df), +#' FUN = mean)[1:10, ] +#' +#' @seealso +#' \code{\link[stats:acf]{acf}} +NULL + +#' @rdname getAutocorrelation +#' @export +setMethod("addAutocorrelation", signature = c(x = "SummarizedExperiment"), + function(x, name = "autocorrelation", ...){ + temp <- .check_input(name, list("character scalar")) + x <- .check_and_get_altExp(x, ...) + args <- c(list(x = x), list(...)[!names(list(...)) %in% c("altexp")]) + res <- do.call(getAutocorrelation, args) + x <- .add_values_to_metadata(x, name, res, ...) + return(x) + } +) + +#' @rdname getAutocorrelation +#' @export +setMethod("getAutocorrelation", signature = c(x = "SummarizedExperiment"), + function(x, time.col, assay.type = "counts", group = NULL, + max.lag = NULL, ...){ + ############################## Input check ############################# + x <- .check_and_get_altExp(x, ...) + temp <- .check_input( + time.col, list("character scalar"), colnames(colData(x))) + if( !is.numeric(x[[time.col]]) || anyNA(x[[time.col]]) ){ + stop("'time.col' must specify a numeric column from colData(x) ", + "without missing values.", call. = FALSE) + } + .check_assay_present(assay.type, x) + temp <- .check_input( + group, list(NULL, "character scalar"), colnames(colData(x))) + temp <- .check_input(max.lag, list(NULL, "numeric scalar")) + ########################### Input check end ############################ + time <- x[[time.col]] + subject <- if( is.null(group) ) rep("all", ncol(x)) else + as.character(x[[group]]) + mat <- as.matrix(assay(x, assay.type)) + res <- .calculate_autocorrelation(mat, time, subject, max.lag) + if( is.null(group) ){ + res[["group"]] <- NULL + } else{ + names(res)[names(res) == "group"] <- group + } + return(DataFrame(res, check.names = FALSE)) + } +) + +################################ HELP FUNCTIONS ################################ + +# Autocorrelation of each feature (row of mat) within each subject. +#' @importFrom stats acf na.pass +.calculate_autocorrelation <- function(mat, time, subject, max.lag){ + # The step is the shortest time between two samples of a subject. + gaps <- unlist(tapply(time, subject, function(t) diff(sort(unique(t))))) + step <- min(gaps[gaps > 0]) + # Replicated samples at the same time are averaged. + key <- paste(subject, time, sep = "\r") + if( anyDuplicated(key) ){ + message("The dataset contains replicated samples. The average ", + "abundance is calculated for each time point.") + mat <- t(rowsum(t(mat), key, reorder = FALSE)) / + rep(as.vector(table(factor(key, levels = unique(key)))), + each = nrow(mat)) + first <- !duplicated(key) + time <- time[first] + subject <- subject[first] + } + res <- lapply(split(seq_along(time), subject), function(idx){ + k <- (time[idx] - min(time[idx])) / step + if( any(abs(k - round(k)) > 1e-8) ){ + stop("The samples of each subject must lie on a regular grid of ", + "time steps; use getVariogram() for irregular sampling.", + call. = FALSE) + } + k <- round(k) + series <- matrix(NA_real_, nrow(mat), max(k) + 1L) + series[, k + 1L] <- mat[, idx, drop = FALSE] + n <- ncol(series) + lags <- seq_len(min(max.lag %||% floor(10 * log10(n)), n - 1L)) + acfs <- vapply(seq_len(nrow(series)), function(i){ + acf(series[i, ], lag.max = max(lags), plot = FALSE, + na.action = na.pass)[["acf"]][lags + 1L] + }, numeric(length(lags))) + present <- !is.na(series[1L, ]) + n_pairs <- vapply(lags, function(l){ + sum(present[seq_len(n - l)] & present[(l + 1L):n]) + }, numeric(1)) + data.frame( + FeatureID = rep(rownames(mat), each = length(lags)), + group = subject[idx[1L]], + lag = rep(lags, nrow(mat)), + time.lag = rep(lags * step, nrow(mat)), + acf = as.vector(acfs), + n.pairs = rep(n_pairs, nrow(mat))) + }) + do.call(rbind, unname(res)) +} diff --git a/_pkgdown.yml b/_pkgdown.yml index 2649e2b..49dbf25 100755 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -11,6 +11,7 @@ reference: - getShortTermChange - getStability - getBimodality + - getAutocorrelation - title: Sampling contents: diff --git a/man/getAutocorrelation.Rd b/man/getAutocorrelation.Rd new file mode 100644 index 0000000..8a2bb28 --- /dev/null +++ b/man/getAutocorrelation.Rd @@ -0,0 +1,101 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/AllGenerics.R, R/getAutocorrelation.R +\name{getAutocorrelation} +\alias{getAutocorrelation} +\alias{addAutocorrelation} +\alias{addAutocorrelation,SummarizedExperiment-method} +\alias{getAutocorrelation,SummarizedExperiment-method} +\title{Autocorrelation of features over time} +\usage{ +getAutocorrelation(x, ...) + +addAutocorrelation(x, ...) + +\S4method{addAutocorrelation}{SummarizedExperiment}(x, name = "autocorrelation", ...) + +\S4method{getAutocorrelation}{SummarizedExperiment}( + x, + time.col, + assay.type = "counts", + group = NULL, + max.lag = NULL, + ... +) +} +\arguments{ +\item{x}{A +\code{\link[SummarizedExperiment:SummarizedExperiment-class]{SummarizedExperiment}} +object.} + +\item{...}{additional arguments.} + +\item{name}{\code{Character scalar}. Specifies a name for storing the +results. (Default: \code{"autocorrelation"})} + +\item{time.col}{\code{Character scalar}. Specifies a name of the column from +\code{colData} that identifies the sampling time points for the samples.} + +\item{assay.type}{\code{Character scalar}. Specifies which assay values are +used in the dissimilarity estimation. (Default: \code{"counts"})} + +\item{group}{\code{Character scalar}. Specifies a name of the column from +\code{colData} that identifies the grouping of the samples. +(Default: \code{NULL})} + +\item{max.lag}{\code{NULL} or \code{Integer scalar}. The largest lag, in +time steps. If \code{NULL}, the default of \code{acf}. +(Default: \code{NULL})} +} +\value{ +\code{getAutocorrelation} returns a \code{DataFrame} with one row per +feature, subject and lag, and the columns \code{FeatureID}, \code{group} +(when given), \code{lag} (in time steps), \code{time.lag} (in the units of +\code{time.col}), \code{acf} and \code{n.pairs} (the pairs of samples that +contribute to the estimate). \code{addAutocorrelation} returns \code{x} +with the table in its \code{metadata}. +} +\description{ +Calculates the autocorrelation of each feature within each subject at +lags of one or more time steps. +} +\details{ +The samples of each subject must lie on a regular grid of time steps. The +step is the shortest time between two samples of a subject. Grid points +without a sample are treated as missing, and replicated samples at the +same time are averaged. The autocorrelation is computed with +\code{\link[stats:acf]{acf}}, passing missing values through. + +For irregularly sampled data, where samples do not lie on a common grid, +use \code{getVariogram()}, which estimates how +fast communities change at arbitrary time lags. +} +\examples{ +library(miaTime) + +# Artificial gut with four vessels sampled every hour +data(SilvermanAGutData) +tse <- SilvermanAGutData +tse <- tse[, tse$SampleType == "Hourly" & + tse$Normal_Noise_Sample == "Normal"] +# Samples named by day and hour, with reads +tse <- tse[, grepl("^T\\\\.+[0-9]+d\\\\.[0-9]+h", colnames(tse)) & + colSums(assay(tse, "counts")) > 0] +# Hours since inoculation, from the sample names +days <- as.numeric(sub("^T\\\\.+([0-9]+)d.*", "\\\\1", colnames(tse))) +hours <- as.numeric(sub("^T\\\\.+[0-9]+d\\\\.([0-9]+)h.*", "\\\\1", colnames(tse))) +tse$hour <- days * 24 + hours + +tse <- transformAssay(tse, method = "relabundance") +df <- getAutocorrelation(tse, time.col = "hour", group = "Vessel", + assay.type = "relabundance", max.lag = 24) + +# Mean autocorrelation of the five most abundant taxa over the vessels +top <- getTop(tse, top = 5, assay.type = "relabundance") +df <- df[df[["FeatureID"]] \%in\% top, ] +aggregate(acf ~ FeatureID + time.lag, data = as.data.frame(df), + FUN = mean)[1:10, ] + +} +\seealso{ +\code{\link[stats:acf]{acf}} +} diff --git a/tests/testthat/test-getAutocorrelation.R b/tests/testthat/test-getAutocorrelation.R new file mode 100644 index 0000000..dfd47a3 --- /dev/null +++ b/tests/testthat/test-getAutocorrelation.R @@ -0,0 +1,67 @@ +# A series with known autocorrelation, for checks real data cannot give. +set.seed(1) +n <- 300 +ar <- as.numeric(arima.sim(list(ar = 0.7), n)) +se <- SummarizedExperiment( + assays = list(counts = rbind(ar = ar)), + colData = DataFrame(t = seq_len(n) * 2)) + +# Artificial gut vessels sampled every hour; hours from the sample names. +data(SilvermanAGutData) +tse <- SilvermanAGutData +tse <- tse[, tse$SampleType == "Hourly" & + tse$Normal_Noise_Sample == "Normal"] +tse <- tse[, grepl("^T\\.+[0-9]+d\\.[0-9]+h", colnames(tse)) & + colSums(assay(tse, "counts")) > 0] +days <- as.numeric(sub("^T\\.+([0-9]+)d.*", "\\1", colnames(tse))) +hours <- as.numeric(sub("^T\\.+[0-9]+d\\.([0-9]+)h.*", "\\1", colnames(tse))) +tse$hour <- days * 24 + hours +tse <- tse[1:20, ] + +test_that("getAutocorrelation checks its input", { + expect_error(getAutocorrelation(se, time.col = "missing")) + expect_error(getAutocorrelation(tse, time.col = "SampleType"), "numeric") + expect_error(getAutocorrelation(se, time.col = "t", max.lag = "a")) + irregular <- se[, 1:3] + irregular$t <- c(0, 1, 2.5) + expect_error(getAutocorrelation(irregular, time.col = "t"), + "regular grid") +}) + +test_that("getAutocorrelation equals stats::acf without gaps", { + res <- getAutocorrelation(se, time.col = "t", max.lag = 3) + expect_equal(res[["acf"]], + as.vector(acf(ar, lag.max = 3, plot = FALSE)[["acf"]][2:4])) + expect_equal(res[["lag"]], 1:3) + expect_equal(res[["time.lag"]], c(2, 4, 6)) + expect_equal(res[["n.pairs"]], n - 1:3) + expect_false("group" %in% names(res)) +}) + +test_that("getAutocorrelation treats missing time points as missing", { + keep <- seq_len(n) %% 5 != 0 + res <- getAutocorrelation(se[, keep], time.col = "t", max.lag = 2) + # Pairs exist only where both samples are present. + expect_equal(res[["n.pairs"]], c( + sum(keep[-n] & keep[-1]), sum(keep[seq_len(n - 2)] & keep[-(1:2)]))) + expect_equal(res[["acf"]][1L], 0.7, tolerance = 0.1) +}) + +test_that("getAutocorrelation works per subject and averages replicates", { + expect_message( + res <- getAutocorrelation(tse, time.col = "hour", group = "Vessel", + max.lag = 5), + "replicated samples") + expect_true("Vessel" %in% names(res)) + expect_setequal(unique(res[["Vessel"]]), as.character(unique(tse$Vessel))) + expect_identical(nrow(res), nrow(tse) * 4L * 5L) + expect_true(all(res[["acf"]] >= -1 & res[["acf"]] <= 1, na.rm = TRUE)) +}) + +test_that("addAutocorrelation stores the table in metadata", { + x <- suppressMessages(addAutocorrelation(tse, time.col = "hour", + group = "Vessel", max.lag = 3, name = "acf_vessel")) + expect_equal(metadata(x)[["acf_vessel"]], + suppressMessages(getAutocorrelation(tse, time.col = "hour", + group = "Vessel", max.lag = 3))) +})