From b75e7a04c561d21d0ec1aa6ec5b34be351fc08c8 Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Wed, 21 Oct 2026 10:15:01 +0300 Subject: [PATCH 1/8] Add getTemporalVariogram Estimates D(L), the expected within-subject dissimilarity at a stated time lag, from all within-subject sample pairs with a local quadratic fit in log lag and subject-clustered intervals. Lags the sampling design does not support are reported as NA. split.by compares groups by the ratio of D(L); at.time estimates D(L) at a common time for developing communities. --- NAMESPACE | 4 + R/AllGenerics.R | 10 + R/getTemporalVariogram.R | 493 +++++++++++++++++++++ man/getTemporalVariogram.Rd | 219 +++++++++ tests/testthat/test-getTemporalVariogram.R | 132 ++++++ 5 files changed, 858 insertions(+) create mode 100644 R/getTemporalVariogram.R create mode 100644 man/getTemporalVariogram.Rd create mode 100644 tests/testthat/test-getTemporalVariogram.R diff --git a/NAMESPACE b/NAMESPACE index 6059c6a..6bdf32d 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -5,21 +5,25 @@ export(addBimodality) export(addShortTermChange) export(addStability) export(addStepwiseDivergence) +export(addTemporalVariogram) export(getBaselineDivergence) export(getBimodality) export(getShortTermChange) export(getStability) export(getStepwiseDivergence) +export(getTemporalVariogram) exportMethods(addBaselineDivergence) exportMethods(addBimodality) exportMethods(addShortTermChange) exportMethods(addStability) exportMethods(addStepwiseDivergence) +exportMethods(addTemporalVariogram) exportMethods(getBaselineDivergence) exportMethods(getBimodality) exportMethods(getShortTermChange) exportMethods(getStability) exportMethods(getStepwiseDivergence) +exportMethods(getTemporalVariogram) import(S4Vectors) import(SingleCellExperiment) import(SummarizedExperiment) diff --git a/R/AllGenerics.R b/R/AllGenerics.R index 40a420e..63249df 100644 --- a/R/AllGenerics.R +++ b/R/AllGenerics.R @@ -50,3 +50,13 @@ setGeneric("getStability", signature = "x", function(x, ...) #' @export setGeneric("addStability", signature = "x", function(x, ...) standardGeneric("addStability")) + +#' @rdname getTemporalVariogram +#' @export +setGeneric("getTemporalVariogram", signature = "x", function(x, ...) + standardGeneric("getTemporalVariogram")) + +#' @rdname getTemporalVariogram +#' @export +setGeneric("addTemporalVariogram", signature = "x", function(x, ...) + standardGeneric("addTemporalVariogram")) diff --git a/R/getTemporalVariogram.R b/R/getTemporalVariogram.R new file mode 100644 index 0000000..c459c2f --- /dev/null +++ b/R/getTemporalVariogram.R @@ -0,0 +1,493 @@ +#' @name +#' getTemporalVariogram +#' +#' @export +#' +#' @title +#' Community change at stated time lags (temporal variogram) +#' +#' @description +#' Estimates \eqn{D(L)}, the expected dissimilarity between two samples of the +#' same subject taken \eqn{L} time units apart, from all within-subject sample +#' pairs. Unlike divergence to the previous sample, \eqn{D(L)} refers to a +#' stated lag, so it can be compared between subjects, groups and studies +#' whose sampling schedules differ. +#' +#' @details +#' Every pair of samples from the same subject measures how much the +#' community changed over that pair's time lag \eqn{h}. The temporal +#' variogram \eqn{g(h)} is the expected dissimilarity as a function of the +#' lag, and \eqn{D(L) = g(L)}. Divergence to the previous sample measures +#' change at whatever intervals the schedule happens to have, so it differs +#' between designs even when the dynamics are the same. +#' +#' \eqn{D(L)} is estimated locally. Pairs with lags in +#' \eqn{[L / window, L \times window]} are used, and the dissimilarities are +#' regressed on \eqn{u = \log(h / L)} and \eqn{u^2} by weighted least +#' squares; the intercept estimates \eqn{D(L)}. The pairs of each subject are +#' weighted so that every subject counts equally. Pairs of the same subject +#' share samples and are correlated, so the standard error is cluster-robust +#' by subject (CR1), and the interval for \eqn{\log D(L)} uses a t +#' distribution with \eqn{G - 1} degrees of freedom, where \eqn{G} is the +#' number of subjects with pairs in the window. +#' +#' \eqn{D(L)} is reported only at lags the design supports: at least +#' \eqn{\max(5, 20\%)} of the subjects with two or more samples must have +#' pairs in the window, and at least three subjects must have pairs at lags +#' up to \eqn{L} and three at lags from \eqn{L}, so that \eqn{D(L)} is +#' interpolated, not extrapolated. Elsewhere the estimate is \code{NA} and +#' \code{supported} is \code{FALSE}. +#' +#' When \code{lags = NULL}, ten lags are spread evenly on the log scale +#' between the shortest and longest supported lag of the whole data: the +#' smallest and largest lag reached by at least \eqn{\max(5, 20\%)} of the +#' subjects. +#' +#' \strong{Groups.} With \code{split.by}, \eqn{D(L)} is estimated separately +#' for each level of a subject-level variable, and each level is compared +#' with the first level by the ratio of \eqn{D(L)}, with a +#' Welch–Satterthwaite t test of the log ratio. The comparison is made only +#' at lags supported in both groups. P-values are not adjusted for multiple +#' comparisons. +#' +#' \strong{Developing communities.} When change at a given lag depends on +#' the time since a common origin (age in infant cohorts, time since an +#' intervention), groups whose samples were taken at different ages differ +#' in \eqn{D(L)} even with the same development. \code{at.time} estimates +#' \eqn{D(L)} at a stated time \eqn{a}: only pairs whose midpoint \eqn{m} +#' satisfies \eqn{(1 + m) / (1 + a)} in \eqn{[1/2, 2]} are used, the +#' regression adds \eqn{z = \log(1 + m) - \log(1 + a)} and \eqn{z^2}, and +#' at least three subjects must have midpoints up to \eqn{a} and three from +#' \eqn{a}. With \code{at.time = "median"}, \eqn{a} is the median midpoint of +#' all pairs in the lag window, pooled over the levels of \code{split.by}, so +#' that every group is evaluated at the same time. Time must then be +#' measured from the common origin and be non-negative. +#' +#' \strong{Dissimilarity.} Any dissimilarity of +#' \code{\link[mia:getDissimilarity]{getDissimilarity()}} can be used. The +#' squared Euclidean distance between Hellinger-transformed abundances +#' (\code{method = "euclidean"}, \code{squared = TRUE} on a +#' \code{"hellinger"} assay) adds technical noise to the dissimilarity +#' additively, so the noise does not change the shape of the variogram, only +#' its level. Dissimilarities depend on sequencing depth; rarefy the counts +#' first (\code{\link[mia:rarefyAssay]{rarefyAssay()}}) when depth differs +#' between samples or groups. +#' +#' @references +#' Diggle P.J. (1988) An approach to the analysis of repeated measurements. +#' Biometrics 44, 959–971. doi: 10.2307/2531727 +#' +#' @return +#' \code{getTemporalVariogram} returns a \code{DataFrame} with one row per +#' lag (and level of \code{split.by}, and comparison) and the columns +#' \describe{ +#' \item{lag}{The lag \eqn{L}.} +#' \item{\code{split.by}}{When \code{split.by} is given: the level, or the +#' comparison (\code{"B / A"}).} +#' \item{type}{\code{"dissimilarity"} for estimates of \eqn{D(L)}, +#' \code{"ratio"} for comparisons between levels.} +#' \item{estimate, lower, upper}{\eqn{D(L)} or the ratio of \eqn{D(L)}, +#' with the confidence interval.} +#' \item{se}{Standard error on the log scale.} +#' \item{df}{Degrees of freedom of the t distribution.} +#' \item{p.value}{For comparisons, the p-value of the test that the ratio +#' is 1.} +#' \item{n.subjects, n.pairs}{Subjects and pairs in the lag window.} +#' \item{supported}{Whether the design supports \eqn{D(L)} at this lag.} +#' \item{at.time}{The time at which \eqn{D(L)} was estimated, when +#' \code{at.time} is given.} +#' } +#' \code{addTemporalVariogram} returns \code{x} with this table in its +#' \code{metadata}. +#' +#' @inheritParams addBaselineDivergence +#' +#' @param group \code{Character scalar}. Specifies a name of the column from +#' \code{colData} that identifies the subject (or other unit followed over +#' time) of each sample. Pairs are formed within subjects. +#' +#' @param lags \code{NULL} or \code{numeric vector}. The lags \eqn{L}, in +#' the units of \code{time.col}, at which \eqn{D(L)} is estimated. If +#' \code{NULL}, ten lags between the shortest and longest supported lag. +#' (Default: \code{NULL}) +#' +#' @param split.by \code{NULL} or \code{Character scalar}. Specifies a name +#' of a column from \code{colData} with one value per subject. \eqn{D(L)} is +#' estimated for each of its levels, and each level is compared with the +#' first. (Default: \code{NULL}) +#' +#' @param at.time \code{NULL}, \code{numeric vector} or \code{"median"}. The +#' time at which \eqn{D(L)} is estimated, for communities whose change +#' depends on time since a common origin; one value, or one per lag. See +#' details. (Default: \code{NULL}) +#' +#' @param window \code{Numeric scalar}. Pairs with lags within a factor of +#' \code{window} of \eqn{L} are used. (Default: \code{2}) +#' +#' @param squared \code{Logical scalar}. Whether the dissimilarities are +#' squared. (Default: \code{FALSE}) +#' +#' @param conf.level \code{Numeric scalar}. Confidence level of the +#' intervals. (Default: \code{0.95}) +#' +#' @param name \code{Character scalar}. Specifies a name for storing the +#' results in \code{metadata}. (Default: \code{"temporal_variogram"}) +#' +#' @param ... additional arguments passed to +#' \code{\link[mia:getDissimilarity]{getDissimilarity()}}. +#' +#' @examples +#' library(miaTime) +#' +#' data(hitchip1006) +#' tse <- transformAssay(hitchip1006, method = "hellinger") +#' +#' # Change over 1 to 9 time units, as squared Hellinger distance +#' res <- getTemporalVariogram( +#' tse, +#' time.col = "time", +#' group = "subject", +#' assay.type = "hellinger", +#' method = "euclidean", +#' squared = TRUE, +#' lags = c(1, 3, 6, 9) +#' ) +#' res +#' +#' # Compare the sexes +#' res <- getTemporalVariogram( +#' tse, +#' time.col = "time", +#' group = "subject", +#' assay.type = "hellinger", +#' method = "euclidean", +#' squared = TRUE, +#' lags = c(1, 3), +#' split.by = "sex" +#' ) +#' res[res$type == "ratio", ] +#' +#' # Store the results in metadata +#' tse <- addTemporalVariogram( +#' tse, +#' time.col = "time", +#' group = "subject", +#' assay.type = "hellinger", +#' method = "euclidean", +#' squared = TRUE +#' ) +#' metadata(tse)[["temporal_variogram"]] +#' +#' @seealso +#' \code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}} +#' +NULL + +#' @rdname getTemporalVariogram +#' @export +setMethod("addTemporalVariogram", signature = c(x = "SummarizedExperiment"), + function(x, name = "temporal_variogram", ...){ + 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(getTemporalVariogram, args) + x <- .add_values_to_metadata(x, name, res, ...) + return(x) + } +) + +#' @rdname getTemporalVariogram +#' @export +setMethod("getTemporalVariogram", signature = c(x = "SummarizedExperiment"), + function( + x, + time.col, + group, + assay.type = "counts", + method = "bray", + lags = NULL, + split.by = NULL, + at.time = NULL, + window = 2, + squared = FALSE, + conf.level = 0.95, + ...){ + ############################# 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]]) ){ + stop("'time.col' must specify numeric column from colData(x)", + call. = FALSE) + } + temp <- .check_input( + group, list("character scalar"), colnames(colData(x))) + .check_assay_present(assay.type, x) + temp <- .check_input(method, list("character scalar")) + temp <- .check_input(lags, list(NULL, "numeric vector")) + if( !is.null(lags) && (anyNA(lags) || any(lags <= 0)) ){ + stop("'lags' must be positive.", call. = FALSE) + } + temp <- .check_input( + split.by, list(NULL, "character scalar"), colnames(colData(x))) + if( !(is.null(at.time) || identical(at.time, "median") || + (is.numeric(at.time) && !anyNA(at.time))) ){ + stop("'at.time' must be NULL, numeric or \"median\".", + call. = FALSE) + } + if( is.numeric(at.time) && !length(at.time) %in% c(1L, length(lags)) ){ + stop("'at.time' must have length 1 or the length of 'lags'.", + call. = FALSE) + } + temp <- .check_input(window, list("numeric scalar")) + if( window <= 1 ){ + stop("'window' must be greater than 1.", call. = FALSE) + } + temp <- .check_input(squared, list("logical scalar")) + temp <- .check_input(conf.level, list("numeric scalar")) + if( conf.level <= 0 || conf.level >= 1 ){ + stop("'conf.level' must be between 0 and 1.", call. = FALSE) + } + ########################### INPUT CHECK END ############################ + args <- list(...)[!names(list(...)) %in% c("altexp")] + pairs <- .get_within_subject_pairs( + x, time.col, group, assay.type, method, split.by, squared, args) + if( is.null(lags) ){ + lags <- .default_lags(pairs) + } + res <- .temporal_variogram( + pairs, lags, split.by, at.time, window, conf.level) + res <- DataFrame(res, check.names = FALSE) + return(res) + } +) + +################################ HELP FUNCTIONS ################################ + +# All pairs of samples of the same subject, with their lag, midpoint time and +# dissimilarity. +.get_within_subject_pairs <- function( + x, time.col, group, assay.type, method, split.by, squared, args){ + time <- x[[time.col]] + subject <- x[[group]] + keep <- !is.na(time) & !is.na(subject) + if( !is.null(split.by) ){ + keep <- keep & !is.na(x[[split.by]]) + } + if( any(!keep) ){ + message(sum(!keep), " samples with missing values in '", time.col, + "', '", group, "'", + if( !is.null(split.by) ) paste0(" or '", split.by, "'"), + " were removed.") + x <- x[, keep] + time <- time[keep] + subject <- subject[keep] + } + subject <- as.character(subject) + level <- NULL + if( !is.null(split.by) ){ + level <- as.character(x[[split.by]]) + n_levels <- tapply(level, subject, function(v) length(unique(v))) + if( any(n_levels > 1L) ){ + stop("'split.by' must have one value per subject ('", group, + "').", call. = FALSE) + } + if( length(unique(level)) < 2L ){ + stop("'split.by' must have at least two levels.", call. = FALSE) + } + # The first level is the reference of the comparisons + level <- factor(level, levels = levels(factor(x[[split.by]]))) + } + mat <- t(assay(x, assay.type)) + idx_list <- split(seq_along(subject), subject) + idx_list <- idx_list[lengths(idx_list) >= 2L] + if( length(idx_list) == 0L ){ + stop("No subject has two or more samples.", call. = FALSE) + } + res <- lapply(idx_list, function(idx){ + d <- do.call(getDissimilarity, c( + list(x = mat[idx, , drop = FALSE], method = method), args)) + d <- as.matrix(d) + ut <- which(upper.tri(d), arr.ind = TRUE) + k <- idx[ut[, 1L]] + l <- idx[ut[, 2L]] + data.frame( + subject = subject[k], h = abs(time[l] - time[k]), + mid = (time[k] + time[l]) / 2, d = d[ut]) + }) + pairs <- do.call(rbind, unname(res)) + if( squared ){ + pairs$d <- pairs$d^2 + } + if( !is.null(split.by) ){ + pairs$level <- level[match(pairs$subject, subject)] + } + return(pairs) +} + +# The k-th smallest of the subjects' shortest lags and the k-th largest of +# their longest lags, k = max(5, 20% of subjects). +.default_lags <- function(pairs){ + p <- pairs[pairs$h > 0, ] + lo <- sort(tapply(p$h, p$subject, min)) + hi <- sort(tapply(p$h, p$subject, max), decreasing = TRUE) + k <- max(5L, ceiling(0.2 * length(lo))) + if( length(lo) < k ){ + stop("Too few subjects to estimate the variogram: pairs from at ", + "least five subjects are needed.", call. = FALSE) + } + lo <- unname(lo[k]) + hi <- unname(hi[k]) + if( hi <= lo ){ + return(lo) + } + lags <- exp(seq(log(lo), log(hi), length.out = 10L)) + lags <- unique(signif(lags, 3L)) + return(lags) +} + +# D(L) for all lags, levels of split.by, and comparisons with the first level +.temporal_variogram <- function( + pairs, lags, split.by, at.time, window, conf.level){ + a0 <- .get_at_time(pairs, lags, at.time, window) + if( is.null(split.by) ){ + res <- .local_variogram(pairs, lags, window, conf.level, a0) + res <- .format_variogram(res, at.time, conf.level) + return(res) + } + lev <- levels(droplevels(pairs$level)) + est <- lapply(lev, function(g){ + .local_variogram( + pairs[pairs$level == g, ], lags, window, conf.level, a0) + }) + comp <- lapply(est[-1L], function(e2){ + .compare_levels(est[[1L]], e2) + }) + est <- lapply(seq_along(lev), function(i){ + cbind(level = lev[[i]], + .format_variogram(est[[i]], at.time, conf.level)) + }) + comp <- lapply(seq_along(comp), function(i){ + lab <- paste(lev[[i + 1L]], "/", lev[[1L]]) + cbind(level = lab, .format_variogram(comp[[i]], at.time, conf.level)) + }) + res <- do.call(rbind, c(est, comp)) + res <- res[order(res$lag), , drop = FALSE] + rownames(res) <- NULL + names(res)[names(res) == "level"] <- split.by + res <- res[, c("lag", split.by, setdiff(names(res), c("lag", split.by)))] + return(res) +} + +# The time at which D(L) is estimated: NA (no adjustment), the values given, +# or the median midpoint of all pairs in each lag window +.get_at_time <- function(pairs, lags, at.time, window){ + if( is.null(at.time) ){ + return(rep(NA_real_, length(lags))) + } + if( is.numeric(at.time) ){ + return(rep_len(as.numeric(at.time), length(lags))) + } + a0 <- vapply(lags, function(l){ + in_window <- pairs$h >= l / window & pairs$h <= l * window + if( any(in_window) ) stats::median(pairs$mid[in_window]) else NA_real_ + }, numeric(1L)) + return(a0) +} + +# Local quadratic estimate of D(L) with a cluster-robust (CR1) interval +.local_variogram <- function(pairs, lags, window, conf.level, a0){ + k <- max(5L, ceiling(0.2 * length(unique(pairs$subject)))) + res <- lapply(seq_along(lags), function(i){ + .local_variogram_at(pairs, lags[[i]], a0[[i]], k, window, conf.level) + }) + res <- do.call(rbind, res) + return(res) +} + +.local_variogram_at <- function(pairs, l, a0, k, window, conf.level){ + rows <- which(pairs$h >= l / window & pairs$h <= l * window) + if( !is.na(a0) ){ + # Local in time too: midpoints within a factor of two of the target + # on the 1 + time scale + r <- (1 + pmax(pairs$mid[rows], 0)) / (1 + max(a0, 0)) + rows <- rows[r >= 1 / 2 & r <= 2] + } + q <- pairs[rows, , drop = FALSE] + subj <- q$subject + ns <- table(subj) + G <- length(ns) + res <- data.frame( + lag = l, estimate = NA_real_, se = NA_real_, df = NA_real_, + n.subjects = G, n.pairs = nrow(q), supported = FALSE, at.time = a0) + # Interpolation only: pairs from at least three subjects on each side + below <- length(unique(subj[q$h <= l])) + above <- length(unique(subj[q$h >= l])) + if( G < max(k, 3L) || below < 3L || above < 3L ){ + return(res) + } + u <- log(q$h / l) + X <- cbind(1, u, u^2) + if( !is.na(a0) ){ + if( length(unique(subj[q$mid <= a0])) < 3L || + length(unique(subj[q$mid >= a0])) < 3L ){ + return(res) + } + z <- log1p(pmax(q$mid, 0)) - log1p(max(a0, 0)) + X <- cbind(X, z, z^2) + } + # Each subject's pairs in the window count as one subject + w <- as.numeric(1 / ns[subj]) + A <- crossprod(X, X * w) + if( qr(A)$rank < ncol(X) ){ + return(res) + } + Ai <- solve(A) + b <- Ai %*% crossprod(X, w * q$d) + r <- q$d - drop(X %*% b) + U <- rowsum(X * (w * r), subj) + V <- Ai %*% crossprod(U) %*% Ai * G / (G - 1) + D <- b[[1L]] + if( !is.finite(D) || D <= 0 ){ + return(res) + } + res$estimate <- D + res$se <- sqrt(V[1L, 1L]) / D + res$df <- G - 1 + res$supported <- TRUE + return(res) +} + +# Ratio of D(L) between two levels, with a Welch-Satterthwaite t test of the +# log ratio +.compare_levels <- function(e1, e2){ + lr <- log(e2$estimate) - log(e1$estimate) + se <- sqrt(e1$se^2 + e2$se^2) + df <- se^4 / (e1$se^4 / e1$df + e2$se^4 / e2$df) + ok <- e1$supported & e2$supported + data.frame( + lag = e1$lag, estimate = exp(lr), se = se, df = df, + n.subjects = e1$n.subjects + e2$n.subjects, + n.pairs = e1$n.pairs + e2$n.pairs, supported = ok, + at.time = e1$at.time, + p.value = ifelse(ok, 2 * stats::pt(-abs(lr / se), df), NA_real_), + type = "ratio") +} + +# Confidence intervals on the log scale, and columns in a fixed order +.format_variogram <- function(res, at.time, conf.level){ + if( is.null(res$type) ){ + res$type <- "dissimilarity" + res$p.value <- NA_real_ + } + q <- stats::qt(1 - (1 - conf.level) / 2, res$df) + res$lower <- res$estimate * exp(-q * res$se) + res$upper <- res$estimate * exp(q * res$se) + cols <- c("lag", "type", "estimate", "lower", "upper", "se", "df", + "p.value", "n.subjects", "n.pairs", "supported") + if( !is.null(at.time) ){ + cols <- c(cols, "at.time") + } + res <- res[, cols] + return(res) +} diff --git a/man/getTemporalVariogram.Rd b/man/getTemporalVariogram.Rd new file mode 100644 index 0000000..4370dfc --- /dev/null +++ b/man/getTemporalVariogram.Rd @@ -0,0 +1,219 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/AllGenerics.R, R/getTemporalVariogram.R +\name{getTemporalVariogram} +\alias{getTemporalVariogram} +\alias{addTemporalVariogram} +\alias{addTemporalVariogram,SummarizedExperiment-method} +\alias{getTemporalVariogram,SummarizedExperiment-method} +\title{Community change at stated time lags (temporal variogram)} +\usage{ +getTemporalVariogram(x, ...) + +addTemporalVariogram(x, ...) + +\S4method{addTemporalVariogram}{SummarizedExperiment}(x, name = "temporal_variogram", ...) + +\S4method{getTemporalVariogram}{SummarizedExperiment}( + x, + time.col, + group, + assay.type = "counts", + method = "bray", + lags = NULL, + split.by = NULL, + at.time = NULL, + window = 2, + squared = FALSE, + conf.level = 0.95, + ... +) +} +\arguments{ +\item{x}{A +\code{\link[SummarizedExperiment:SummarizedExperiment-class]{SummarizedExperiment}} +object.} + +\item{...}{additional arguments passed to +\code{\link[mia:getDissimilarity]{getDissimilarity()}}.} + +\item{name}{\code{Character scalar}. Specifies a name for storing the +results in \code{metadata}. (Default: \code{"temporal_variogram"})} + +\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{group}{\code{Character scalar}. Specifies a name of the column from +\code{colData} that identifies the subject (or other unit followed over +time) of each sample. Pairs are formed within subjects.} + +\item{assay.type}{\code{Character scalar}. Specifies which assay values are +used in the dissimilarity estimation. (Default: \code{"counts"})} + +\item{method}{\code{Character scalar}. Used to calculate the dissimilarity +Method is passed to the function that is specified by \code{dis.fun}. +(Default: \code{"bray"})} + +\item{lags}{\code{NULL} or \code{numeric vector}. The lags \eqn{L}, in +the units of \code{time.col}, at which \eqn{D(L)} is estimated. If +\code{NULL}, ten lags between the shortest and longest supported lag. +(Default: \code{NULL})} + +\item{split.by}{\code{NULL} or \code{Character scalar}. Specifies a name +of a column from \code{colData} with one value per subject. \eqn{D(L)} is +estimated for each of its levels, and each level is compared with the +first. (Default: \code{NULL})} + +\item{at.time}{\code{NULL}, \code{numeric vector} or \code{"median"}. The +time at which \eqn{D(L)} is estimated, for communities whose change +depends on time since a common origin; one value, or one per lag. See +details. (Default: \code{NULL})} + +\item{window}{\code{Numeric scalar}. Pairs with lags within a factor of +\code{window} of \eqn{L} are used. (Default: \code{2})} + +\item{squared}{\code{Logical scalar}. Whether the dissimilarities are +squared. (Default: \code{FALSE})} + +\item{conf.level}{\code{Numeric scalar}. Confidence level of the +intervals. (Default: \code{0.95})} +} +\value{ +\code{getTemporalVariogram} returns a \code{DataFrame} with one row per +lag (and level of \code{split.by}, and comparison) and the columns +\describe{ +\item{lag}{The lag \eqn{L}.} +\item{\code{split.by}}{When \code{split.by} is given: the level, or the +comparison (\code{"B / A"}).} +\item{type}{\code{"dissimilarity"} for estimates of \eqn{D(L)}, +\code{"ratio"} for comparisons between levels.} +\item{estimate, lower, upper}{\eqn{D(L)} or the ratio of \eqn{D(L)}, +with the confidence interval.} +\item{se}{Standard error on the log scale.} +\item{df}{Degrees of freedom of the t distribution.} +\item{p.value}{For comparisons, the p-value of the test that the ratio +is 1.} +\item{n.subjects, n.pairs}{Subjects and pairs in the lag window.} +\item{supported}{Whether the design supports \eqn{D(L)} at this lag.} +\item{at.time}{The time at which \eqn{D(L)} was estimated, when +\code{at.time} is given.} +} +\code{addTemporalVariogram} returns \code{x} with this table in its +\code{metadata}. +} +\description{ +Estimates \eqn{D(L)}, the expected dissimilarity between two samples of the +same subject taken \eqn{L} time units apart, from all within-subject sample +pairs. Unlike divergence to the previous sample, \eqn{D(L)} refers to a +stated lag, so it can be compared between subjects, groups and studies +whose sampling schedules differ. +} +\details{ +Every pair of samples from the same subject measures how much the +community changed over that pair's time lag \eqn{h}. The temporal +variogram \eqn{g(h)} is the expected dissimilarity as a function of the +lag, and \eqn{D(L) = g(L)}. Divergence to the previous sample measures +change at whatever intervals the schedule happens to have, so it differs +between designs even when the dynamics are the same. + +\eqn{D(L)} is estimated locally. Pairs with lags in +\eqn{[L / window, L \times window]} are used, and the dissimilarities are +regressed on \eqn{u = \log(h / L)} and \eqn{u^2} by weighted least +squares; the intercept estimates \eqn{D(L)}. The pairs of each subject are +weighted so that every subject counts equally. Pairs of the same subject +share samples and are correlated, so the standard error is cluster-robust +by subject (CR1), and the interval for \eqn{\log D(L)} uses a t +distribution with \eqn{G - 1} degrees of freedom, where \eqn{G} is the +number of subjects with pairs in the window. + +\eqn{D(L)} is reported only at lags the design supports: at least +\eqn{\max(5, 20\%)} of the subjects with two or more samples must have +pairs in the window, and at least three subjects must have pairs at lags +up to \eqn{L} and three at lags from \eqn{L}, so that \eqn{D(L)} is +interpolated, not extrapolated. Elsewhere the estimate is \code{NA} and +\code{supported} is \code{FALSE}. + +When \code{lags = NULL}, ten lags are spread evenly on the log scale +between the shortest and longest supported lag of the whole data: the +smallest and largest lag reached by at least \eqn{\max(5, 20\%)} of the +subjects. + +\strong{Groups.} With \code{split.by}, \eqn{D(L)} is estimated separately +for each level of a subject-level variable, and each level is compared +with the first level by the ratio of \eqn{D(L)}, with a +Welch–Satterthwaite t test of the log ratio. The comparison is made only +at lags supported in both groups. P-values are not adjusted for multiple +comparisons. + +\strong{Developing communities.} When change at a given lag depends on +the time since a common origin (age in infant cohorts, time since an +intervention), groups whose samples were taken at different ages differ +in \eqn{D(L)} even with the same development. \code{at.time} estimates +\eqn{D(L)} at a stated time \eqn{a}: only pairs whose midpoint \eqn{m} +satisfies \eqn{(1 + m) / (1 + a)} in \eqn{[1/2, 2]} are used, the +regression adds \eqn{z = \log(1 + m) - \log(1 + a)} and \eqn{z^2}, and +at least three subjects must have midpoints up to \eqn{a} and three from +\eqn{a}. With \code{at.time = "median"}, \eqn{a} is the median midpoint of +all pairs in the lag window, pooled over the levels of \code{split.by}, so +that every group is evaluated at the same time. Time must then be +measured from the common origin and be non-negative. + +\strong{Dissimilarity.} Any dissimilarity of +\code{\link[mia:getDissimilarity]{getDissimilarity()}} can be used. The +squared Euclidean distance between Hellinger-transformed abundances +(\code{method = "euclidean"}, \code{squared = TRUE} on a +\code{"hellinger"} assay) adds technical noise to the dissimilarity +additively, so the noise does not change the shape of the variogram, only +its level. Dissimilarities depend on sequencing depth; rarefy the counts +first (\code{\link[mia:rarefyAssay]{rarefyAssay()}}) when depth differs +between samples or groups. +} +\examples{ +library(miaTime) + +data(hitchip1006) +tse <- transformAssay(hitchip1006, method = "hellinger") + +# Change over 1 to 9 time units, as squared Hellinger distance +res <- getTemporalVariogram( + tse, + time.col = "time", + group = "subject", + assay.type = "hellinger", + method = "euclidean", + squared = TRUE, + lags = c(1, 3, 6, 9) + ) +res + +# Compare the sexes +res <- getTemporalVariogram( + tse, + time.col = "time", + group = "subject", + assay.type = "hellinger", + method = "euclidean", + squared = TRUE, + lags = c(1, 3), + split.by = "sex" + ) +res[res$type == "ratio", ] + +# Store the results in metadata +tse <- addTemporalVariogram( + tse, + time.col = "time", + group = "subject", + assay.type = "hellinger", + method = "euclidean", + squared = TRUE + ) +metadata(tse)[["temporal_variogram"]] + +} +\references{ +Diggle P.J. (1988) An approach to the analysis of repeated measurements. +Biometrics 44, 959–971. doi: 10.2307/2531727 +} +\seealso{ +\code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}} +} diff --git a/tests/testthat/test-getTemporalVariogram.R b/tests/testthat/test-getTemporalVariogram.R new file mode 100644 index 0000000..8625e3e --- /dev/null +++ b/tests/testthat/test-getTemporalVariogram.R @@ -0,0 +1,132 @@ +test_that("getTemporalVariogram input checks", { + data(hitchip1006, package = "miaTime") + tse <- hitchip1006 + expect_error(getTemporalVariogram(tse, time.col = "x", group = "subject")) + expect_error(getTemporalVariogram(tse, time.col = "sex", + group = "subject")) + expect_error(getTemporalVariogram(tse, time.col = "time", group = "x")) + expect_error(getTemporalVariogram(tse, time.col = "time", + group = "subject", assay.type = "x")) + expect_error(getTemporalVariogram(tse, time.col = "time", + group = "subject", lags = -1)) + expect_error(getTemporalVariogram(tse, time.col = "time", + group = "subject", lags = 1, window = 1)) + expect_error(getTemporalVariogram(tse, time.col = "time", + group = "subject", lags = 1, at.time = "mean")) + expect_error(getTemporalVariogram(tse, time.col = "time", + group = "subject", lags = c(1, 2), at.time = c(1, 2, 3))) + expect_error(getTemporalVariogram(tse, time.col = "time", + group = "subject", lags = 1, conf.level = 1)) + # split.by must be constant within subjects + expect_error(getTemporalVariogram(tse, time.col = "time", + group = "subject", lags = 1, split.by = "time")) +}) + +# Pairs of n subjects with lags spread around 10 and d an exact quadratic in +# log(h / 10) +.make_quadratic_pairs <- function(n = 20, at = 0.3){ + h <- rep(c(6, 8, 10, 12, 15), n) + u <- log(h / 10) + data.frame( + subject = rep(paste0("s", seq_len(n)), each = 5), + h = h, mid = 10, d = at + 0.1 * u - 0.05 * u^2) +} + +test_that("Local estimate is exact when the variogram is quadratic", { + pairs <- .make_quadratic_pairs() + res <- miaTime:::.local_variogram(pairs, lags = 10, window = 2, + conf.level = 0.95, a0 = NA_real_) + expect_equal(res$estimate, 0.3) + expect_true(res$supported) + expect_equal(res$n.subjects, 20L) + expect_equal(res$df, 19) + expect_equal(res$se, 0, tolerance = 1e-8) +}) + +test_that("D(L) is reported only at supported lags", { + # Fewer than five subjects + pairs <- .make_quadratic_pairs(n = 4) + res <- miaTime:::.local_variogram(pairs, lags = 10, window = 2, + conf.level = 0.95, a0 = NA_real_) + expect_false(res$supported) + expect_true(is.na(res$estimate)) + # No pairs above L: extrapolation is not reported + pairs <- .make_quadratic_pairs() + pairs <- pairs[pairs$h < 10, ] + res <- miaTime:::.local_variogram(pairs, lags = 10, window = 2, + conf.level = 0.95, a0 = NA_real_) + expect_false(res$supported) +}) + +test_that("getTemporalVariogram output", { + data(hitchip1006, package = "miaTime") + tse <- transformAssay(hitchip1006, method = "hellinger") + res <- getTemporalVariogram(tse, time.col = "time", group = "subject", + assay.type = "hellinger", method = "euclidean", squared = TRUE, + lags = c(1, 3, 6)) + expect_s4_class(res, "DataFrame") + expect_equal(res$lag, c(1, 3, 6)) + expect_true(all(res$type == "dissimilarity")) + ok <- res$supported + expect_true(any(ok)) + expect_true(all(res$lower[ok] < res$estimate[ok])) + expect_true(all(res$estimate[ok] < res$upper[ok])) + expect_true(all(is.na(res$estimate[!ok]))) + # Squaring changes the dissimilarity + res2 <- getTemporalVariogram(tse, time.col = "time", group = "subject", + assay.type = "hellinger", method = "euclidean", lags = c(1, 3, 6)) + expect_false(isTRUE(all.equal(res$estimate[ok], res2$estimate[ok]))) + # Wider intervals at a higher confidence level + res3 <- getTemporalVariogram(tse, time.col = "time", group = "subject", + assay.type = "hellinger", method = "euclidean", squared = TRUE, + lags = c(1, 3, 6), conf.level = 0.99) + expect_equal(res3$estimate, res$estimate) + expect_true(all(res3$upper[ok] > res$upper[ok])) + # Default lags + res4 <- getTemporalVariogram(tse, time.col = "time", group = "subject", + assay.type = "hellinger", method = "euclidean", squared = TRUE) + expect_true(nrow(res4) > 1L) + expect_true(all(diff(res4$lag) > 0)) +}) + +test_that("getTemporalVariogram compares groups", { + data(hitchip1006, package = "miaTime") + tse <- transformAssay(hitchip1006, method = "hellinger") + expect_message(res <- getTemporalVariogram(tse, time.col = "time", + group = "subject", assay.type = "hellinger", method = "euclidean", + squared = TRUE, lags = c(3, 6), split.by = "sex")) + expect_true("sex" %in% colnames(res)) + expect_equal(nrow(res), 6L) + est <- res[res$type == "dissimilarity", ] + rat <- res[res$type == "ratio", ] + expect_equal(unique(rat$sex), "male / female") + for( l in c(3, 6) ){ + e <- est[est$lag == l, ] + r <- rat[rat$lag == l, ] + expect_equal(r$estimate, + e$estimate[e$sex == "male"] / e$estimate[e$sex == "female"]) + expect_equal(r$n.subjects, sum(e$n.subjects)) + expect_true(r$p.value >= 0 && r$p.value <= 1) + } + expect_true(all(is.na(est$p.value))) + # Comparison at a common time + expect_message(res <- getTemporalVariogram(tse, time.col = "time", + group = "subject", assay.type = "hellinger", method = "euclidean", + squared = TRUE, lags = c(3, 6), split.by = "sex", + at.time = "median")) + expect_true("at.time" %in% colnames(res)) + expect_equal(length(unique(res$at.time[res$lag == 6])), 1L) +}) + +test_that("addTemporalVariogram stores results in metadata", { + data(hitchip1006, package = "miaTime") + tse <- transformAssay(hitchip1006, method = "hellinger") + args <- list(time.col = "time", group = "subject", + assay.type = "hellinger", method = "euclidean", lags = c(3, 6)) + res <- do.call(getTemporalVariogram, c(list(x = tse), args)) + tse <- do.call(addTemporalVariogram, c(list(x = tse), args)) + expect_equal(metadata(tse)[["temporal_variogram"]], res) + tse <- do.call(addTemporalVariogram, + c(list(x = tse, name = "vario"), args)) + expect_equal(metadata(tse)[["vario"]], res) +}) From 3f4605f7fc57c80574203ef0128c1232bc34704f Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Wed, 21 Oct 2026 11:19:03 +0300 Subject: [PATCH 2/8] Rename to getVariogram and add microbiome references --- R/{getTemporalVariogram.R => getVariogram.R} | 0 man/getTemporalVariogram.Rd | 219 ------------------ ...emporalVariogram.R => test-getVariogram.R} | 0 3 files changed, 219 deletions(-) rename R/{getTemporalVariogram.R => getVariogram.R} (100%) delete mode 100644 man/getTemporalVariogram.Rd rename tests/testthat/{test-getTemporalVariogram.R => test-getVariogram.R} (100%) diff --git a/R/getTemporalVariogram.R b/R/getVariogram.R similarity index 100% rename from R/getTemporalVariogram.R rename to R/getVariogram.R diff --git a/man/getTemporalVariogram.Rd b/man/getTemporalVariogram.Rd deleted file mode 100644 index 4370dfc..0000000 --- a/man/getTemporalVariogram.Rd +++ /dev/null @@ -1,219 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/AllGenerics.R, R/getTemporalVariogram.R -\name{getTemporalVariogram} -\alias{getTemporalVariogram} -\alias{addTemporalVariogram} -\alias{addTemporalVariogram,SummarizedExperiment-method} -\alias{getTemporalVariogram,SummarizedExperiment-method} -\title{Community change at stated time lags (temporal variogram)} -\usage{ -getTemporalVariogram(x, ...) - -addTemporalVariogram(x, ...) - -\S4method{addTemporalVariogram}{SummarizedExperiment}(x, name = "temporal_variogram", ...) - -\S4method{getTemporalVariogram}{SummarizedExperiment}( - x, - time.col, - group, - assay.type = "counts", - method = "bray", - lags = NULL, - split.by = NULL, - at.time = NULL, - window = 2, - squared = FALSE, - conf.level = 0.95, - ... -) -} -\arguments{ -\item{x}{A -\code{\link[SummarizedExperiment:SummarizedExperiment-class]{SummarizedExperiment}} -object.} - -\item{...}{additional arguments passed to -\code{\link[mia:getDissimilarity]{getDissimilarity()}}.} - -\item{name}{\code{Character scalar}. Specifies a name for storing the -results in \code{metadata}. (Default: \code{"temporal_variogram"})} - -\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{group}{\code{Character scalar}. Specifies a name of the column from -\code{colData} that identifies the subject (or other unit followed over -time) of each sample. Pairs are formed within subjects.} - -\item{assay.type}{\code{Character scalar}. Specifies which assay values are -used in the dissimilarity estimation. (Default: \code{"counts"})} - -\item{method}{\code{Character scalar}. Used to calculate the dissimilarity -Method is passed to the function that is specified by \code{dis.fun}. -(Default: \code{"bray"})} - -\item{lags}{\code{NULL} or \code{numeric vector}. The lags \eqn{L}, in -the units of \code{time.col}, at which \eqn{D(L)} is estimated. If -\code{NULL}, ten lags between the shortest and longest supported lag. -(Default: \code{NULL})} - -\item{split.by}{\code{NULL} or \code{Character scalar}. Specifies a name -of a column from \code{colData} with one value per subject. \eqn{D(L)} is -estimated for each of its levels, and each level is compared with the -first. (Default: \code{NULL})} - -\item{at.time}{\code{NULL}, \code{numeric vector} or \code{"median"}. The -time at which \eqn{D(L)} is estimated, for communities whose change -depends on time since a common origin; one value, or one per lag. See -details. (Default: \code{NULL})} - -\item{window}{\code{Numeric scalar}. Pairs with lags within a factor of -\code{window} of \eqn{L} are used. (Default: \code{2})} - -\item{squared}{\code{Logical scalar}. Whether the dissimilarities are -squared. (Default: \code{FALSE})} - -\item{conf.level}{\code{Numeric scalar}. Confidence level of the -intervals. (Default: \code{0.95})} -} -\value{ -\code{getTemporalVariogram} returns a \code{DataFrame} with one row per -lag (and level of \code{split.by}, and comparison) and the columns -\describe{ -\item{lag}{The lag \eqn{L}.} -\item{\code{split.by}}{When \code{split.by} is given: the level, or the -comparison (\code{"B / A"}).} -\item{type}{\code{"dissimilarity"} for estimates of \eqn{D(L)}, -\code{"ratio"} for comparisons between levels.} -\item{estimate, lower, upper}{\eqn{D(L)} or the ratio of \eqn{D(L)}, -with the confidence interval.} -\item{se}{Standard error on the log scale.} -\item{df}{Degrees of freedom of the t distribution.} -\item{p.value}{For comparisons, the p-value of the test that the ratio -is 1.} -\item{n.subjects, n.pairs}{Subjects and pairs in the lag window.} -\item{supported}{Whether the design supports \eqn{D(L)} at this lag.} -\item{at.time}{The time at which \eqn{D(L)} was estimated, when -\code{at.time} is given.} -} -\code{addTemporalVariogram} returns \code{x} with this table in its -\code{metadata}. -} -\description{ -Estimates \eqn{D(L)}, the expected dissimilarity between two samples of the -same subject taken \eqn{L} time units apart, from all within-subject sample -pairs. Unlike divergence to the previous sample, \eqn{D(L)} refers to a -stated lag, so it can be compared between subjects, groups and studies -whose sampling schedules differ. -} -\details{ -Every pair of samples from the same subject measures how much the -community changed over that pair's time lag \eqn{h}. The temporal -variogram \eqn{g(h)} is the expected dissimilarity as a function of the -lag, and \eqn{D(L) = g(L)}. Divergence to the previous sample measures -change at whatever intervals the schedule happens to have, so it differs -between designs even when the dynamics are the same. - -\eqn{D(L)} is estimated locally. Pairs with lags in -\eqn{[L / window, L \times window]} are used, and the dissimilarities are -regressed on \eqn{u = \log(h / L)} and \eqn{u^2} by weighted least -squares; the intercept estimates \eqn{D(L)}. The pairs of each subject are -weighted so that every subject counts equally. Pairs of the same subject -share samples and are correlated, so the standard error is cluster-robust -by subject (CR1), and the interval for \eqn{\log D(L)} uses a t -distribution with \eqn{G - 1} degrees of freedom, where \eqn{G} is the -number of subjects with pairs in the window. - -\eqn{D(L)} is reported only at lags the design supports: at least -\eqn{\max(5, 20\%)} of the subjects with two or more samples must have -pairs in the window, and at least three subjects must have pairs at lags -up to \eqn{L} and three at lags from \eqn{L}, so that \eqn{D(L)} is -interpolated, not extrapolated. Elsewhere the estimate is \code{NA} and -\code{supported} is \code{FALSE}. - -When \code{lags = NULL}, ten lags are spread evenly on the log scale -between the shortest and longest supported lag of the whole data: the -smallest and largest lag reached by at least \eqn{\max(5, 20\%)} of the -subjects. - -\strong{Groups.} With \code{split.by}, \eqn{D(L)} is estimated separately -for each level of a subject-level variable, and each level is compared -with the first level by the ratio of \eqn{D(L)}, with a -Welch–Satterthwaite t test of the log ratio. The comparison is made only -at lags supported in both groups. P-values are not adjusted for multiple -comparisons. - -\strong{Developing communities.} When change at a given lag depends on -the time since a common origin (age in infant cohorts, time since an -intervention), groups whose samples were taken at different ages differ -in \eqn{D(L)} even with the same development. \code{at.time} estimates -\eqn{D(L)} at a stated time \eqn{a}: only pairs whose midpoint \eqn{m} -satisfies \eqn{(1 + m) / (1 + a)} in \eqn{[1/2, 2]} are used, the -regression adds \eqn{z = \log(1 + m) - \log(1 + a)} and \eqn{z^2}, and -at least three subjects must have midpoints up to \eqn{a} and three from -\eqn{a}. With \code{at.time = "median"}, \eqn{a} is the median midpoint of -all pairs in the lag window, pooled over the levels of \code{split.by}, so -that every group is evaluated at the same time. Time must then be -measured from the common origin and be non-negative. - -\strong{Dissimilarity.} Any dissimilarity of -\code{\link[mia:getDissimilarity]{getDissimilarity()}} can be used. The -squared Euclidean distance between Hellinger-transformed abundances -(\code{method = "euclidean"}, \code{squared = TRUE} on a -\code{"hellinger"} assay) adds technical noise to the dissimilarity -additively, so the noise does not change the shape of the variogram, only -its level. Dissimilarities depend on sequencing depth; rarefy the counts -first (\code{\link[mia:rarefyAssay]{rarefyAssay()}}) when depth differs -between samples or groups. -} -\examples{ -library(miaTime) - -data(hitchip1006) -tse <- transformAssay(hitchip1006, method = "hellinger") - -# Change over 1 to 9 time units, as squared Hellinger distance -res <- getTemporalVariogram( - tse, - time.col = "time", - group = "subject", - assay.type = "hellinger", - method = "euclidean", - squared = TRUE, - lags = c(1, 3, 6, 9) - ) -res - -# Compare the sexes -res <- getTemporalVariogram( - tse, - time.col = "time", - group = "subject", - assay.type = "hellinger", - method = "euclidean", - squared = TRUE, - lags = c(1, 3), - split.by = "sex" - ) -res[res$type == "ratio", ] - -# Store the results in metadata -tse <- addTemporalVariogram( - tse, - time.col = "time", - group = "subject", - assay.type = "hellinger", - method = "euclidean", - squared = TRUE - ) -metadata(tse)[["temporal_variogram"]] - -} -\references{ -Diggle P.J. (1988) An approach to the analysis of repeated measurements. -Biometrics 44, 959–971. doi: 10.2307/2531727 -} -\seealso{ -\code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}} -} diff --git a/tests/testthat/test-getTemporalVariogram.R b/tests/testthat/test-getVariogram.R similarity index 100% rename from tests/testthat/test-getTemporalVariogram.R rename to tests/testthat/test-getVariogram.R From 5eef3d561f39b913dfb45630d94bb2b6f3b9ec90 Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Wed, 21 Oct 2026 11:19:14 +0300 Subject: [PATCH 3/8] Rename to getVariogram and add microbiome references --- NAMESPACE | 8 +- R/AllGenerics.R | 12 +- R/getVariogram.R | 40 +++-- man/getVariogram.Rd | 227 +++++++++++++++++++++++++++++ tests/testthat/test-getVariogram.R | 48 +++--- 5 files changed, 285 insertions(+), 50 deletions(-) create mode 100644 man/getVariogram.Rd diff --git a/NAMESPACE b/NAMESPACE index 6bdf32d..5b60ec4 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -5,25 +5,25 @@ export(addBimodality) export(addShortTermChange) export(addStability) export(addStepwiseDivergence) -export(addTemporalVariogram) +export(addVariogram) export(getBaselineDivergence) export(getBimodality) export(getShortTermChange) export(getStability) export(getStepwiseDivergence) -export(getTemporalVariogram) +export(getVariogram) exportMethods(addBaselineDivergence) exportMethods(addBimodality) exportMethods(addShortTermChange) exportMethods(addStability) exportMethods(addStepwiseDivergence) -exportMethods(addTemporalVariogram) +exportMethods(addVariogram) exportMethods(getBaselineDivergence) exportMethods(getBimodality) exportMethods(getShortTermChange) exportMethods(getStability) exportMethods(getStepwiseDivergence) -exportMethods(getTemporalVariogram) +exportMethods(getVariogram) import(S4Vectors) import(SingleCellExperiment) import(SummarizedExperiment) diff --git a/R/AllGenerics.R b/R/AllGenerics.R index 63249df..95bf1d4 100644 --- a/R/AllGenerics.R +++ b/R/AllGenerics.R @@ -51,12 +51,12 @@ setGeneric("getStability", signature = "x", function(x, ...) setGeneric("addStability", signature = "x", function(x, ...) standardGeneric("addStability")) -#' @rdname getTemporalVariogram +#' @rdname getVariogram #' @export -setGeneric("getTemporalVariogram", signature = "x", function(x, ...) - standardGeneric("getTemporalVariogram")) +setGeneric("getVariogram", signature = "x", function(x, ...) + standardGeneric("getVariogram")) -#' @rdname getTemporalVariogram +#' @rdname getVariogram #' @export -setGeneric("addTemporalVariogram", signature = "x", function(x, ...) - standardGeneric("addTemporalVariogram")) +setGeneric("addVariogram", signature = "x", function(x, ...) + standardGeneric("addVariogram")) diff --git a/R/getVariogram.R b/R/getVariogram.R index c459c2f..8696eb4 100644 --- a/R/getVariogram.R +++ b/R/getVariogram.R @@ -1,5 +1,5 @@ #' @name -#' getTemporalVariogram +#' getVariogram #' #' @export #' @@ -77,8 +77,16 @@ #' Diggle P.J. (1988) An approach to the analysis of repeated measurements. #' Biometrics 44, 959–971. doi: 10.2307/2531727 #' +#' Lloyd-Price J., et al. (2019) Multi-omics of the gut microbial ecosystem in +#' inflammatory bowel diseases. Nature 569, 655–662. +#' doi: 10.1038/s41586-019-1237-9 +#' +#' Björk J.R., et al. (2022) Synchrony and idiosyncrasy in the gut microbiome +#' of wild baboons. Nature Ecology & Evolution 6, 955–964. +#' doi: 10.1038/s41559-022-01773-4 +#' #' @return -#' \code{getTemporalVariogram} returns a \code{DataFrame} with one row per +#' \code{getVariogram} returns a \code{DataFrame} with one row per #' lag (and level of \code{split.by}, and comparison) and the columns #' \describe{ #' \item{lag}{The lag \eqn{L}.} @@ -97,7 +105,7 @@ #' \item{at.time}{The time at which \eqn{D(L)} was estimated, when #' \code{at.time} is given.} #' } -#' \code{addTemporalVariogram} returns \code{x} with this table in its +#' \code{addVariogram} returns \code{x} with this table in its #' \code{metadata}. #' #' @inheritParams addBaselineDivergence @@ -131,7 +139,7 @@ #' intervals. (Default: \code{0.95}) #' #' @param name \code{Character scalar}. Specifies a name for storing the -#' results in \code{metadata}. (Default: \code{"temporal_variogram"}) +#' results in \code{metadata}. (Default: \code{"variogram"}) #' #' @param ... additional arguments passed to #' \code{\link[mia:getDissimilarity]{getDissimilarity()}}. @@ -143,7 +151,7 @@ #' tse <- transformAssay(hitchip1006, method = "hellinger") #' #' # Change over 1 to 9 time units, as squared Hellinger distance -#' res <- getTemporalVariogram( +#' res <- getVariogram( #' tse, #' time.col = "time", #' group = "subject", @@ -155,7 +163,7 @@ #' res #' #' # Compare the sexes -#' res <- getTemporalVariogram( +#' res <- getVariogram( #' tse, #' time.col = "time", #' group = "subject", @@ -168,7 +176,7 @@ #' res[res$type == "ratio", ] #' #' # Store the results in metadata -#' tse <- addTemporalVariogram( +#' tse <- addVariogram( #' tse, #' time.col = "time", #' group = "subject", @@ -176,29 +184,29 @@ #' method = "euclidean", #' squared = TRUE #' ) -#' metadata(tse)[["temporal_variogram"]] +#' metadata(tse)[["variogram"]] #' #' @seealso #' \code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}} #' NULL -#' @rdname getTemporalVariogram +#' @rdname getVariogram #' @export -setMethod("addTemporalVariogram", signature = c(x = "SummarizedExperiment"), - function(x, name = "temporal_variogram", ...){ +setMethod("addVariogram", signature = c(x = "SummarizedExperiment"), + function(x, name = "variogram", ...){ 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(getTemporalVariogram, args) + res <- do.call(getVariogram, args) x <- .add_values_to_metadata(x, name, res, ...) return(x) } ) -#' @rdname getTemporalVariogram +#' @rdname getVariogram #' @export -setMethod("getTemporalVariogram", signature = c(x = "SummarizedExperiment"), +setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), function( x, time.col, @@ -255,7 +263,7 @@ setMethod("getTemporalVariogram", signature = c(x = "SummarizedExperiment"), if( is.null(lags) ){ lags <- .default_lags(pairs) } - res <- .temporal_variogram( + res <- .variogram( pairs, lags, split.by, at.time, window, conf.level) res <- DataFrame(res, check.names = FALSE) return(res) @@ -347,7 +355,7 @@ setMethod("getTemporalVariogram", signature = c(x = "SummarizedExperiment"), } # D(L) for all lags, levels of split.by, and comparisons with the first level -.temporal_variogram <- function( +.variogram <- function( pairs, lags, split.by, at.time, window, conf.level){ a0 <- .get_at_time(pairs, lags, at.time, window) if( is.null(split.by) ){ diff --git a/man/getVariogram.Rd b/man/getVariogram.Rd new file mode 100644 index 0000000..b0d29e5 --- /dev/null +++ b/man/getVariogram.Rd @@ -0,0 +1,227 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/AllGenerics.R, R/getVariogram.R +\name{getVariogram} +\alias{getVariogram} +\alias{addVariogram} +\alias{addVariogram,SummarizedExperiment-method} +\alias{getVariogram,SummarizedExperiment-method} +\title{Community change at stated time lags (temporal variogram)} +\usage{ +getVariogram(x, ...) + +addVariogram(x, ...) + +\S4method{addVariogram}{SummarizedExperiment}(x, name = "variogram", ...) + +\S4method{getVariogram}{SummarizedExperiment}( + x, + time.col, + group, + assay.type = "counts", + method = "bray", + lags = NULL, + split.by = NULL, + at.time = NULL, + window = 2, + squared = FALSE, + conf.level = 0.95, + ... +) +} +\arguments{ +\item{x}{A +\code{\link[SummarizedExperiment:SummarizedExperiment-class]{SummarizedExperiment}} +object.} + +\item{...}{additional arguments passed to +\code{\link[mia:getDissimilarity]{getDissimilarity()}}.} + +\item{name}{\code{Character scalar}. Specifies a name for storing the +results in \code{metadata}. (Default: \code{"variogram"})} + +\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{group}{\code{Character scalar}. Specifies a name of the column from +\code{colData} that identifies the subject (or other unit followed over +time) of each sample. Pairs are formed within subjects.} + +\item{assay.type}{\code{Character scalar}. Specifies which assay values are +used in the dissimilarity estimation. (Default: \code{"counts"})} + +\item{method}{\code{Character scalar}. Used to calculate the dissimilarity +Method is passed to the function that is specified by \code{dis.fun}. +(Default: \code{"bray"})} + +\item{lags}{\code{NULL} or \code{numeric vector}. The lags \eqn{L}, in +the units of \code{time.col}, at which \eqn{D(L)} is estimated. If +\code{NULL}, ten lags between the shortest and longest supported lag. +(Default: \code{NULL})} + +\item{split.by}{\code{NULL} or \code{Character scalar}. Specifies a name +of a column from \code{colData} with one value per subject. \eqn{D(L)} is +estimated for each of its levels, and each level is compared with the +first. (Default: \code{NULL})} + +\item{at.time}{\code{NULL}, \code{numeric vector} or \code{"median"}. The +time at which \eqn{D(L)} is estimated, for communities whose change +depends on time since a common origin; one value, or one per lag. See +details. (Default: \code{NULL})} + +\item{window}{\code{Numeric scalar}. Pairs with lags within a factor of +\code{window} of \eqn{L} are used. (Default: \code{2})} + +\item{squared}{\code{Logical scalar}. Whether the dissimilarities are +squared. (Default: \code{FALSE})} + +\item{conf.level}{\code{Numeric scalar}. Confidence level of the +intervals. (Default: \code{0.95})} +} +\value{ +\code{getVariogram} returns a \code{DataFrame} with one row per +lag (and level of \code{split.by}, and comparison) and the columns +\describe{ +\item{lag}{The lag \eqn{L}.} +\item{\code{split.by}}{When \code{split.by} is given: the level, or the +comparison (\code{"B / A"}).} +\item{type}{\code{"dissimilarity"} for estimates of \eqn{D(L)}, +\code{"ratio"} for comparisons between levels.} +\item{estimate, lower, upper}{\eqn{D(L)} or the ratio of \eqn{D(L)}, +with the confidence interval.} +\item{se}{Standard error on the log scale.} +\item{df}{Degrees of freedom of the t distribution.} +\item{p.value}{For comparisons, the p-value of the test that the ratio +is 1.} +\item{n.subjects, n.pairs}{Subjects and pairs in the lag window.} +\item{supported}{Whether the design supports \eqn{D(L)} at this lag.} +\item{at.time}{The time at which \eqn{D(L)} was estimated, when +\code{at.time} is given.} +} +\code{addVariogram} returns \code{x} with this table in its +\code{metadata}. +} +\description{ +Estimates \eqn{D(L)}, the expected dissimilarity between two samples of the +same subject taken \eqn{L} time units apart, from all within-subject sample +pairs. Unlike divergence to the previous sample, \eqn{D(L)} refers to a +stated lag, so it can be compared between subjects, groups and studies +whose sampling schedules differ. +} +\details{ +Every pair of samples from the same subject measures how much the +community changed over that pair's time lag \eqn{h}. The temporal +variogram \eqn{g(h)} is the expected dissimilarity as a function of the +lag, and \eqn{D(L) = g(L)}. Divergence to the previous sample measures +change at whatever intervals the schedule happens to have, so it differs +between designs even when the dynamics are the same. + +\eqn{D(L)} is estimated locally. Pairs with lags in +\eqn{[L / window, L \times window]} are used, and the dissimilarities are +regressed on \eqn{u = \log(h / L)} and \eqn{u^2} by weighted least +squares; the intercept estimates \eqn{D(L)}. The pairs of each subject are +weighted so that every subject counts equally. Pairs of the same subject +share samples and are correlated, so the standard error is cluster-robust +by subject (CR1), and the interval for \eqn{\log D(L)} uses a t +distribution with \eqn{G - 1} degrees of freedom, where \eqn{G} is the +number of subjects with pairs in the window. + +\eqn{D(L)} is reported only at lags the design supports: at least +\eqn{\max(5, 20\%)} of the subjects with two or more samples must have +pairs in the window, and at least three subjects must have pairs at lags +up to \eqn{L} and three at lags from \eqn{L}, so that \eqn{D(L)} is +interpolated, not extrapolated. Elsewhere the estimate is \code{NA} and +\code{supported} is \code{FALSE}. + +When \code{lags = NULL}, ten lags are spread evenly on the log scale +between the shortest and longest supported lag of the whole data: the +smallest and largest lag reached by at least \eqn{\max(5, 20\%)} of the +subjects. + +\strong{Groups.} With \code{split.by}, \eqn{D(L)} is estimated separately +for each level of a subject-level variable, and each level is compared +with the first level by the ratio of \eqn{D(L)}, with a +Welch–Satterthwaite t test of the log ratio. The comparison is made only +at lags supported in both groups. P-values are not adjusted for multiple +comparisons. + +\strong{Developing communities.} When change at a given lag depends on +the time since a common origin (age in infant cohorts, time since an +intervention), groups whose samples were taken at different ages differ +in \eqn{D(L)} even with the same development. \code{at.time} estimates +\eqn{D(L)} at a stated time \eqn{a}: only pairs whose midpoint \eqn{m} +satisfies \eqn{(1 + m) / (1 + a)} in \eqn{[1/2, 2]} are used, the +regression adds \eqn{z = \log(1 + m) - \log(1 + a)} and \eqn{z^2}, and +at least three subjects must have midpoints up to \eqn{a} and three from +\eqn{a}. With \code{at.time = "median"}, \eqn{a} is the median midpoint of +all pairs in the lag window, pooled over the levels of \code{split.by}, so +that every group is evaluated at the same time. Time must then be +measured from the common origin and be non-negative. + +\strong{Dissimilarity.} Any dissimilarity of +\code{\link[mia:getDissimilarity]{getDissimilarity()}} can be used. The +squared Euclidean distance between Hellinger-transformed abundances +(\code{method = "euclidean"}, \code{squared = TRUE} on a +\code{"hellinger"} assay) adds technical noise to the dissimilarity +additively, so the noise does not change the shape of the variogram, only +its level. Dissimilarities depend on sequencing depth; rarefy the counts +first (\code{\link[mia:rarefyAssay]{rarefyAssay()}}) when depth differs +between samples or groups. +} +\examples{ +library(miaTime) + +data(hitchip1006) +tse <- transformAssay(hitchip1006, method = "hellinger") + +# Change over 1 to 9 time units, as squared Hellinger distance +res <- getVariogram( + tse, + time.col = "time", + group = "subject", + assay.type = "hellinger", + method = "euclidean", + squared = TRUE, + lags = c(1, 3, 6, 9) + ) +res + +# Compare the sexes +res <- getVariogram( + tse, + time.col = "time", + group = "subject", + assay.type = "hellinger", + method = "euclidean", + squared = TRUE, + lags = c(1, 3), + split.by = "sex" + ) +res[res$type == "ratio", ] + +# Store the results in metadata +tse <- addVariogram( + tse, + time.col = "time", + group = "subject", + assay.type = "hellinger", + method = "euclidean", + squared = TRUE + ) +metadata(tse)[["variogram"]] + +} +\references{ +Diggle P.J. (1988) An approach to the analysis of repeated measurements. +Biometrics 44, 959–971. doi: 10.2307/2531727 + +Lloyd-Price J., et al. (2019) Multi-omics of the gut microbial ecosystem in +inflammatory bowel diseases. Nature 569, 655–662. +doi: 10.1038/s41586-019-1237-9 + +Björk J.R., et al. (2022) Synchrony and idiosyncrasy in the gut microbiome +of wild baboons. Nature Ecology & Evolution 6, 955–964. +doi: 10.1038/s41559-022-01773-4 +} +\seealso{ +\code{\link[miaTime:getStepwiseDivergence]{getStepwiseDivergence()}} +} diff --git a/tests/testthat/test-getVariogram.R b/tests/testthat/test-getVariogram.R index 8625e3e..520bbb1 100644 --- a/tests/testthat/test-getVariogram.R +++ b/tests/testthat/test-getVariogram.R @@ -1,24 +1,24 @@ -test_that("getTemporalVariogram input checks", { +test_that("getVariogram input checks", { data(hitchip1006, package = "miaTime") tse <- hitchip1006 - expect_error(getTemporalVariogram(tse, time.col = "x", group = "subject")) - expect_error(getTemporalVariogram(tse, time.col = "sex", + expect_error(getVariogram(tse, time.col = "x", group = "subject")) + expect_error(getVariogram(tse, time.col = "sex", group = "subject")) - expect_error(getTemporalVariogram(tse, time.col = "time", group = "x")) - expect_error(getTemporalVariogram(tse, time.col = "time", + expect_error(getVariogram(tse, time.col = "time", group = "x")) + expect_error(getVariogram(tse, time.col = "time", group = "subject", assay.type = "x")) - expect_error(getTemporalVariogram(tse, time.col = "time", + expect_error(getVariogram(tse, time.col = "time", group = "subject", lags = -1)) - expect_error(getTemporalVariogram(tse, time.col = "time", + expect_error(getVariogram(tse, time.col = "time", group = "subject", lags = 1, window = 1)) - expect_error(getTemporalVariogram(tse, time.col = "time", + expect_error(getVariogram(tse, time.col = "time", group = "subject", lags = 1, at.time = "mean")) - expect_error(getTemporalVariogram(tse, time.col = "time", + expect_error(getVariogram(tse, time.col = "time", group = "subject", lags = c(1, 2), at.time = c(1, 2, 3))) - expect_error(getTemporalVariogram(tse, time.col = "time", + expect_error(getVariogram(tse, time.col = "time", group = "subject", lags = 1, conf.level = 1)) # split.by must be constant within subjects - expect_error(getTemporalVariogram(tse, time.col = "time", + expect_error(getVariogram(tse, time.col = "time", group = "subject", lags = 1, split.by = "time")) }) @@ -58,10 +58,10 @@ test_that("D(L) is reported only at supported lags", { expect_false(res$supported) }) -test_that("getTemporalVariogram output", { +test_that("getVariogram output", { data(hitchip1006, package = "miaTime") tse <- transformAssay(hitchip1006, method = "hellinger") - res <- getTemporalVariogram(tse, time.col = "time", group = "subject", + res <- getVariogram(tse, time.col = "time", group = "subject", assay.type = "hellinger", method = "euclidean", squared = TRUE, lags = c(1, 3, 6)) expect_s4_class(res, "DataFrame") @@ -73,26 +73,26 @@ test_that("getTemporalVariogram output", { expect_true(all(res$estimate[ok] < res$upper[ok])) expect_true(all(is.na(res$estimate[!ok]))) # Squaring changes the dissimilarity - res2 <- getTemporalVariogram(tse, time.col = "time", group = "subject", + res2 <- getVariogram(tse, time.col = "time", group = "subject", assay.type = "hellinger", method = "euclidean", lags = c(1, 3, 6)) expect_false(isTRUE(all.equal(res$estimate[ok], res2$estimate[ok]))) # Wider intervals at a higher confidence level - res3 <- getTemporalVariogram(tse, time.col = "time", group = "subject", + res3 <- getVariogram(tse, time.col = "time", group = "subject", assay.type = "hellinger", method = "euclidean", squared = TRUE, lags = c(1, 3, 6), conf.level = 0.99) expect_equal(res3$estimate, res$estimate) expect_true(all(res3$upper[ok] > res$upper[ok])) # Default lags - res4 <- getTemporalVariogram(tse, time.col = "time", group = "subject", + res4 <- getVariogram(tse, time.col = "time", group = "subject", assay.type = "hellinger", method = "euclidean", squared = TRUE) expect_true(nrow(res4) > 1L) expect_true(all(diff(res4$lag) > 0)) }) -test_that("getTemporalVariogram compares groups", { +test_that("getVariogram compares groups", { data(hitchip1006, package = "miaTime") tse <- transformAssay(hitchip1006, method = "hellinger") - expect_message(res <- getTemporalVariogram(tse, time.col = "time", + expect_message(res <- getVariogram(tse, time.col = "time", group = "subject", assay.type = "hellinger", method = "euclidean", squared = TRUE, lags = c(3, 6), split.by = "sex")) expect_true("sex" %in% colnames(res)) @@ -110,7 +110,7 @@ test_that("getTemporalVariogram compares groups", { } expect_true(all(is.na(est$p.value))) # Comparison at a common time - expect_message(res <- getTemporalVariogram(tse, time.col = "time", + expect_message(res <- getVariogram(tse, time.col = "time", group = "subject", assay.type = "hellinger", method = "euclidean", squared = TRUE, lags = c(3, 6), split.by = "sex", at.time = "median")) @@ -118,15 +118,15 @@ test_that("getTemporalVariogram compares groups", { expect_equal(length(unique(res$at.time[res$lag == 6])), 1L) }) -test_that("addTemporalVariogram stores results in metadata", { +test_that("addVariogram stores results in metadata", { data(hitchip1006, package = "miaTime") tse <- transformAssay(hitchip1006, method = "hellinger") args <- list(time.col = "time", group = "subject", assay.type = "hellinger", method = "euclidean", lags = c(3, 6)) - res <- do.call(getTemporalVariogram, c(list(x = tse), args)) - tse <- do.call(addTemporalVariogram, c(list(x = tse), args)) - expect_equal(metadata(tse)[["temporal_variogram"]], res) - tse <- do.call(addTemporalVariogram, + res <- do.call(getVariogram, c(list(x = tse), args)) + tse <- do.call(addVariogram, c(list(x = tse), args)) + expect_equal(metadata(tse)[["variogram"]], res) + tse <- do.call(addVariogram, c(list(x = tse, name = "vario"), args)) expect_equal(metadata(tse)[["vario"]], res) }) From 08214cf447ddc88829382dbb28a4d1de7dd35875 Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Wed, 21 Oct 2026 13:16:55 +0300 Subject: [PATCH 4/8] Rename at.time to time.point and lags to time.lag --- R/getVariogram.R | 74 +++++++++++++++--------------- man/getVariogram.Rd | 22 ++++----- tests/testthat/test-getVariogram.R | 30 ++++++------ 3 files changed, 64 insertions(+), 62 deletions(-) diff --git a/R/getVariogram.R b/R/getVariogram.R index 8696eb4..ee95b8f 100644 --- a/R/getVariogram.R +++ b/R/getVariogram.R @@ -38,7 +38,7 @@ #' interpolated, not extrapolated. Elsewhere the estimate is \code{NA} and #' \code{supported} is \code{FALSE}. #' -#' When \code{lags = NULL}, ten lags are spread evenly on the log scale +#' When \code{time.lag = NULL}, ten lags are spread evenly on the log scale #' between the shortest and longest supported lag of the whole data: the #' smallest and largest lag reached by at least \eqn{\max(5, 20\%)} of the #' subjects. @@ -53,12 +53,12 @@ #' \strong{Developing communities.} When change at a given lag depends on #' the time since a common origin (age in infant cohorts, time since an #' intervention), groups whose samples were taken at different ages differ -#' in \eqn{D(L)} even with the same development. \code{at.time} estimates +#' in \eqn{D(L)} even with the same development. \code{time.point} estimates #' \eqn{D(L)} at a stated time \eqn{a}: only pairs whose midpoint \eqn{m} #' satisfies \eqn{(1 + m) / (1 + a)} in \eqn{[1/2, 2]} are used, the #' regression adds \eqn{z = \log(1 + m) - \log(1 + a)} and \eqn{z^2}, and #' at least three subjects must have midpoints up to \eqn{a} and three from -#' \eqn{a}. With \code{at.time = "median"}, \eqn{a} is the median midpoint of +#' \eqn{a}. With \code{time.point = "median"}, \eqn{a} is the median midpoint of #' all pairs in the lag window, pooled over the levels of \code{split.by}, so #' that every group is evaluated at the same time. Time must then be #' measured from the common origin and be non-negative. @@ -102,8 +102,8 @@ #' is 1.} #' \item{n.subjects, n.pairs}{Subjects and pairs in the lag window.} #' \item{supported}{Whether the design supports \eqn{D(L)} at this lag.} -#' \item{at.time}{The time at which \eqn{D(L)} was estimated, when -#' \code{at.time} is given.} +#' \item{time.point}{The time at which \eqn{D(L)} was estimated, when +#' \code{time.point} is given.} #' } #' \code{addVariogram} returns \code{x} with this table in its #' \code{metadata}. @@ -114,7 +114,7 @@ #' \code{colData} that identifies the subject (or other unit followed over #' time) of each sample. Pairs are formed within subjects. #' -#' @param lags \code{NULL} or \code{numeric vector}. The lags \eqn{L}, in +#' @param time.lag \code{NULL} or \code{numeric vector}. The lags \eqn{L}, in #' the units of \code{time.col}, at which \eqn{D(L)} is estimated. If #' \code{NULL}, ten lags between the shortest and longest supported lag. #' (Default: \code{NULL}) @@ -124,7 +124,7 @@ #' estimated for each of its levels, and each level is compared with the #' first. (Default: \code{NULL}) #' -#' @param at.time \code{NULL}, \code{numeric vector} or \code{"median"}. The +#' @param time.point \code{NULL}, \code{numeric vector} or \code{"median"}. The #' time at which \eqn{D(L)} is estimated, for communities whose change #' depends on time since a common origin; one value, or one per lag. See #' details. (Default: \code{NULL}) @@ -158,7 +158,7 @@ #' assay.type = "hellinger", #' method = "euclidean", #' squared = TRUE, -#' lags = c(1, 3, 6, 9) +#' time.lag = c(1, 3, 6, 9) #' ) #' res #' @@ -170,7 +170,7 @@ #' assay.type = "hellinger", #' method = "euclidean", #' squared = TRUE, -#' lags = c(1, 3), +#' time.lag = c(1, 3), #' split.by = "sex" #' ) #' res[res$type == "ratio", ] @@ -213,9 +213,9 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), group, assay.type = "counts", method = "bray", - lags = NULL, + time.lag = NULL, split.by = NULL, - at.time = NULL, + time.point = NULL, window = 2, squared = FALSE, conf.level = 0.95, @@ -232,19 +232,21 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), group, list("character scalar"), colnames(colData(x))) .check_assay_present(assay.type, x) temp <- .check_input(method, list("character scalar")) - temp <- .check_input(lags, list(NULL, "numeric vector")) - if( !is.null(lags) && (anyNA(lags) || any(lags <= 0)) ){ - stop("'lags' must be positive.", call. = FALSE) + temp <- .check_input(time.lag, list(NULL, "numeric vector")) + if( !is.null(time.lag) && (anyNA(time.lag) || any(time.lag <= 0)) ){ + stop("'time.lag' must be positive.", call. = FALSE) } temp <- .check_input( split.by, list(NULL, "character scalar"), colnames(colData(x))) - if( !(is.null(at.time) || identical(at.time, "median") || - (is.numeric(at.time) && !anyNA(at.time))) ){ - stop("'at.time' must be NULL, numeric or \"median\".", + if( !(is.null(time.point) || identical(time.point, "median") || + (is.numeric(time.point) && !anyNA(time.point))) ){ + stop("'time.point' must be NULL, numeric or \"median\".", call. = FALSE) } - if( is.numeric(at.time) && !length(at.time) %in% c(1L, length(lags)) ){ - stop("'at.time' must have length 1 or the length of 'lags'.", + if( is.numeric(time.point) && + !length(time.point) %in% c(1L, length(time.lag)) ){ + stop("'time.point' must have length 1 or the length of ", + "'time.lag'.", call. = FALSE) } temp <- .check_input(window, list("numeric scalar")) @@ -260,11 +262,11 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), args <- list(...)[!names(list(...)) %in% c("altexp")] pairs <- .get_within_subject_pairs( x, time.col, group, assay.type, method, split.by, squared, args) - if( is.null(lags) ){ - lags <- .default_lags(pairs) + if( is.null(time.lag) ){ + time.lag <- .default_lags(pairs) } res <- .variogram( - pairs, lags, split.by, at.time, window, conf.level) + pairs, time.lag, split.by, time.point, window, conf.level) res <- DataFrame(res, check.names = FALSE) return(res) } @@ -356,11 +358,11 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), # D(L) for all lags, levels of split.by, and comparisons with the first level .variogram <- function( - pairs, lags, split.by, at.time, window, conf.level){ - a0 <- .get_at_time(pairs, lags, at.time, window) + pairs, lags, split.by, time.point, window, conf.level){ + a0 <- .get_at_time(pairs, lags, time.point, window) if( is.null(split.by) ){ res <- .local_variogram(pairs, lags, window, conf.level, a0) - res <- .format_variogram(res, at.time, conf.level) + res <- .format_variogram(res, time.point, conf.level) return(res) } lev <- levels(droplevels(pairs$level)) @@ -373,11 +375,11 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), }) est <- lapply(seq_along(lev), function(i){ cbind(level = lev[[i]], - .format_variogram(est[[i]], at.time, conf.level)) + .format_variogram(est[[i]], time.point, conf.level)) }) comp <- lapply(seq_along(comp), function(i){ lab <- paste(lev[[i + 1L]], "/", lev[[1L]]) - cbind(level = lab, .format_variogram(comp[[i]], at.time, conf.level)) + cbind(level = lab, .format_variogram(comp[[i]], time.point, conf.level)) }) res <- do.call(rbind, c(est, comp)) res <- res[order(res$lag), , drop = FALSE] @@ -389,12 +391,12 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), # The time at which D(L) is estimated: NA (no adjustment), the values given, # or the median midpoint of all pairs in each lag window -.get_at_time <- function(pairs, lags, at.time, window){ - if( is.null(at.time) ){ +.get_at_time <- function(pairs, lags, time.point, window){ + if( is.null(time.point) ){ return(rep(NA_real_, length(lags))) } - if( is.numeric(at.time) ){ - return(rep_len(as.numeric(at.time), length(lags))) + if( is.numeric(time.point) ){ + return(rep_len(as.numeric(time.point), length(lags))) } a0 <- vapply(lags, function(l){ in_window <- pairs$h >= l / window & pairs$h <= l * window @@ -427,7 +429,7 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), G <- length(ns) res <- data.frame( lag = l, estimate = NA_real_, se = NA_real_, df = NA_real_, - n.subjects = G, n.pairs = nrow(q), supported = FALSE, at.time = a0) + n.subjects = G, n.pairs = nrow(q), supported = FALSE, time.point = a0) # Interpolation only: pairs from at least three subjects on each side below <- length(unique(subj[q$h <= l])) above <- length(unique(subj[q$h >= l])) @@ -477,13 +479,13 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), lag = e1$lag, estimate = exp(lr), se = se, df = df, n.subjects = e1$n.subjects + e2$n.subjects, n.pairs = e1$n.pairs + e2$n.pairs, supported = ok, - at.time = e1$at.time, + time.point = e1$time.point, p.value = ifelse(ok, 2 * stats::pt(-abs(lr / se), df), NA_real_), type = "ratio") } # Confidence intervals on the log scale, and columns in a fixed order -.format_variogram <- function(res, at.time, conf.level){ +.format_variogram <- function(res, time.point, conf.level){ if( is.null(res$type) ){ res$type <- "dissimilarity" res$p.value <- NA_real_ @@ -493,8 +495,8 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), res$upper <- res$estimate * exp(q * res$se) cols <- c("lag", "type", "estimate", "lower", "upper", "se", "df", "p.value", "n.subjects", "n.pairs", "supported") - if( !is.null(at.time) ){ - cols <- c(cols, "at.time") + if( !is.null(time.point) ){ + cols <- c(cols, "time.point") } res <- res[, cols] return(res) diff --git a/man/getVariogram.Rd b/man/getVariogram.Rd index b0d29e5..adc1674 100644 --- a/man/getVariogram.Rd +++ b/man/getVariogram.Rd @@ -19,9 +19,9 @@ addVariogram(x, ...) group, assay.type = "counts", method = "bray", - lags = NULL, + time.lag = NULL, split.by = NULL, - at.time = NULL, + time.point = NULL, window = 2, squared = FALSE, conf.level = 0.95, @@ -53,7 +53,7 @@ used in the dissimilarity estimation. (Default: \code{"counts"})} Method is passed to the function that is specified by \code{dis.fun}. (Default: \code{"bray"})} -\item{lags}{\code{NULL} or \code{numeric vector}. The lags \eqn{L}, in +\item{time.lag}{\code{NULL} or \code{numeric vector}. The lags \eqn{L}, in the units of \code{time.col}, at which \eqn{D(L)} is estimated. If \code{NULL}, ten lags between the shortest and longest supported lag. (Default: \code{NULL})} @@ -63,7 +63,7 @@ of a column from \code{colData} with one value per subject. \eqn{D(L)} is estimated for each of its levels, and each level is compared with the first. (Default: \code{NULL})} -\item{at.time}{\code{NULL}, \code{numeric vector} or \code{"median"}. The +\item{time.point}{\code{NULL}, \code{numeric vector} or \code{"median"}. The time at which \eqn{D(L)} is estimated, for communities whose change depends on time since a common origin; one value, or one per lag. See details. (Default: \code{NULL})} @@ -94,8 +94,8 @@ with the confidence interval.} is 1.} \item{n.subjects, n.pairs}{Subjects and pairs in the lag window.} \item{supported}{Whether the design supports \eqn{D(L)} at this lag.} -\item{at.time}{The time at which \eqn{D(L)} was estimated, when -\code{at.time} is given.} +\item{time.point}{The time at which \eqn{D(L)} was estimated, when +\code{time.point} is given.} } \code{addVariogram} returns \code{x} with this table in its \code{metadata}. @@ -132,7 +132,7 @@ up to \eqn{L} and three at lags from \eqn{L}, so that \eqn{D(L)} is interpolated, not extrapolated. Elsewhere the estimate is \code{NA} and \code{supported} is \code{FALSE}. -When \code{lags = NULL}, ten lags are spread evenly on the log scale +When \code{time.lag = NULL}, ten lags are spread evenly on the log scale between the shortest and longest supported lag of the whole data: the smallest and largest lag reached by at least \eqn{\max(5, 20\%)} of the subjects. @@ -147,12 +147,12 @@ comparisons. \strong{Developing communities.} When change at a given lag depends on the time since a common origin (age in infant cohorts, time since an intervention), groups whose samples were taken at different ages differ -in \eqn{D(L)} even with the same development. \code{at.time} estimates +in \eqn{D(L)} even with the same development. \code{time.point} estimates \eqn{D(L)} at a stated time \eqn{a}: only pairs whose midpoint \eqn{m} satisfies \eqn{(1 + m) / (1 + a)} in \eqn{[1/2, 2]} are used, the regression adds \eqn{z = \log(1 + m) - \log(1 + a)} and \eqn{z^2}, and at least three subjects must have midpoints up to \eqn{a} and three from -\eqn{a}. With \code{at.time = "median"}, \eqn{a} is the median midpoint of +\eqn{a}. With \code{time.point = "median"}, \eqn{a} is the median midpoint of all pairs in the lag window, pooled over the levels of \code{split.by}, so that every group is evaluated at the same time. Time must then be measured from the common origin and be non-negative. @@ -181,7 +181,7 @@ res <- getVariogram( assay.type = "hellinger", method = "euclidean", squared = TRUE, - lags = c(1, 3, 6, 9) + time.lag = c(1, 3, 6, 9) ) res @@ -193,7 +193,7 @@ res <- getVariogram( assay.type = "hellinger", method = "euclidean", squared = TRUE, - lags = c(1, 3), + time.lag = c(1, 3), split.by = "sex" ) res[res$type == "ratio", ] diff --git a/tests/testthat/test-getVariogram.R b/tests/testthat/test-getVariogram.R index 520bbb1..028c339 100644 --- a/tests/testthat/test-getVariogram.R +++ b/tests/testthat/test-getVariogram.R @@ -8,18 +8,18 @@ test_that("getVariogram input checks", { expect_error(getVariogram(tse, time.col = "time", group = "subject", assay.type = "x")) expect_error(getVariogram(tse, time.col = "time", - group = "subject", lags = -1)) + group = "subject", time.lag = -1)) expect_error(getVariogram(tse, time.col = "time", - group = "subject", lags = 1, window = 1)) + group = "subject", time.lag = 1, window = 1)) expect_error(getVariogram(tse, time.col = "time", - group = "subject", lags = 1, at.time = "mean")) + group = "subject", time.lag = 1, time.point = "mean")) expect_error(getVariogram(tse, time.col = "time", - group = "subject", lags = c(1, 2), at.time = c(1, 2, 3))) + group = "subject", time.lag = c(1, 2), time.point = c(1, 2, 3))) expect_error(getVariogram(tse, time.col = "time", - group = "subject", lags = 1, conf.level = 1)) + group = "subject", time.lag = 1, conf.level = 1)) # split.by must be constant within subjects expect_error(getVariogram(tse, time.col = "time", - group = "subject", lags = 1, split.by = "time")) + group = "subject", time.lag = 1, split.by = "time")) }) # Pairs of n subjects with lags spread around 10 and d an exact quadratic in @@ -63,7 +63,7 @@ test_that("getVariogram output", { tse <- transformAssay(hitchip1006, method = "hellinger") res <- getVariogram(tse, time.col = "time", group = "subject", assay.type = "hellinger", method = "euclidean", squared = TRUE, - lags = c(1, 3, 6)) + time.lag = c(1, 3, 6)) expect_s4_class(res, "DataFrame") expect_equal(res$lag, c(1, 3, 6)) expect_true(all(res$type == "dissimilarity")) @@ -74,12 +74,12 @@ test_that("getVariogram output", { expect_true(all(is.na(res$estimate[!ok]))) # Squaring changes the dissimilarity res2 <- getVariogram(tse, time.col = "time", group = "subject", - assay.type = "hellinger", method = "euclidean", lags = c(1, 3, 6)) + assay.type = "hellinger", method = "euclidean", time.lag = c(1, 3, 6)) expect_false(isTRUE(all.equal(res$estimate[ok], res2$estimate[ok]))) # Wider intervals at a higher confidence level res3 <- getVariogram(tse, time.col = "time", group = "subject", assay.type = "hellinger", method = "euclidean", squared = TRUE, - lags = c(1, 3, 6), conf.level = 0.99) + time.lag = c(1, 3, 6), conf.level = 0.99) expect_equal(res3$estimate, res$estimate) expect_true(all(res3$upper[ok] > res$upper[ok])) # Default lags @@ -94,7 +94,7 @@ test_that("getVariogram compares groups", { tse <- transformAssay(hitchip1006, method = "hellinger") expect_message(res <- getVariogram(tse, time.col = "time", group = "subject", assay.type = "hellinger", method = "euclidean", - squared = TRUE, lags = c(3, 6), split.by = "sex")) + squared = TRUE, time.lag = c(3, 6), split.by = "sex")) expect_true("sex" %in% colnames(res)) expect_equal(nrow(res), 6L) est <- res[res$type == "dissimilarity", ] @@ -112,17 +112,17 @@ test_that("getVariogram compares groups", { # Comparison at a common time expect_message(res <- getVariogram(tse, time.col = "time", group = "subject", assay.type = "hellinger", method = "euclidean", - squared = TRUE, lags = c(3, 6), split.by = "sex", - at.time = "median")) - expect_true("at.time" %in% colnames(res)) - expect_equal(length(unique(res$at.time[res$lag == 6])), 1L) + squared = TRUE, time.lag = c(3, 6), split.by = "sex", + time.point = "median")) + expect_true("time.point" %in% colnames(res)) + expect_equal(length(unique(res$time.point[res$lag == 6])), 1L) }) test_that("addVariogram stores results in metadata", { data(hitchip1006, package = "miaTime") tse <- transformAssay(hitchip1006, method = "hellinger") args <- list(time.col = "time", group = "subject", - assay.type = "hellinger", method = "euclidean", lags = c(3, 6)) + assay.type = "hellinger", method = "euclidean", time.lag = c(3, 6)) res <- do.call(getVariogram, c(list(x = tse), args)) tse <- do.call(addVariogram, c(list(x = tse), args)) expect_equal(metadata(tse)[["variogram"]], res) From 8ae9747d39123071f71a0330617c0fd890edc174 Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Wed, 28 Oct 2026 19:18:14 +0200 Subject: [PATCH 5/8] Require twice as many subjects as coefficients in getVariogram The subjects' scores sum to zero, so with as many subjects as regression coefficients the sandwich variance is singular. D(L) is now reported only when the lag window holds at least 6 subjects, or 10 with time.point. --- R/getVariogram.R | 10 +++++++++- man/getVariogram.Rd | 5 ++++- tests/testthat/test-getVariogram.R | 9 +++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/R/getVariogram.R b/R/getVariogram.R index ee95b8f..3be2380 100644 --- a/R/getVariogram.R +++ b/R/getVariogram.R @@ -35,7 +35,10 @@ #' \eqn{\max(5, 20\%)} of the subjects with two or more samples must have #' pairs in the window, and at least three subjects must have pairs at lags #' up to \eqn{L} and three at lags from \eqn{L}, so that \eqn{D(L)} is -#' interpolated, not extrapolated. Elsewhere the estimate is \code{NA} and +#' interpolated, not extrapolated. The window must also contain at least +#' twice as many subjects as regression coefficients (6, or 10 with +#' \code{time.point}), because the sandwich variance is singular when there +#' are as many subjects as coefficients. Elsewhere the estimate is \code{NA} and #' \code{supported} is \code{FALSE}. #' #' When \code{time.lag = NULL}, ten lags are spread evenly on the log scale @@ -446,6 +449,11 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), z <- log1p(pmax(q$mid, 0)) - log1p(max(a0, 0)) X <- cbind(X, z, z^2) } + # The subjects' scores sum to zero, so the sandwich needs clearly more + # subjects than coefficients + if( G < 2L * ncol(X) ){ + return(res) + } # Each subject's pairs in the window count as one subject w <- as.numeric(1 / ns[subj]) A <- crossprod(X, X * w) diff --git a/man/getVariogram.Rd b/man/getVariogram.Rd index adc1674..519e985 100644 --- a/man/getVariogram.Rd +++ b/man/getVariogram.Rd @@ -129,7 +129,10 @@ number of subjects with pairs in the window. \eqn{\max(5, 20\%)} of the subjects with two or more samples must have pairs in the window, and at least three subjects must have pairs at lags up to \eqn{L} and three at lags from \eqn{L}, so that \eqn{D(L)} is -interpolated, not extrapolated. Elsewhere the estimate is \code{NA} and +interpolated, not extrapolated. The window must also contain at least +twice as many subjects as regression coefficients (6, or 10 with +\code{time.point}), because the sandwich variance is singular when there +are as many subjects as coefficients. Elsewhere the estimate is \code{NA} and \code{supported} is \code{FALSE}. When \code{time.lag = NULL}, ten lags are spread evenly on the log scale diff --git a/tests/testthat/test-getVariogram.R b/tests/testthat/test-getVariogram.R index 028c339..8e76d2f 100644 --- a/tests/testthat/test-getVariogram.R +++ b/tests/testthat/test-getVariogram.R @@ -50,6 +50,15 @@ test_that("D(L) is reported only at supported lags", { conf.level = 0.95, a0 = NA_real_) expect_false(res$supported) expect_true(is.na(res$estimate)) + # At least twice as many subjects as coefficients + pairs <- .make_quadratic_pairs(n = 5) + res <- miaTime:::.local_variogram(pairs, lags = 10, window = 2, + conf.level = 0.95, a0 = NA_real_) + expect_false(res$supported) + pairs <- .make_quadratic_pairs(n = 6) + res <- miaTime:::.local_variogram(pairs, lags = 10, window = 2, + conf.level = 0.95, a0 = NA_real_) + expect_true(res$supported) # No pairs above L: extrapolation is not reported pairs <- .make_quadratic_pairs() pairs <- pairs[pairs$h < 10, ] From 255c0273090d3f13fc0c8cc5453375deabe7dd60 Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Tue, 3 Nov 2026 07:36:17 +0200 Subject: [PATCH 6/8] Add getVariogram to the pkgdown index --- _pkgdown.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/_pkgdown.yml b/_pkgdown.yml index eaf38c5..aef0df8 100755 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -6,6 +6,10 @@ reference: - getBaselineDivergence - getStepwiseDivergence +- title: Variogram + contents: + - getVariogram + - title: Feature dynamics contents: - getShortTermChange From 430ba00941a26c1330af5ca377888272c79f52c4 Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Mon, 9 Nov 2026 09:31:52 +0200 Subject: [PATCH 7/8] Add getVariogram to NEWS and bump version --- DESCRIPTION | 2 +- NEWS | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) 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/NEWS b/NEWS index 4f4a267..92cbe6b 100755 --- a/NEWS +++ b/NEWS @@ -1,3 +1,6 @@ +Changes in version 1.3.6 (2026-11-09) ++ Added getVariogram + Changes in version 1.3.5 (2026-11-06) + getStepwiseDivergence: Option to select reference samples based on time lag From f807cfa79bef57e5ab745069d9d6740b6b494e56 Mon Sep 17 00:00:00 2001 From: Daena Rys Date: Tue, 10 Nov 2026 13:23:37 +0200 Subject: [PATCH 8/8] Add the getVariogram options from #136, #146, #147, #148, #155 and #157 --- R/getVariogram.R | 439 ++++++++++++++++++++++++++--- man/getVariogram.Rd | 92 +++++- tests/testthat/test-getVariogram.R | 180 +++++++++++- 3 files changed, 668 insertions(+), 43 deletions(-) diff --git a/R/getVariogram.R b/R/getVariogram.R index 3be2380..1d35865 100644 --- a/R/getVariogram.R +++ b/R/getVariogram.R @@ -53,6 +53,45 @@ #' at lags supported in both groups. P-values are not adjusted for multiple #' comparisons. #' +#' With \code{permutations > 0}, each comparison also gets a permutation +#' p-value: the levels of \code{split.by} are reassigned at random among +#' the subjects of the two levels compared, keeping their numbers, and the +#' t statistic of the log ratio is recomputed. When the levels share a +#' sampling schedule, subjects are exchangeable under the null hypothesis +#' and the permutation test is exact, whereas the t test can reject slightly +#' too often in real data. When the schedules differ, the labels are not +#' exchangeable and the permutation p-value is not valid; use the t test. +#' Set a seed (\code{set.seed()}) for reproducible permutation p-values. +#' +#' \strong{Kinds of pairs.} When \code{split.by} varies within subjects (a +#' sample-level state, such as community type or the phase of an +#' intervention), each pair takes the level of its earlier sample, and +#' \eqn{D(L)} is estimated for the pairs of each level. A subject then +#' contributes pairs to several levels, so the levels are not independent. +#' Each level is compared with the first in one weighted regression on the +#' pairs of both levels in the lag window, with an indicator of the level, +#' the terms in \eqn{u} for each level and, with \code{time.point}, the +#' terms in \eqn{z} shared by the levels; the log ratio of \eqn{D(L)} is +#' \eqn{\log((b_0 + b_1) / b_0)}, where \eqn{b_0} is the intercept and +#' \eqn{b_1} the coefficient of the indicator. Its standard error is +#' cluster-robust by subject, by the delta method, with \eqn{G - 1} degrees +#' of freedom. Both levels must meet the support rules on their own. The +#' permutation test is not available, as levels are not assigned to +#' subjects. +#' +#' With \code{pair.level = "highest"}, a pair takes the higher of the levels +#' of its two samples, in the order of the levels of \code{split.by}: with +#' levels \code{"baseline"} and \code{"exacerbation"}, pairs that span an +#' exacerbation are compared with pairs of two baseline samples. A sample +#' without a level (\code{NA}) classifies its pair only when the other +#' sample has the highest level, which decides the pair whatever the missing +#' level; other pairs with such a sample are left out. +#' +#' With \code{subset.by}, only pairs whose earlier sample is \code{TRUE} in +#' a logical column of \code{colData} are used, for example pairs starting +#' from a given community type. Subjects are then compared on those pairs, +#' and a sample-level state is compared within them. +#' #' \strong{Developing communities.} When change at a given lag depends on #' the time since a common origin (age in infant cohorts, time since an #' intervention), groups whose samples were taken at different ages differ @@ -76,6 +115,23 @@ #' first (\code{\link[mia:rarefyAssay]{rarefyAssay()}}) when depth differs #' between samples or groups. #' +#' Dissimilarities bounded by 1, such as Bray–Curtis and Jaccard, approach +#' their bound as communities share fewer features, so \eqn{D(L)} flattens +#' near 1 whatever the dynamics. With \code{bounded = TRUE} they are analysed +#' on the scale \eqn{-\log(1 - d)}, which is unbounded and close to \eqn{d} +#' for small dissimilarities. Pairs without shared features (\eqn{d = 1}) are +#' set to \eqn{d = 1 - 10^{-9}}. +#' +#' \strong{Relative change.} \eqn{D(L)} is on the scale of the +#' dissimilarity, so it cannot be compared between dissimilarities, studies +#' or body sites. With \code{relative = TRUE}, \eqn{D(L)} is also reported +#' relative to \eqn{B}, the mean dissimilarity between samples of different +#' subjects, where every pair of subjects counts equally: a value of 0.5 +#' means that over \eqn{L} a subject's community changes half as much as it +#' differs from another subject's. \eqn{B} is computed from the samples of +#' all subjects, so it is the same for every level of \code{split.by}, and +#' it is treated as fixed. +#' #' @references #' Diggle P.J. (1988) An approach to the analysis of repeated measurements. #' Biometrics 44, 959–971. doi: 10.2307/2531727 @@ -103,10 +159,14 @@ #' \item{df}{Degrees of freedom of the t distribution.} #' \item{p.value}{For comparisons, the p-value of the test that the ratio #' is 1.} +#' \item{p.value.permutation}{When \code{permutations > 0}: for +#' comparisons, the permutation p-value (see details).} #' \item{n.subjects, n.pairs}{Subjects and pairs in the lag window.} #' \item{supported}{Whether the design supports \eqn{D(L)} at this lag.} #' \item{time.point}{The time at which \eqn{D(L)} was estimated, when #' \code{time.point} is given.} +#' \item{relative}{When \code{relative = TRUE}: \eqn{D(L) / B}, for +#' estimates of \eqn{D(L)}.} #' } #' \code{addVariogram} returns \code{x} with this table in its #' \code{metadata}. @@ -123,9 +183,18 @@ #' (Default: \code{NULL}) #' #' @param split.by \code{NULL} or \code{Character scalar}. Specifies a name -#' of a column from \code{colData} with one value per subject. \eqn{D(L)} is -#' estimated for each of its levels, and each level is compared with the -#' first. (Default: \code{NULL}) +#' of a column from \code{colData}, with one value per subject or a +#' sample-level state. \eqn{D(L)} is estimated for each of its levels, and +#' each level is compared with the first. (Default: \code{NULL}) +#' +#' @param pair.level \code{Character scalar}. When \code{split.by} varies +#' within subjects, the level of a pair: \code{"earlier"}, that of its +#' earlier sample, or \code{"highest"}, the higher of the levels of its two +#' samples. See details. (Default: \code{"earlier"}) +#' +#' @param subset.by \code{NULL} or \code{Character scalar}. Specifies a name +#' of a logical column of \code{colData}; only pairs whose earlier sample is +#' \code{TRUE} are used. See details. (Default: \code{NULL}) #' #' @param time.point \code{NULL}, \code{numeric vector} or \code{"median"}. The #' time at which \eqn{D(L)} is estimated, for communities whose change @@ -138,9 +207,21 @@ #' @param squared \code{Logical scalar}. Whether the dissimilarities are #' squared. (Default: \code{FALSE}) #' +#' @param bounded \code{Logical scalar}. Whether the dissimilarities are +#' bounded by 1 and analysed on the scale \eqn{-\log(1 - d)}. See details. +#' (Default: \code{FALSE}) +#' +#' @param relative \code{Logical scalar}. Whether \eqn{D(L)} is also +#' reported relative to the dissimilarity between subjects. See details. +#' (Default: \code{FALSE}) +#' #' @param conf.level \code{Numeric scalar}. Confidence level of the #' intervals. (Default: \code{0.95}) #' +#' @param permutations \code{Integer scalar}. The number of permutations +#' of \code{split.by} among subjects for a permutation p-value of each +#' comparison; \code{0} for none. See details. (Default: \code{0}) +#' #' @param name \code{Character scalar}. Specifies a name for storing the #' results in \code{metadata}. (Default: \code{"variogram"}) #' @@ -218,10 +299,15 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), method = "bray", time.lag = NULL, split.by = NULL, + pair.level = "earlier", + subset.by = NULL, time.point = NULL, window = 2, squared = FALSE, + bounded = FALSE, + relative = FALSE, conf.level = 0.95, + permutations = 0, ...){ ############################# INPUT CHECK ############################## x <- .check_and_get_altExp(x, ...) @@ -241,6 +327,15 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), } temp <- .check_input( split.by, list(NULL, "character scalar"), colnames(colData(x))) + .check_split_by_name(split.by, .VARIOGRAM_COLUMNS) + temp <- .check_input( + pair.level, list("character scalar"), c("earlier", "highest")) + temp <- .check_input( + subset.by, list(NULL, "character scalar"), colnames(colData(x))) + if( !is.null(subset.by) && !is.logical(x[[subset.by]]) ){ + stop("'subset.by' must specify a logical column of colData(x).", + call. = FALSE) + } if( !(is.null(time.point) || identical(time.point, "median") || (is.numeric(time.point) && !anyNA(time.point))) ){ stop("'time.point' must be NULL, numeric or \"median\".", @@ -257,19 +352,42 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), stop("'window' must be greater than 1.", call. = FALSE) } temp <- .check_input(squared, list("logical scalar")) + temp <- .check_input(bounded, list("logical scalar")) + temp <- .check_input(relative, list("logical scalar")) temp <- .check_input(conf.level, list("numeric scalar")) if( conf.level <= 0 || conf.level >= 1 ){ stop("'conf.level' must be between 0 and 1.", call. = FALSE) } + temp <- .check_input(permutations, list("numeric scalar")) + if( permutations < 0 || permutations != round(permutations) ){ + stop("'permutations' must be a non-negative integer.", + call. = FALSE) + } ########################### INPUT CHECK END ############################ args <- list(...)[!names(list(...)) %in% c("altexp")] pairs <- .get_within_subject_pairs( - x, time.col, group, assay.type, method, split.by, squared, args) + x, time.col, group, assay.type, method, split.by, squared, + bounded, args, pair.level) + if( !is.null(subset.by) ){ + pairs <- .subset_pairs(pairs, x, time.col, subset.by) + } if( is.null(time.lag) ){ time.lag <- .default_lags(pairs) } + if( isTRUE(attr(pairs, "pair.level")) && permutations > 0 ){ + stop("'permutations' needs 'split.by' with one value per ", + "subject.", call. = FALSE) + } res <- .variogram( - pairs, time.lag, split.by, time.point, window, conf.level) + pairs, time.lag, split.by, time.point, window, conf.level, + permutations) + if( relative ){ + B <- .between_subject_level( + x, time.col, group, assay.type, method, split.by, squared, + bounded, args) + res$relative <- ifelse( + res$type == "dissimilarity", res$estimate / B, NA_real_) + } res <- DataFrame(res, check.names = FALSE) return(res) } @@ -277,14 +395,31 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), ################################ HELP FUNCTIONS ################################ +# Columns of the output; split.by becomes a column too, so it must not take +# one of these names +.VARIOGRAM_COLUMNS <- c( + "lag", "type", "estimate", "lower", "upper", "se", "df", "p.value", + "p.value.permutation", "n.subjects", "n.pairs", "supported", + "time.point", "relative") + +.check_split_by_name <- function(split.by, columns){ + if( !is.null(split.by) && split.by %in% columns ){ + stop("'split.by' must not be named '", split.by, "', the name of ", + "an output column; rename the column of colData.", call. = FALSE) + } +} + # All pairs of samples of the same subject, with their lag, midpoint time and # dissimilarity. .get_within_subject_pairs <- function( - x, time.col, group, assay.type, method, split.by, squared, args){ + x, time.col, group, assay.type, method, split.by, squared, bounded, + args, pair.level = "earlier"){ time <- x[[time.col]] subject <- x[[group]] keep <- !is.na(time) & !is.na(subject) - if( !is.null(split.by) ){ + # With pair.level = "highest", samples without a level can still + # classify their pairs + if( !is.null(split.by) && pair.level == "earlier" ){ keep <- keep & !is.na(x[[split.by]]) } if( any(!keep) ){ @@ -296,16 +431,20 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), time <- time[keep] subject <- subject[keep] } + samples <- which(keep) subject <- as.character(subject) level <- NULL if( !is.null(split.by) ){ level <- as.character(x[[split.by]]) - n_levels <- tapply(level, subject, function(v) length(unique(v))) - if( any(n_levels > 1L) ){ - stop("'split.by' must have one value per subject ('", group, - "').", call. = FALSE) + n_levels <- tapply(level, subject, function(v){ + length(unique(v[!is.na(v)])) + }) + pair_level <- any(n_levels > 1L) || pair.level == "highest" + if( pair_level && pair.level == "earlier" ){ + message("'split.by' varies within subjects: each pair takes ", + "the value of its earlier sample.") } - if( length(unique(level)) < 2L ){ + if( length(unique(level[!is.na(level)])) < 2L ){ stop("'split.by' must have at least two levels.", call. = FALSE) } # The first level is the reference of the comparisons @@ -326,16 +465,93 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), l <- idx[ut[, 2L]] data.frame( subject = subject[k], h = abs(time[l] - time[k]), - mid = (time[k] + time[l]) / 2, d = d[ut]) + mid = (time[k] + time[l]) / 2, d = d[ut], k = k, l = l) }) pairs <- do.call(rbind, unname(res)) + pairs$d <- .dissimilarity_scale(pairs$d, squared, bounded) + if( !is.null(split.by) ){ + if( pair.level == "earlier" ){ + first <- ifelse(time[pairs$k] <= time[pairs$l], pairs$k, pairs$l) + pairs$level <- level[first] + } else{ + pairs$level <- .highest_level(level[pairs$k], level[pairs$l]) + pairs <- pairs[!is.na(pairs$level), , drop = FALSE] + } + attr(pairs, "pair.level") <- pair_level + } + # Columns of the input that k and l index + attr(pairs, "samples") <- samples + return(pairs) +} + +# The higher of two levels in the order of the factor levels. A missing level +# decides nothing, unless the other sample has the highest level +.highest_level <- function(a, b){ + top <- nlevels(a) + ia <- as.integer(a) + ib <- as.integer(b) + h <- pmax(ia, ib) + h[is.na(ia) & ib %in% top] <- top + h[is.na(ib) & ia %in% top] <- top + res <- factor(levels(a)[h], levels = levels(a)) + return(res) +} + +# The pairs whose earlier sample is TRUE in the logical column subset.by +.subset_pairs <- function(pairs, x, time.col, subset.by){ + samples <- attr(pairs, "samples") + pair_level <- attr(pairs, "pair.level") + keep <- x[[subset.by]][samples] + time <- x[[time.col]][samples] + first <- ifelse(time[pairs$k] <= time[pairs$l], pairs$k, pairs$l) + pairs <- pairs[keep[first] %in% TRUE, , drop = FALSE] + if( nrow(pairs) == 0L ){ + stop("No pair starts from a sample with 'subset.by' TRUE.", + call. = FALSE) + } + attr(pairs, "samples") <- samples + attr(pairs, "pair.level") <- pair_level + return(pairs) +} + +# Squared, or on the scale -log(1 - d) for bounded dissimilarities +.dissimilarity_scale <- function(d, squared, bounded){ if( squared ){ - pairs$d <- pairs$d^2 + d <- d^2 + } + if( bounded ){ + if( any(d < 0 | d > 1, na.rm = TRUE) ){ + stop("'bounded = TRUE' needs dissimilarities between 0 and 1.", + call. = FALSE) + } + d <- -log1p(-pmin(d, 1 - 1e-9)) } + return(d) +} + +# Mean dissimilarity between samples of different subjects, every pair of +# subjects counting equally +.between_subject_level <- function( + x, time.col, group, assay.type, method, split.by, squared, bounded, + args){ + keep <- !is.na(x[[time.col]]) & !is.na(x[[group]]) if( !is.null(split.by) ){ - pairs$level <- level[match(pairs$subject, subject)] + keep <- keep & !is.na(x[[split.by]]) } - return(pairs) + x <- x[, keep] + subject <- as.character(x[[group]]) + if( length(unique(subject)) < 2L ){ + stop("'relative = TRUE' needs at least two subjects.", call. = FALSE) + } + d <- do.call(getDissimilarity, c( + list(x = t(assay(x, assay.type)), method = method), args)) + d <- .dissimilarity_scale(as.matrix(d), squared, bounded) + # Sums and numbers of sample pairs for every pair of subjects + sums <- rowsum(t(rowsum(d, subject)), subject) + n <- as.numeric(table(subject)[rownames(sums)]) + means <- sums / outer(n, n) + B <- mean(means[upper.tri(means)]) + return(B) } # The k-th smallest of the subjects' shortest lags and the k-th largest of @@ -361,7 +577,8 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), # D(L) for all lags, levels of split.by, and comparisons with the first level .variogram <- function( - pairs, lags, split.by, time.point, window, conf.level){ + pairs, lags, split.by, time.point, window, conf.level, + permutations = 0){ a0 <- .get_at_time(pairs, lags, time.point, window) if( is.null(split.by) ){ res <- .local_variogram(pairs, lags, window, conf.level, a0) @@ -373,9 +590,28 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), .local_variogram( pairs[pairs$level == g, ], lags, window, conf.level, a0) }) - comp <- lapply(est[-1L], function(e2){ - .compare_levels(est[[1L]], e2) - }) + if( isTRUE(attr(pairs, "pair.level")) ){ + comp <- lapply(seq_along(lev)[-1L], function(i){ + .compare_pair_levels( + pairs, lev[[1L]], lev[[i]], lags, window, a0, est[[1L]], + est[[i]]) + }) + } else{ + comp <- lapply(est[-1L], function(e2){ + .compare_levels(est[[1L]], e2) + }) + } + if( permutations > 0 ){ + for( i in seq_along(comp) ){ + comp[[i]]$p.value.permutation <- .permutation_p( + pairs, lev[[1L]], lev[[i + 1L]], lags, window, conf.level, + a0, comp[[i]], permutations) + } + est <- lapply(est, function(e){ + e$p.value.permutation <- NA_real_ + e + }) + } est <- lapply(seq_along(lev), function(i){ cbind(level = lev[[i]], .format_variogram(est[[i]], time.point, conf.level)) @@ -419,6 +655,34 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), } .local_variogram_at <- function(pairs, l, a0, k, window, conf.level){ + f <- .local_design(pairs, l, a0, k, window) + res <- data.frame( + lag = l, estimate = NA_real_, se = NA_real_, df = NA_real_, + n.subjects = f$G, n.pairs = length(f$rows), supported = FALSE, + time.point = a0) + if( !f$ok ){ + return(res) + } + G <- f$G + d <- pairs$d[f$rows] + b <- f$Ai %*% crossprod(f$X, f$w * d) + r <- d - drop(f$X %*% b) + U <- rowsum(f$X * (f$w * r), f$subj) + V <- f$Ai %*% crossprod(U) %*% f$Ai * G / (G - 1) + D <- b[[1L]] + if( !is.finite(D) || D <= 0 ){ + return(res) + } + res$estimate <- D + res$se <- sqrt(V[1L, 1L]) / D + res$df <- G - 1 + res$supported <- TRUE + return(res) +} + +# The pairs in the window of lag l (and time a0), the support rules, and the +# design of the local regression +.local_design <- function(pairs, l, a0, k, window){ rows <- which(pairs$h >= l / window & pairs$h <= l * window) if( !is.na(a0) ){ # Local in time too: midpoints within a factor of two of the target @@ -430,9 +694,7 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), subj <- q$subject ns <- table(subj) G <- length(ns) - res <- data.frame( - lag = l, estimate = NA_real_, se = NA_real_, df = NA_real_, - n.subjects = G, n.pairs = nrow(q), supported = FALSE, time.point = a0) + res <- list(ok = FALSE, rows = rows, G = G) # Interpolation only: pairs from at least three subjects on each side below <- length(unique(subj[q$h <= l])) above <- length(unique(subj[q$h >= l])) @@ -460,19 +722,9 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), if( qr(A)$rank < ncol(X) ){ return(res) } - Ai <- solve(A) - b <- Ai %*% crossprod(X, w * q$d) - r <- q$d - drop(X %*% b) - U <- rowsum(X * (w * r), subj) - V <- Ai %*% crossprod(U) %*% Ai * G / (G - 1) - D <- b[[1L]] - if( !is.finite(D) || D <= 0 ){ - return(res) - } - res$estimate <- D - res$se <- sqrt(V[1L, 1L]) / D - res$df <- G - 1 - res$supported <- TRUE + res <- list( + ok = TRUE, rows = rows, G = G, X = X, w = w, subj = subj, + Ai = solve(A)) return(res) } @@ -492,6 +744,118 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), type = "ratio") } +# Ratio of D(L) between two levels of a sample-level state: one regression on +# the pairs of both levels, with an indicator of the second level, lag terms +# for each level and time terms shared by the levels. The log ratio is +# log((b0 + b1) / b0), with a cluster-robust (CR1) standard error by the +# delta method. +.compare_pair_levels <- function(pairs, lev1, lev2, lags, window, a0, e1, e2){ + p <- pairs[pairs$level %in% c(lev1, lev2), , drop = FALSE] + res <- lapply(seq_along(lags), function(i){ + l <- lags[[i]] + out <- data.frame( + lag = l, estimate = NA_real_, se = NA_real_, df = NA_real_, + n.subjects = NA_integer_, n.pairs = NA_integer_, + supported = FALSE, time.point = a0[[i]], p.value = NA_real_, + type = "ratio") + f <- .pair_level_design(p, lev2, l, a0[[i]], window) + G <- f$G + out$n.subjects <- G + out$n.pairs <- length(f$rows) + # Each level must be supported on its own + if( !e1$supported[[i]] || !e2$supported[[i]] || !f$ok ){ + return(out) + } + d <- p$d[f$rows] + b <- drop(f$Ai %*% crossprod(f$X, f$w * d)) + if( b[[1L]] <= 0 || b[[1L]] + b[[2L]] <= 0 ){ + return(out) + } + r <- d - drop(f$X %*% b) + U <- rowsum(f$X * (f$w * r), f$subj) + V <- f$Ai %*% crossprod(U) %*% f$Ai * G / (G - 1) + lr <- log(b[[1L]] + b[[2L]]) - log(b[[1L]]) + grad <- c(1 / (b[[1L]] + b[[2L]]) - 1 / b[[1L]], + 1 / (b[[1L]] + b[[2L]]), rep(0, ncol(f$X) - 2L)) + se <- sqrt(drop(t(grad) %*% V %*% grad)) + out$estimate <- exp(lr) + out$se <- se + out$df <- G - 1 + out$supported <- TRUE + out$p.value <- 2 * stats::pt(-abs(lr / se), G - 1) + return(out) + }) + res <- do.call(rbind, res) + return(res) +} + +# Design of the regression on the pairs of two levels of a sample-level state +# in the window of lag l (and time a0); the second coefficient is that of the +# indicator of lev2 +.pair_level_design <- function(p, lev2, l, a0, window){ + rows <- which(p$h >= l / window & p$h <= l * window) + if( !is.na(a0) ){ + r <- (1 + pmax(p$mid[rows], 0)) / (1 + max(a0, 0)) + rows <- rows[r >= 1 / 2 & r <= 2] + } + q <- p[rows, , drop = FALSE] + subj <- q$subject + ns <- table(subj) + G <- length(ns) + res <- list(ok = FALSE, rows = rows, G = G) + g <- as.numeric(q$level == lev2) + u <- log(q$h / l) + X <- cbind(1, g, u, u^2, g * u, g * u^2) + if( !is.na(a0) ){ + z <- log1p(pmax(q$mid, 0)) - log1p(max(a0, 0)) + X <- cbind(X, z, z^2) + } + if( G < 2L * ncol(X) ){ + return(res) + } + w <- as.numeric(1 / ns[subj]) + A <- crossprod(X, X * w) + if( qr(A)$rank < ncol(X) ){ + return(res) + } + res <- list( + ok = TRUE, rows = rows, G = G, X = X, w = w, subj = subj, + Ai = solve(A)) + return(res) +} + +# Permutation p-value of each lag's comparison between two levels: the +# levels are reassigned among the subjects of the two levels, keeping their +# numbers, and the t statistic of the log ratio is recomputed +.permutation_p <- function( + pairs, lev1, lev2, lags, window, conf.level, a0, obs, + permutations){ + p <- pairs[pairs$level %in% c(lev1, lev2), , drop = FALSE] + subj <- unique(data.frame( + subject = p$subject, level = as.character(p$level))) + t_obs <- log(obs$estimate) / obs$se + t_perm <- vapply(seq_len(permutations), function(b){ + lab <- stats::setNames(sample(subj$level), subj$subject) + pl <- lab[p$subject] + e1 <- .local_variogram( + p[pl == lev1, , drop = FALSE], lags, window, conf.level, a0) + e2 <- .local_variogram( + p[pl == lev2, , drop = FALSE], lags, window, conf.level, a0) + cmp <- .compare_levels(e1, e2) + ifelse(cmp$supported, log(cmp$estimate) / cmp$se, NA_real_) + }, numeric(length(lags))) + t_perm <- matrix(t_perm, nrow = length(lags)) + res <- vapply(seq_along(lags), function(i){ + v <- t_perm[i, ] + v <- v[!is.na(v)] + if( !obs$supported[[i]] || length(v) == 0L ){ + return(NA_real_) + } + (1 + sum(abs(v) >= abs(t_obs[[i]]))) / (1 + length(v)) + }, numeric(1L)) + return(res) +} + # Confidence intervals on the log scale, and columns in a fixed order .format_variogram <- function(res, time.point, conf.level){ if( is.null(res$type) ){ @@ -502,7 +866,8 @@ setMethod("getVariogram", signature = c(x = "SummarizedExperiment"), res$lower <- res$estimate * exp(-q * res$se) res$upper <- res$estimate * exp(q * res$se) cols <- c("lag", "type", "estimate", "lower", "upper", "se", "df", - "p.value", "n.subjects", "n.pairs", "supported") + "p.value", intersect("p.value.permutation", names(res)), + "n.subjects", "n.pairs", "supported") if( !is.null(time.point) ){ cols <- c(cols, "time.point") } diff --git a/man/getVariogram.Rd b/man/getVariogram.Rd index 519e985..af8fc2f 100644 --- a/man/getVariogram.Rd +++ b/man/getVariogram.Rd @@ -21,10 +21,15 @@ addVariogram(x, ...) method = "bray", time.lag = NULL, split.by = NULL, + pair.level = "earlier", + subset.by = NULL, time.point = NULL, window = 2, squared = FALSE, + bounded = FALSE, + relative = FALSE, conf.level = 0.95, + permutations = 0, ... ) } @@ -59,9 +64,18 @@ the units of \code{time.col}, at which \eqn{D(L)} is estimated. If (Default: \code{NULL})} \item{split.by}{\code{NULL} or \code{Character scalar}. Specifies a name -of a column from \code{colData} with one value per subject. \eqn{D(L)} is -estimated for each of its levels, and each level is compared with the -first. (Default: \code{NULL})} +of a column from \code{colData}, with one value per subject or a +sample-level state. \eqn{D(L)} is estimated for each of its levels, and +each level is compared with the first. (Default: \code{NULL})} + +\item{pair.level}{\code{Character scalar}. When \code{split.by} varies +within subjects, the level of a pair: \code{"earlier"}, that of its +earlier sample, or \code{"highest"}, the higher of the levels of its two +samples. See details. (Default: \code{"earlier"})} + +\item{subset.by}{\code{NULL} or \code{Character scalar}. Specifies a name +of a logical column of \code{colData}; only pairs whose earlier sample is +\code{TRUE} are used. See details. (Default: \code{NULL})} \item{time.point}{\code{NULL}, \code{numeric vector} or \code{"median"}. The time at which \eqn{D(L)} is estimated, for communities whose change @@ -74,8 +88,20 @@ details. (Default: \code{NULL})} \item{squared}{\code{Logical scalar}. Whether the dissimilarities are squared. (Default: \code{FALSE})} +\item{bounded}{\code{Logical scalar}. Whether the dissimilarities are +bounded by 1 and analysed on the scale \eqn{-\log(1 - d)}. See details. +(Default: \code{FALSE})} + +\item{relative}{\code{Logical scalar}. Whether \eqn{D(L)} is also +reported relative to the dissimilarity between subjects. See details. +(Default: \code{FALSE})} + \item{conf.level}{\code{Numeric scalar}. Confidence level of the intervals. (Default: \code{0.95})} + +\item{permutations}{\code{Integer scalar}. The number of permutations +of \code{split.by} among subjects for a permutation p-value of each +comparison; \code{0} for none. See details. (Default: \code{0})} } \value{ \code{getVariogram} returns a \code{DataFrame} with one row per @@ -92,10 +118,14 @@ with the confidence interval.} \item{df}{Degrees of freedom of the t distribution.} \item{p.value}{For comparisons, the p-value of the test that the ratio is 1.} +\item{p.value.permutation}{When \code{permutations > 0}: for +comparisons, the permutation p-value (see details).} \item{n.subjects, n.pairs}{Subjects and pairs in the lag window.} \item{supported}{Whether the design supports \eqn{D(L)} at this lag.} \item{time.point}{The time at which \eqn{D(L)} was estimated, when \code{time.point} is given.} +\item{relative}{When \code{relative = TRUE}: \eqn{D(L) / B}, for +estimates of \eqn{D(L)}.} } \code{addVariogram} returns \code{x} with this table in its \code{metadata}. @@ -147,6 +177,45 @@ Welch–Satterthwaite t test of the log ratio. The comparison is made only at lags supported in both groups. P-values are not adjusted for multiple comparisons. +With \code{permutations > 0}, each comparison also gets a permutation +p-value: the levels of \code{split.by} are reassigned at random among +the subjects of the two levels compared, keeping their numbers, and the +t statistic of the log ratio is recomputed. When the levels share a +sampling schedule, subjects are exchangeable under the null hypothesis +and the permutation test is exact, whereas the t test can reject slightly +too often in real data. When the schedules differ, the labels are not +exchangeable and the permutation p-value is not valid; use the t test. +Set a seed (\code{set.seed()}) for reproducible permutation p-values. + +\strong{Kinds of pairs.} When \code{split.by} varies within subjects (a +sample-level state, such as community type or the phase of an +intervention), each pair takes the level of its earlier sample, and +\eqn{D(L)} is estimated for the pairs of each level. A subject then +contributes pairs to several levels, so the levels are not independent. +Each level is compared with the first in one weighted regression on the +pairs of both levels in the lag window, with an indicator of the level, +the terms in \eqn{u} for each level and, with \code{time.point}, the +terms in \eqn{z} shared by the levels; the log ratio of \eqn{D(L)} is +\eqn{\log((b_0 + b_1) / b_0)}, where \eqn{b_0} is the intercept and +\eqn{b_1} the coefficient of the indicator. Its standard error is +cluster-robust by subject, by the delta method, with \eqn{G - 1} degrees +of freedom. Both levels must meet the support rules on their own. The +permutation test is not available, as levels are not assigned to +subjects. + +With \code{pair.level = "highest"}, a pair takes the higher of the levels +of its two samples, in the order of the levels of \code{split.by}: with +levels \code{"baseline"} and \code{"exacerbation"}, pairs that span an +exacerbation are compared with pairs of two baseline samples. A sample +without a level (\code{NA}) classifies its pair only when the other +sample has the highest level, which decides the pair whatever the missing +level; other pairs with such a sample are left out. + +With \code{subset.by}, only pairs whose earlier sample is \code{TRUE} in +a logical column of \code{colData} are used, for example pairs starting +from a given community type. Subjects are then compared on those pairs, +and a sample-level state is compared within them. + \strong{Developing communities.} When change at a given lag depends on the time since a common origin (age in infant cohorts, time since an intervention), groups whose samples were taken at different ages differ @@ -169,6 +238,23 @@ additively, so the noise does not change the shape of the variogram, only its level. Dissimilarities depend on sequencing depth; rarefy the counts first (\code{\link[mia:rarefyAssay]{rarefyAssay()}}) when depth differs between samples or groups. + +Dissimilarities bounded by 1, such as Bray–Curtis and Jaccard, approach +their bound as communities share fewer features, so \eqn{D(L)} flattens +near 1 whatever the dynamics. With \code{bounded = TRUE} they are analysed +on the scale \eqn{-\log(1 - d)}, which is unbounded and close to \eqn{d} +for small dissimilarities. Pairs without shared features (\eqn{d = 1}) are +set to \eqn{d = 1 - 10^{-9}}. + +\strong{Relative change.} \eqn{D(L)} is on the scale of the +dissimilarity, so it cannot be compared between dissimilarities, studies +or body sites. With \code{relative = TRUE}, \eqn{D(L)} is also reported +relative to \eqn{B}, the mean dissimilarity between samples of different +subjects, where every pair of subjects counts equally: a value of 0.5 +means that over \eqn{L} a subject's community changes half as much as it +differs from another subject's. \eqn{B} is computed from the samples of +all subjects, so it is the same for every level of \code{split.by}, and +it is treated as fixed. } \examples{ library(miaTime) diff --git a/tests/testthat/test-getVariogram.R b/tests/testthat/test-getVariogram.R index 8e76d2f..0a83c82 100644 --- a/tests/testthat/test-getVariogram.R +++ b/tests/testthat/test-getVariogram.R @@ -17,9 +17,6 @@ test_that("getVariogram input checks", { group = "subject", time.lag = c(1, 2), time.point = c(1, 2, 3))) expect_error(getVariogram(tse, time.col = "time", group = "subject", time.lag = 1, conf.level = 1)) - # split.by must be constant within subjects - expect_error(getVariogram(tse, time.col = "time", - group = "subject", time.lag = 1, split.by = "time")) }) # Pairs of n subjects with lags spread around 10 and d an exact quadratic in @@ -139,3 +136,180 @@ test_that("addVariogram stores results in metadata", { c(list(x = tse, name = "vario"), args)) expect_equal(metadata(tse)[["vario"]], res) }) + +test_that("Permutation p-values of comparisons", { + data(hitchip1006, package = "miaTime") + tse <- transformAssay(hitchip1006, method = "hellinger") + args <- list(tse, time.col = "time", group = "subject", + assay.type = "hellinger", method = "euclidean", squared = TRUE, + time.lag = c(1, 3), split.by = "sex") + expect_error(do.call(getVariogram, c(args, permutations = -1))) + expect_error(do.call(getVariogram, c(args, permutations = 1.5))) + # No permutation column by default + res <- do.call(getVariogram, args) + expect_false("p.value.permutation" %in% colnames(res)) + set.seed(1) + res <- do.call(getVariogram, c(args, permutations = 19)) + expect_true("p.value.permutation" %in% colnames(res)) + # Only comparisons get a permutation p-value + expect_true(all(is.na( + res$p.value.permutation[res$type == "dissimilarity"]))) + p <- res$p.value.permutation[res$type == "ratio" & res$supported] + expect_true(length(p) > 0L) + expect_true(all(p >= 1 / 20 & p <= 1)) + # The estimates do not change + res0 <- do.call(getVariogram, args) + expect_equal(res$estimate, res0$estimate) + expect_equal(res$p.value, res0$p.value) + # Reproducible with a seed + set.seed(1) + res2 <- do.call(getVariogram, c(args, permutations = 19)) + expect_equal(res$p.value.permutation, res2$p.value.permutation) +}) + +test_that("Bounded dissimilarities are analysed on the -log(1 - d) scale", { + data(hitchip1006, package = "miaTime") + tse <- transformAssay(hitchip1006, method = "relabundance") + args <- list(tse, time.col = "time", group = "subject", + assay.type = "relabundance", method = "bray", time.lag = c(1, 3)) + pairs <- miaTime:::.get_within_subject_pairs(tse, "time", "subject", + "relabundance", "bray", NULL, FALSE, FALSE, list()) + pairs$d <- -log(1 - pairs$d) + ref <- miaTime:::.local_variogram(pairs, c(1, 3), 2, 0.95, c(NA, NA)) + res <- do.call(getVariogram, c(args, bounded = TRUE)) + expect_equal(res$estimate, ref$estimate) + expect_true(any(res$supported)) + expect_true(all(res$estimate > do.call(getVariogram, args)$estimate, + na.rm = TRUE)) + # Dissimilarities above 1 are not bounded + expect_error(getVariogram(tse, time.col = "time", group = "subject", + assay.type = "counts", method = "euclidean", time.lag = 1, + bounded = TRUE)) + expect_error(do.call(getVariogram, c(args, bounded = NA))) +}) + +test_that("Relative change divides D(L) by the dissimilarity between subjects", { + data(hitchip1006, package = "miaTime") + tse <- transformAssay(hitchip1006, method = "relabundance") + # Subjects with two or more samples, and ten with one + n <- table(tse$subject) + tse <- tse[, tse$subject %in% c(names(n)[n > 1], names(n)[n == 1][1:10])] + args <- list(tse, time.col = "time", group = "subject", + assay.type = "relabundance", method = "bray", time.lag = c(1, 3), + split.by = "sex") + res <- do.call(getVariogram, c(args, relative = TRUE)) + # Every pair of subjects counts equally + d <- as.matrix(getDissimilarity(t(assay(tse, "relabundance")), + method = "bray")) + s <- tse$subject + sp <- combn(unique(s), 2) + B <- mean(apply(sp, 2, function(p) mean(d[s == p[1], s == p[2]]))) + est <- res$type == "dissimilarity" + expect_equal(res$relative[est], res$estimate[est] / B) + expect_true(all(is.na(res$relative[!est]))) + expect_false("relative" %in% names(do.call(getVariogram, args))) + # On the same scale as D(L) + res <- do.call(getVariogram, c(args, relative = TRUE, bounded = TRUE)) + B <- mean(apply(sp, 2, function(p) + mean(-log(1 - d[s == p[1], s == p[2]])))) + expect_equal(res$relative[est], res$estimate[est] / B) +}) + +test_that("Pairs are classified by a sample-level state", { + # Every subject has pairs of both kinds; D(L) is exactly linear in + # log(h / 10), twice as high for pairs starting in state b + h <- rep(c(6, 8, 10, 12, 15), 2) + u <- log(h / 10) + pairs <- data.frame( + subject = rep(paste0("s", 1:12), each = 10), + h = rep(h, 12), mid = 10, + level = factor(rep(rep(c("a", "b"), each = 5), 12))) + pairs$d <- ifelse(pairs$level == "a", 0.3 + 0.1 * u, 0.6 + 0.05 * u) + e <- lapply(c("a", "b"), function(g) miaTime:::.local_variogram( + pairs[pairs$level == g, ], 10, 2, 0.95, NA_real_)) + res <- miaTime:::.compare_pair_levels(pairs, "a", "b", 10, 2, NA_real_, + e[[1]], e[[2]]) + expect_equal(res$estimate, 2) + expect_equal(res$se, 0, tolerance = 1e-8) + expect_equal(res$n.subjects, 12L) + expect_equal(res$df, 11) + + data(hitchip1006, package = "miaTime") + tse <- transformAssay(hitchip1006, method = "hellinger") + tse$state <- ifelse(tse$time < 2, "early", "late") + args <- list(tse, time.col = "time", group = "subject", + assay.type = "hellinger", method = "euclidean", squared = TRUE, + time.lag = c(1, 3), split.by = "state") + expect_message(res <- do.call(getVariogram, args), "earlier sample") + expect_identical(unique(res$state), + c("early", "late", "late / early")) + # Each pair takes the state of its earlier sample + pairs <- miaTime:::.get_within_subject_pairs(tse, "time", "subject", + "hellinger", "euclidean", "state", TRUE, FALSE, list()) + expect_true(attr(pairs, "pair.level")) + expect_true(all(pairs$level[pairs$mid - pairs$h / 2 >= 2] == "late")) + expect_true(all(pairs$level[pairs$mid - pairs$h / 2 < 2] == "early")) + expect_error(do.call(getVariogram, c(args, permutations = 9))) + # split.by must not take the name of an output column + tse$type <- tse$state + args[[1]] <- tse + args$split.by <- "type" + expect_error(do.call(getVariogram, args), "output column") +}) + +test_that("Pairs are restricted to those from samples with subset.by TRUE", { + data(hitchip1006, package = "miaTime") + tse <- transformAssay(hitchip1006, method = "hellinger") + tse$early <- tse$time < 3 + args <- list(tse, time.col = "time", group = "subject", + assay.type = "hellinger", method = "euclidean", squared = TRUE, + time.lag = c(1, 3)) + res <- do.call(getVariogram, c(args, subset.by = "early")) + # The same as the local estimate on the pairs from early samples + pairs <- miaTime:::.get_within_subject_pairs(tse, "time", "subject", + "hellinger", "euclidean", NULL, TRUE, FALSE, list()) + first <- pmin(pairs$mid - pairs$h / 2) + ref <- miaTime:::.local_variogram(pairs[first < 3, ], c(1, 3), 2, 0.95, + c(NA, NA)) + expect_equal(res$estimate, ref$estimate) + expect_equal(res$n.pairs, ref$n.pairs) + expect_error(do.call(getVariogram, c(args, subset.by = "time")), + "logical") + tse$none <- FALSE + args[[1]] <- tse + expect_error(do.call(getVariogram, c(args, subset.by = "none"))) +}) + +test_that("Pairs take the highest level of their two samples", { + lev <- c("baseline", "exacerbation") + a <- factor(c("baseline", "baseline", "exacerbation", NA, NA, NA), + levels = lev) + b <- factor(c("baseline", "exacerbation", "baseline", "exacerbation", + "baseline", NA), levels = lev) + expect_identical(as.character(miaTime:::.highest_level(a, b)), + c("baseline", "exacerbation", "exacerbation", "exacerbation", NA, NA)) + # Every pair with an exacerbation sample, against pairs of two baseline + # samples; samples of other states are kept for their pairs + set.seed(1) + n <- 160 + mat <- matrix(runif(5 * n), 5, dimnames = list(paste0("f", 1:5), NULL)) + tse <- SummarizedExperiment(assays = list(x = mat), + colData = DataFrame(subject = rep(1:20, each = 8), + time = rep(0:7, 20) + runif(n, 0, 0.5), + state = factor(sample(c("baseline", "exacerbation", NA), n, + replace = TRUE, prob = c(0.5, 0.3, 0.2)), levels = lev))) + args <- list(tse, time.col = "time", group = "subject", assay.type = "x", + method = "euclidean", squared = TRUE, time.lag = 2, + split.by = "state") + res <- do.call(getVariogram, c(args, pair.level = "highest")) + pairs <- miaTime:::.get_within_subject_pairs(tse, "time", "subject", "x", + "euclidean", "state", TRUE, FALSE, list(), "highest") + st <- tse$state + expect_true(all(pairs$level[st[pairs$k] %in% "exacerbation" | + st[pairs$l] %in% "exacerbation"] == "exacerbation")) + expect_true(all(pairs$level == "baseline" | st[pairs$k] %in% + "exacerbation" | st[pairs$l] %in% "exacerbation")) + expect_identical(unique(res$state), c("baseline", "exacerbation", + "exacerbation / baseline")) + expect_error(do.call(getVariogram, c(args, pair.level = "later"))) +})