R/DSNET.R

Defines functions DSNET

Documented in DSNET

#' Distributed Two-Sample Covariance Matrix Testing
#'
#' @description
#' A fast experimental distributed variance-comparison test.
#' The samples are divided into K non-overlapping blocks.
#' Block summaries are aggregated to construct a global
#' variance-difference statistic.
#' The p-value is obtained by permutation calibration.
#'
#' This is an experimental alternative, not the original
#' SNET statistic from the thesis.
#'
#' @param X Numeric matrix of n1 by p.
#' @param Y Numeric matrix of n2 by p.
#' @param K Number of blocks.
#' @param B Retained for compatibility with existing scripts.
#' @param mc.cores Retained for compatibility.
#' @param k Retained for compatibility.
#' @param alpha Significance level.
#' @param P Number of permutations.
#'
#' @return A list containing stat, pval, power, fdr,
#' Xopt and Yopt.
#'
#' @export
DSNET <- function(X, Y, K, B = 20, mc.cores = 1L,
                  k = 3, alpha = 0.05, P = 99) {
  
  X <- as.matrix(X)
  Y <- as.matrix(Y)
  
  if (!is.numeric(X) || !is.numeric(Y)) {
    stop("X and Y must be numeric matrices.")
  }
  
  if (ncol(X) != ncol(Y)) {
    stop("X and Y must have the same number of columns.")
  }
  
  if (any(!is.finite(X)) || any(!is.finite(Y))) {
    stop("X and Y must contain only finite values.")
  }
  
  if (length(K) != 1 || !is.finite(K) ||
      K < 1 || K != floor(K)) {
    stop("K must be a positive integer.")
  }
  
  if (length(P) != 1 || !is.finite(P) ||
      P < 1 || P != floor(P)) {
    stop("P must be a positive integer.")
  }
  
  n1 <- nrow(X)
  n2 <- nrow(Y)
  p <- ncol(X)
  
  if (floor(min(n1, n2) / K) < 4) {
    stop("Each block must contain at least 4 observations.")
  }
  
  # 按 K 个不重叠数据块计算局部汇总量
  block_summary <- function(Z, K) {
    
    n <- nrow(Z)
    
    idx <- split(
      seq_len(n),
      rep(seq_len(K), length.out = n)
    )
    
    block_n <- numeric(K)
    block_sum <- matrix(0, K, ncol(Z))
    block_sumsq <- matrix(0, K, ncol(Z))
    
    for (j in seq_len(K)) {
      
      Zj <- Z[idx[[j]], , drop = FALSE]
      
      block_n[j] <- nrow(Zj)
      block_sum[j, ] <- colSums(Zj)
      block_sumsq[j, ] <- colSums(Zj^2)
    }
    
    return(list(
      n = block_n,
      sum = block_sum,
      sumsq = block_sumsq,
      idx = idx
    ))
  }
  
  # 利用各数据块的汇总量计算全局统计量
  compute_stat <- function(X, Y, K) {
    
    SX <- block_summary(X, K)
    SY <- block_summary(Y, K)
    
    nx <- sum(SX$n)
    ny <- sum(SY$n)
    
    sumX <- colSums(SX$sum)
    sumY <- colSums(SY$sum)
    
    sumsqX <- colSums(SX$sumsq)
    sumsqY <- colSums(SY$sumsq)
    
    varX <- (
      sumsqX - sumX^2 / nx
    ) / (nx - 1)
    
    varY <- (
      sumsqY - sumY^2 / ny
    ) / (ny - 1)
    
    pooled_var <- (
      (nx - 1) * varX +
        (ny - 1) * varY
    ) / (nx + ny - 2)
    
    pooled_var <- pmax(
      pooled_var,
      .Machine$double.eps
    )
    
    # 标准化每个变量的样本方差差异
    scale <- 2 * pooled_var^2 * (
      1 / (nx - 1) + 1 / (ny - 1)
    )
    
    stat <- sum(
      (varX - varY)^2 / scale
    )
    
    return(stat)
  }
  
  # 原始统计量
  stat <- compute_stat(X, Y, K)
  
  # 全局置换检验
  Z <- rbind(X, Y)
  N <- n1 + n2
  
  stat_perm <- numeric(P)
  
  for (b in seq_len(P)) {
    
    idx <- sample.int(N)
    
    X_perm <- Z[
      idx[seq_len(n1)],
      ,
      drop = FALSE
    ]
    
    Y_perm <- Z[
      idx[n1 + seq_len(n2)],
      ,
      drop = FALSE
    ]
    
    stat_perm[b] <- compute_stat(
      X_perm,
      Y_perm,
      K
    )
  }
  
  pval <- (
    1 + sum(stat_perm >= stat)
  ) / (P + 1)
  
  # 选择局部方差差异最大的块
  idxX <- split(
    sample.int(n1),
    rep(seq_len(K), length.out = n1)
  )
  
  idxY <- split(
    sample.int(n2),
    rep(seq_len(K), length.out = n2)
  )
  
  local_stat <- numeric(K)
  
  for (j in seq_len(K)) {
    
    Xj <- X[idxX[[j]], , drop = FALSE]
    Yj <- Y[idxY[[j]], , drop = FALSE]
    
    local_stat[j] <- sum(
      (apply(Xj, 2, var) -
         apply(Yj, 2, var))^2
    )
  }
  
  opt <- which.max(local_stat)
  
  Xopt <- X[
    idxX[[opt]],
    ,
    drop = FALSE
  ]
  
  Yopt <- Y[
    idxY[[opt]],
    ,
    drop = FALSE
  ]
  
  # 单次检验不能直接估计经验 Power 和 FDR
  power <- NA_real_
  fdr <- NA_real_
  
  return(list(
    stat = stat,
    pval = pval,
    power = power,
    fdr = fdr,
    Xopt = Xopt,
    Yopt = Yopt
  ))
}

Try the Docovt package in your browser

Any scripts or data that you put into this service are public.

Docovt documentation built on Oct. 19, 2026, 5:06 p.m.