diff --git a/R/getVariogramModel.R b/R/getVariogramModel.R index 674f580..64c17e2 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{Stationarity.} A fitted form assumes that change at a given lag +#' does not depend on when the pair was taken, which fails in cohorts +#' followed from birth or around a perturbation. A row \code{"stationarity"} +#' reports the slope of the relative residuals \eqn{d / g(h) - 1} on the +#' pair midpoint (time, or age), per unit of time, by weighted least squares +#' with every subject counting equally and a standard error clustered by +#' subject (CR1, \eqn{G - 1} degrees of freedom). A slope that differs from +#' 0 means that the fitted form averages over changing dynamics; compare +#' change at a stated time with \code{time.point} in +#' \code{\link[miaTime:getVariogram]{getVariogram()}} instead. +#' #' \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 @@ -312,7 +323,8 @@ setMethod("getVariogramModel", signature = c(x = "SummarizedExperiment"), warning("The fit of the ", form, " form did not converge.", call. = FALSE) } - res <- .variogram_parameters(fit, conf.level) + res <- rbind(.variogram_parameters(fit, conf.level), + .stationarity(fit, conf.level)) } else{ res <- .compare_variogram_models( pairs, form, conf.level, bootstrap, BPPARAM) @@ -612,7 +624,9 @@ setMethod("getVariogramModel", signature = c(x = "SummarizedExperiment"), ci[1L, ] >= min_lag & ci[2L, ] <= max_lag, NA), n.subjects = length(unique(p$subject)), n.pairs = nrow(p), min.lag = min_lag, max.lag = max_lag) - list(table = res, boot = boot) + st <- cbind(level = g, .stationarity(fit, conf.level)) + st$max.lag <- max_lag + list(table = res, boot = boot, stationarity = st) }) comp <- lapply(seq_along(lev)[-1L], function(i){ e1 <- fits[[1L]]$table @@ -642,7 +656,8 @@ setMethod("getVariogramModel", signature = c(x = "SummarizedExperiment"), n.pairs = e1$n.pairs + e2$n.pairs, min.lag = max(e1$min.lag, e2$min.lag), max.lag = max_lag) }) - res <- do.call(rbind, c(lapply(fits, function(f) f$table), comp)) + res <- do.call(rbind, c(lapply(fits, function(f) f$table), comp, + lapply(fits, function(f) f$stationarity))) rownames(res) <- NULL attr(res, "cv") <- cv return(res) @@ -670,6 +685,37 @@ setMethod("getVariogramModel", signature = c(x = "SummarizedExperiment"), return(res) } +# Slope of the relative residuals d / g(h) - 1 on the pair midpoint, with +# subjects weighted equally and a CR1 standard error clustered by subject +.stationarity <- function(fit, conf.level){ + p <- fit$pairs + r <- p$d / fit$fitted - 1 + w <- as.numeric(1 / table(p$subject)[p$subject]) + X <- cbind(1, p$mid - stats::weighted.mean(p$mid, w)) + A <- crossprod(X, X * w) + G <- length(unique(p$subject)) + b <- c(NA_real_, NA_real_) + se <- NA_real_ + # Without spread in the midpoints there is no slope + if( qr(A)$rank == 2L ){ + Ai <- solve(A) + b <- drop(Ai %*% crossprod(X, w * r)) + U <- rowsum(X * (w * drop(r - X %*% b)), p$subject) + V <- Ai %*% crossprod(U) %*% Ai * G / (G - 1) + se <- sqrt(V[2L, 2L]) + } + q <- stats::qt(1 - (1 - conf.level) / 2, G - 1) + h <- p$h + res <- data.frame( + type = "test", form = fit$form, parameter = "stationarity", + estimate = b[[2L]], lower = b[[2L]] - q * se, upper = b[[2L]] + q * se, + se = se, df = G - 1, + p.value = 2 * stats::pt(-abs(b[[2L]] / se), G - 1), identified = NA, + n.subjects = G, n.pairs = nrow(p), min.lag = min(h[h > 0]), + max.lag = max(h)) + 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 diff --git a/man/getVariogramModel.Rd b/man/getVariogramModel.Rd index f848cce..075b263 100644 --- a/man/getVariogramModel.Rd +++ b/man/getVariogramModel.Rd @@ -192,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{Stationarity.} A fitted form assumes that change at a given lag +does not depend on when the pair was taken, which fails in cohorts +followed from birth or around a perturbation. A row \code{"stationarity"} +reports the slope of the relative residuals \eqn{d / g(h) - 1} on the +pair midpoint (time, or age), per unit of time, by weighted least squares +with every subject counting equally and a standard error clustered by +subject (CR1, \eqn{G - 1} degrees of freedom). A slope that differs from +0 means that the fitted form averages over changing dynamics; compare +change at a stated time with \code{time.point} in +\code{\link[miaTime:getVariogram]{getVariogram()}} instead. + \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 diff --git a/tests/testthat/test-getVariogramModel.R b/tests/testthat/test-getVariogramModel.R index 7d1eb20..6e508bd 100644 --- a/tests/testthat/test-getVariogramModel.R +++ b/tests/testthat/test-getVariogramModel.R @@ -58,12 +58,12 @@ test_that("getVariogramModel output", { res <- do.call(getVariogramModel, c(args, form = "exponential")) expect_s4_class(res, "DataFrame") expect_identical(res$parameter, - c("nugget", "partial.sill", "sill", "timescale")) + c("nugget", "partial.sill", "sill", "timescale", "stationarity")) expect_true(all(res$form == "exponential")) expect_null(metadata(res)$cv) expect_equal(res$estimate[3], res$estimate[1] + res$estimate[2]) expect_identical(do.call(getVariogramModel, c(args, form = "linear"))$parameter, - c("nugget", "slope")) + c("nugget", "slope", "stationarity")) # Cross-validation set.seed(1) res <- do.call(getVariogramModel, c(args, @@ -110,7 +110,8 @@ test_that("Parameters are compared between groups", { assay.type = "hellinger", method = "euclidean", squared = TRUE, form = "linear", split.by = "sex", bootstrap = 19, time.point = 5) expect_identical(unique(res$sex), c("female", "male", "male / female")) - expect_identical(res$type, rep(c("parameter", "ratio"), c(4, 2))) + expect_identical(res$type, rep(c("parameter", "ratio", "test"), + c(4, 2, 2))) expect_true(all(res$time.point == 5)) expect_true(all(is.na(res$p.value[res$type == "parameter"]))) }) @@ -142,15 +143,38 @@ test_that("Permutation test for temporal structure", { 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) + expect_false("temporal.structure" %in% + do.call(getVariogramModel, args)$parameter) set.seed(1) res <- do.call(getVariogramModel, c(args, permutations = 19)) - tt <- res[res$type == "test", ] + tt <- res[res$parameter == "temporal.structure", ] 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_identical(res$sex[res$parameter == "temporal.structure"], + c("female", "male")) expect_error(do.call(getVariogramModel, c(args, permutations = -1))) }) + +test_that("Stationarity check", { + # Relative residuals that grow by 0.01 per unit of midpoint time, with + # pairs of every subject spread over time + set.seed(1) + pairs <- .make_exponential_pairs() + pairs$mid <- rep(seq(0, 90, by = 10), 40) + fit <- miaTime:::.fit_variogram(pairs, "exponential") + res <- miaTime:::.stationarity(fit, 0.95) + expect_true(abs(res$estimate) < 3 * res$se) + fit$pairs$d <- fit$fitted * (1 + 0.01 * (pairs$mid - 45) + + rnorm(400, sd = 0.05)) + res <- miaTime:::.stationarity(fit, 0.95) + expect_equal(res$estimate, 0.01, tolerance = 0.05) + expect_true(res$p.value < 0.001) + expect_true(res$lower < 0.01 && res$upper > 0.01) + expect_identical(res$df, 39) + # No slope when every pair has the same midpoint + fit$pairs$mid <- 20 + expect_true(is.na(miaTime:::.stationarity(fit, 0.95)$estimate)) +})