diff --git a/R/getVariogramModel.R b/R/getVariogramModel.R index 679d1df..674f580 100644 --- a/R/getVariogramModel.R +++ b/R/getVariogramModel.R @@ -77,6 +77,17 @@ #' \code{\link[miaTime:getVariogram]{getVariogram()}}, so that the levels #' are compared around the same time \eqn{a}. #' +#' \strong{Temporal structure.} Without temporal structure, dissimilarity +#' does not depend on the lag, the timescale is not identified and tests on +#' it are meaningless. With \code{permutations > 0}, a row +#' \code{"temporal.structure"} tests whether dissimilarity depends on the +#' lag at all: its estimate is the subject-weighted mean dissimilarity of +#' pairs in the upper quartile of the lags minus that of pairs in the lower +#' quartile, and its p-value compares it with the same statistic after the +#' sampling times are permuted within each subject, which leaves the +#' dissimilarities unchanged. It uses the pairs at all lags, and is computed +#' for each level of \code{split.by}. +#' #' The dissimilarities are those of #' \code{\link[miaTime:getVariogram]{getVariogram()}}; see its details for #' the choice of dissimilarity and for bounded dissimilarities. @@ -94,8 +105,8 @@ #' \describe{ #' \item{\code{split.by}}{When \code{split.by} is given: the level, or the #' comparison (\code{"B / A"}).} -#' \item{type}{\code{"parameter"}, or \code{"ratio"} for comparisons -#' between levels.} +#' \item{type}{\code{"parameter"}, \code{"ratio"} for comparisons +#' between levels, or \code{"test"}.} #' \item{form}{The fitted form.} #' \item{parameter}{\code{"nugget"}, \code{"partial.sill"}, #' \code{"sill"} and \code{"timescale"} (with suffixes \code{.1} and @@ -133,6 +144,10 @@ #' which pairs are fitted, for communities whose change depends on time since #' a common origin. See details. (Default: \code{NULL}) #' +#' @param permutations \code{Integer scalar}. The number of permutations of +#' the sampling times within subjects for the test of temporal structure; +#' \code{0} for none. See details. (Default: \code{0}) +#' #' @param bootstrap \code{Integer scalar}. The number of resamples of #' subjects within each level of \code{split.by}. (Default: \code{999}) #' @@ -228,6 +243,7 @@ setMethod("getVariogramModel", signature = c(x = "SummarizedExperiment"), squared = FALSE, bounded = FALSE, conf.level = 0.95, + permutations = 0, bootstrap = 999, BPPARAM = BiocParallel::SerialParam(), ...){ @@ -256,6 +272,11 @@ setMethod("getVariogramModel", signature = c(x = "SummarizedExperiment"), 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) + } temp <- .check_input(bootstrap, list("numeric scalar")) if( bootstrap < 1 || bootstrap != round(bootstrap) ){ stop("'bootstrap' must be a positive integer.", call. = FALSE) @@ -272,10 +293,12 @@ setMethod("getVariogramModel", signature = c(x = "SummarizedExperiment"), if( isTRUE(attr(pairs, "pair.level")) ){ stop("'split.by' must have one value per subject.", call. = FALSE) } + time <- x[[time.col]][attr(pairs, "samples")] if( !is.null(time.point) ){ r <- (1 + pmax(pairs$mid, 0)) / (1 + max(time.point, 0)) pairs <- pairs[r >= 1 / 2 & r <= 2, , drop = FALSE] } + all_pairs <- pairs form <- unique(form) if( is.null(split.by) ){ pairs <- pairs[pairs$h <= .max_lag(pairs), , drop = FALSE] @@ -294,6 +317,12 @@ setMethod("getVariogramModel", signature = c(x = "SummarizedExperiment"), res <- .compare_variogram_models( pairs, form, conf.level, bootstrap, BPPARAM) cv <- attr(res, "cv") + } + if( permutations > 0 ){ + res <- .add_temporal_structure( + res, all_pairs, time, permutations, split.by) + } + if( !is.null(split.by) ){ names(res)[names(res) == "level"] <- split.by } if( !is.null(time.point) ){ @@ -641,6 +670,63 @@ setMethod("getVariogramModel", signature = c(x = "SummarizedExperiment"), return(res) } +# Rows of the test for temporal structure, for all pairs or each level +.add_temporal_structure <- function(res, pairs, time, permutations, split.by){ + lev <- if( is.null(split.by) ) list(NULL) else + levels(droplevels(pairs$level)) + rows <- lapply(lev, function(g){ + p <- if( is.null(g) ) pairs else pairs[pairs$level == g, ] + tt <- .temporal_structure(p, time, permutations) + out <- data.frame( + type = "test", form = res$form[[1L]], + parameter = "temporal.structure", estimate = tt$statistic, + lower = NA_real_, upper = NA_real_, se = NA_real_, df = NA_real_, + p.value = tt$p.value, identified = NA, + n.subjects = length(unique(p$subject)), n.pairs = nrow(p), + min.lag = min(p$h[p$h > 0]), max.lag = max(p$h)) + if( !is.null(g) ){ + out <- cbind(level = g, out) + } + out + }) + res <- rbind(res, do.call(rbind, rows)) + rownames(res) <- NULL + return(res) +} + +# Permutation test of whether dissimilarity depends on the lag: the +# subject-weighted mean dissimilarity of pairs in the upper quartile of the +# lags minus that in the lower quartile, against the same statistic with +# the sampling times permuted within subjects +.temporal_structure <- function(pairs, time, permutations){ + p <- pairs[pairs$h > 0, , drop = FALSE] + q <- stats::quantile(p$h, c(0.25, 0.75)) + stat <- function(h){ + lo <- h <= q[[1L]] + hi <- h >= q[[2L]] + if( !any(lo) || !any(hi) ){ + return(NA_real_) + } + wl <- as.numeric(1 / table(p$subject[lo])[p$subject[lo]]) + wh <- as.numeric(1 / table(p$subject[hi])[p$subject[hi]]) + stats::weighted.mean(p$d[hi], wh) - stats::weighted.mean(p$d[lo], wl) + } + obs <- stat(p$h) + # The samples of the pairs, ordered by subject + id <- c(p$k, p$l) + keep <- !duplicated(id) + id <- id[keep] + subj <- c(p$subject, p$subject)[keep] + sorted <- id[order(subj)] + perm <- vapply(seq_len(permutations), function(b){ + tp <- time + tp[sorted] <- time[id[order(subj, stats::runif(length(id)))]] + stat(abs(tp[p$l] - tp[p$k])) + }, numeric(1L)) + p_value <- (1 + sum(perm >= obs, na.rm = TRUE)) / (1 + sum(!is.na(perm))) + return(list(statistic = obs, p.value = p_value)) +} + # Ten-fold cross-validation over subjects. Single pairs are too noisy to # separate forms, so the held-out subjects' variogram is binned at quantiles # of the lags and compared with the fitted variogram by the mean squared diff --git a/man/getVariogramModel.Rd b/man/getVariogramModel.Rd index 7cc47c8..f848cce 100644 --- a/man/getVariogramModel.Rd +++ b/man/getVariogramModel.Rd @@ -25,6 +25,7 @@ addVariogramModel(x, ...) squared = FALSE, bounded = FALSE, conf.level = 0.95, + permutations = 0, bootstrap = 999, BPPARAM = BiocParallel::SerialParam(), ... @@ -78,6 +79,10 @@ bounded by 1 and analysed on the scale \eqn{-\log(1 - d)}. See details. \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 +the sampling times within subjects for the test of temporal structure; +\code{0} for none. See details. (Default: \code{0})} + \item{bootstrap}{\code{Integer scalar}. The number of resamples of subjects within each level of \code{split.by}. (Default: \code{999})} @@ -92,8 +97,8 @@ parameter (and level of \code{split.by}, and comparison) and the columns \describe{ \item{\code{split.by}}{When \code{split.by} is given: the level, or the comparison (\code{"B / A"}).} -\item{type}{\code{"parameter"}, or \code{"ratio"} for comparisons -between levels.} +\item{type}{\code{"parameter"}, \code{"ratio"} for comparisons +between levels, or \code{"test"}.} \item{form}{The fitted form.} \item{parameter}{\code{"nugget"}, \code{"partial.sill"}, \code{"sill"} and \code{"timescale"} (with suffixes \code{.1} and @@ -187,6 +192,17 @@ whose midpoint \eqn{m} satisfies \eqn{(1 + m) / (1 + a)} in \code{\link[miaTime:getVariogram]{getVariogram()}}, so that the levels are compared around the same time \eqn{a}. +\strong{Temporal structure.} Without temporal structure, dissimilarity +does not depend on the lag, the timescale is not identified and tests on +it are meaningless. With \code{permutations > 0}, a row +\code{"temporal.structure"} tests whether dissimilarity depends on the +lag at all: its estimate is the subject-weighted mean dissimilarity of +pairs in the upper quartile of the lags minus that of pairs in the lower +quartile, and its p-value compares it with the same statistic after the +sampling times are permuted within each subject, which leaves the +dissimilarities unchanged. It uses the pairs at all lags, and is computed +for each level of \code{split.by}. + The dissimilarities are those of \code{\link[miaTime:getVariogram]{getVariogram()}}; see its details for the choice of dissimilarity and for bounded dissimilarities. diff --git a/tests/testthat/test-getVariogramModel.R b/tests/testthat/test-getVariogramModel.R index c59ed3e..7d1eb20 100644 --- a/tests/testthat/test-getVariogramModel.R +++ b/tests/testthat/test-getVariogramModel.R @@ -114,3 +114,43 @@ test_that("Parameters are compared between groups", { expect_true(all(res$time.point == 5)) expect_true(all(is.na(res$p.value[res$type == "parameter"]))) }) + +test_that("Permutation test for temporal structure", { + # Twenty subjects with eight samples each: a random walk has temporal + # structure, independent values have none + time <- rep(0:7, 20) + subject <- rep(paste0("s", 1:20), each = 8) + ij <- do.call(rbind, lapply(split(seq_along(time), subject), function(i){ + t(combn(i, 2)) + })) + .pairs <- function(x){ + data.frame(subject = subject[ij[, 1]], + h = abs(time[ij[, 2]] - time[ij[, 1]]), + mid = (time[ij[, 1]] + time[ij[, 2]]) / 2, + d = (x[ij[, 1]] - x[ij[, 2]])^2, k = ij[, 1], l = ij[, 2]) + } + set.seed(1) + walk <- ave(rnorm(160), subject, FUN = cumsum) + res <- miaTime:::.temporal_structure(.pairs(walk), time, 99) + expect_true(res$statistic > 0) + expect_equal(res$p.value, 0.01) + res <- miaTime:::.temporal_structure(.pairs(rnorm(160)), time, 99) + expect_true(res$p.value > 0.05) + + data(hitchip1006, package = "miaTime") + tse <- transformAssay(hitchip1006, method = "hellinger") + args <- list(tse, time.col = "time", group = "subject", + assay.type = "hellinger", method = "euclidean", squared = TRUE, + form = "linear") + expect_false("test" %in% do.call(getVariogramModel, args)$type) + set.seed(1) + res <- do.call(getVariogramModel, c(args, permutations = 19)) + tt <- res[res$type == "test", ] + expect_identical(tt$parameter, "temporal.structure") + expect_true(tt$p.value >= 1 / 20 && tt$p.value <= 1) + set.seed(1) + res <- do.call(getVariogramModel, c(args, permutations = 19, + split.by = "sex", bootstrap = 9)) + expect_identical(res$sex[res$type == "test"], c("female", "male")) + expect_error(do.call(getVariogramModel, c(args, permutations = -1))) +})