R/internal.R

Defines functions .as_index .ranked .false_parts .recount .max_p .threshold_chernoff .p_plus .kl_bern .threshold_bernstein .phat .centered .psi_sums .grids .cap .h_prime .h2_fun .h_fun .ecw

# Internal functions. The statistics are handled on the scale u = -z, so that
# small values of u are evidence against the null hypothesis, and the one-sided
# p-value of hypothesis i is pnorm(u[i]).

.cache <- new.env(parent = emptyenv())

# E[cosh(z X); |X| < B] for X ~ N(mu, 1)
.ecw <- function(mu, z, B) {
  a <- exp(z * mu + z * z / 2) * (stats::pnorm(B - mu - z) - stats::pnorm(-B - mu - z))
  b <- exp(-z * mu + z * z / 2) * (stats::pnorm(B - mu + z) - stats::pnorm(-B - mu + z))
  0.5 * (a + b)
}

# Mean of psi_z(u) for u ~ N(lam, 1), where
# psi_z(u) = exp(-z^2/2) min(cosh(z (u + z)), cosh(2 z^2)).
.h_fun <- function(lam, z) {
  B <- 2 * z
  mu <- lam + z
  cap <- cosh(z * B)
  tail <- stats::pnorm(-B - mu) + stats::pnorm(mu - B)
  exp(-z * z / 2) * (.ecw(mu, z, B) + cap * tail)
}

# Second moment of psi_z(u) for u ~ N(lam, 1).
.h2_fun <- function(lam, z) {
  B <- 2 * z
  mu <- lam + z
  cap <- cosh(z * B)
  w <- 0.5 * (.ecw(mu, 2 * z, B) + (stats::pnorm(B - mu) - stats::pnorm(-B - mu)))
  tail <- stats::pnorm(-B - mu) + stats::pnorm(mu - B)
  exp(-z * z) * (w + cap * cap * tail)
}

# Derivative of .h_fun in lam.
.h_prime <- function(lam, a) {
  B <- 2 * a
  s <- lam + a
  ep <- exp(a * s + a * a / 2) * (stats::pnorm(B - s - a) - stats::pnorm(-B - s - a))
  em <- exp(-a * s + a * a / 2) * (stats::pnorm(B - s + a) - stats::pnorm(-B - s + a))
  exp(-a * a / 2) * a * 0.5 * (ep - em)
}

.cap <- function(a) exp(-a * a / 2) * cosh(2 * a * a)

# Grids and constants that depend only on the number of hypotheses m; cached.
.grids <- function(m) {
  key <- as.character(m)
  g <- .cache[[key]]
  if (!is.null(g)) return(g)
  lm <- log(m)
  cmax <- 2 * sqrt(2 * lm)
  C <- 0.5 * (0:ceiling(cmax / 0.5))
  hmax <- min(0.25, (2 * lm)^(-0.5))
  h <- 2^floor(log2(hmax))
  top <- 2 * sqrt(2 * lm) + h
  K <- floor((top - 1.5) / h + 1e-12)
  A <- 1.5 + h * (0:K)
  # constants of the single-center bounds
  h0 <- .h_fun(-A, A)
  single <- list(h0 = h0, G = .h_fun(0, A) - h0,
                 var0 = .h2_fun(-A, A) - h0^2, cap = .cap(A))
  # constants of the bounds that combine two neighbouring centers
  nz <- max(20, ceiling(m^0.25)) + 1
  nk <- length(A) - 1L
  n <- nk * nz
  pair <- list(k = integer(n), w1 = numeric(n), w2 = numeric(n), f0 = numeric(n),
               G = numeric(n), sC1 = numeric(n), sC2 = numeric(n),
               cap2 = numeric(n), kappa = numeric(n))
  for (k in seq_len(nk)) {
    a1 <- A[k]
    a2 <- A[k + 1L]
    zz <- seq(a1, a2, length.out = nz)
    d1 <- .h_prime(-zz, a1)
    d2 <- .h_prime(-zz, a2)
    den <- d2 - d1
    w1 <- ifelse(den > 0, d2 / ifelse(den > 0, den, 1), 1)
    w1 <- pmin(pmax(w1, 0), 1)
    w2 <- 1 - w1
    f0 <- w1 * .h_fun(-zz, a1) + w2 * .h_fun(-zz, a2)
    Gf <- w1 * .h_fun(0, a1) + w2 * .h_fun(0, a2) - f0
    dd1 <- abs(zz - a1) + 2 * h
    dd2 <- abs(zz - a2) + 2 * h
    C1 <- pmax(.h2_fun(-a1 - dd1, a1), .h2_fun(-a1 + dd1, a1))
    C2 <- pmax(.h2_fun(-a2 - dd2, a2), .h2_fun(-a2 + dd2, a2))
    j <- (k - 1L) * nz + seq_len(nz)
    pair$k[j] <- k
    pair$w1[j] <- w1
    pair$w2[j] <- w2
    pair$f0[j] <- f0
    pair$G[j] <- Gf
    pair$sC1[j] <- sqrt(C1)
    pair$sC2[j] <- sqrt(C2)
    pair$cap2[j] <- .cap(a2)
    pair$kappa[j] <- 4 * (1 + 2 * sqrt(w1 * w2)) + 2 / 3
  }
  Q <- 2^(-(seq_len(ceiling(2 * log2(m)))))
  g <- list(C = C, A = A, h = h, single = single, pair = pair, Q = Q)
  assign(key, g, envir = .cache)
  g
}

# S_a = sum_i psi_a(u_i) for every center a.
.psi_sums <- function(u, A) {
  vapply(A, function(a) {
    exp(-a * a / 2) * sum(pmin(cosh(a * (u + a)), cosh(2 * a * a)))
  }, numeric(1))
}

.centered <- function(u, g, L) {
  m <- length(u)
  S <- .psi_sums(u, g$A)
  sc <- g$single
  ba <- (2 * pmax(S - m * sc$h0, 0) + 2 * sqrt(2 * L * m * (sc$var0 + 1)) +
           (14 / 3) * sc$cap * L) / sc$G
  pc <- g$pair
  k <- pc$k
  Dh <- pmax(pc$w1 * S[k] + pc$w2 * S[k + 1L] - m * pc$f0, 0)
  bb <- (2 * Dh + 2 * sqrt(2 * L * m) * (pc$w1 * pc$sC1 + pc$w2 * pc$sC2) +
           pc$kappa * pc$cap2 * L) / pc$G
  min(m, ba, bb, na.rm = TRUE)
}

# Fraction of statistics above each threshold c.
.phat <- function(us, C) (length(us) - findInterval(C, us)) / length(us)

.threshold_bernstein <- function(us, C, L) {
  m <- length(us)
  phat <- .phat(us, C)
  a2 <- 2 * L / m
  bb <- phat + L / (3 * m)
  xstar <- a2 / 2 + bb + 0.5 * sqrt(a2) * sqrt(a2 + 4 * bb)
  min(m, m * xstar / stats::pnorm(-C))
}

.kl_bern <- function(ph, p) {
  t1 <- ifelse(ph > 0, ph * log(ph / p), 0)
  t2 <- ifelse(ph < 1, (1 - ph) * log((1 - ph) / (1 - p)), 0)
  t1 + t2
}

# max{p >= phat : m KL(phat || p) <= L}, by bisection (upper end).
.p_plus <- function(phat, m, L, iters = 80L) {
  lo <- phat
  hi <- rep(1, length(phat))
  for (i in seq_len(iters)) {
    mid <- 0.5 * (lo + hi)
    ok <- m * .kl_bern(phat, mid) <= L
    ok[is.na(ok)] <- FALSE
    lo <- ifelse(ok, mid, lo)
    hi <- ifelse(ok, hi, mid)
  }
  ifelse(phat >= 1, 1, hi)
}

.threshold_chernoff <- function(us, C, L) {
  m <- length(us)
  phat <- .phat(us, C)
  min(m, m * .p_plus(phat, m, L) / stats::pnorm(-C))
}

# Closed testing with the maximum p-value as local test, blocks of size <= b.
.max_p <- function(u, level, b) {
  m <- length(u)
  lp <- stats::pnorm(max(u), log.p = TRUE)
  if (lp >= 0) return(m)
  x <- log(1 / level) / (-lp)
  if (!is.finite(x) || x > 10 * m) return(m)
  min(m, b * max(0, ceiling(x) - 1))
}

# Reference family bound for one selection with p-values pS.
.recount <- function(pS, N, Q, LT) {
  s <- length(pS)
  if (s == 0L) return(0)
  ps <- sort(pS)
  n_above <- s - findInterval(Q, ps)
  zeta <- N * Q + sqrt(2 * N * Q * LT) + LT / 3
  min(s, floor(min(n_above + zeta) + 1e-9))
}

# Bound on the number of false discoveries in the selection idx, with its parts.
.false_parts <- function(fit, idx) {
  s <- length(idx)
  u <- fit$.u[idx]
  total <- min(s, fit$false_all)
  cutoff <- sum(u > -fit$.cutoff)
  tail <- .recount(stats::pnorm(u), fit$bound, fit$.Q, fit$.LT)
  c(false = min(s, total, cutoff, tail), total = total, cutoff = cutoff, tail = tail)
}

# Bounds on the s most significant hypotheses, s = 1, ..., m.
.ranked <- function(fit) {
  m <- fit$m
  us <- fit$.u[fit$.order]
  s <- seq_len(m)
  cutoff <- cumsum(us > -fit$.cutoff)
  n_le <- findInterval(fit$.Q, stats::pnorm(us))
  zeta <- fit$bound * fit$.Q + sqrt(2 * fit$bound * fit$.Q * fit$.LT) + fit$.LT / 3
  best <- rep(Inf, m)
  for (j in seq_along(fit$.Q)) best <- pmin(best, pmax(0, s - n_le[j]) + zeta[j])
  tail <- pmin(s, floor(best + 1e-9))
  pmin(s, fit$false_all, cutoff, tail)
}

# Selections given as indices, logical vectors or names, converted to indices.
.as_index <- function(sel, fit) {
  m <- fit$m
  if (is.logical(sel)) {
    if (length(sel) != m) stop("a logical selection must have one value per hypothesis")
    if (anyNA(sel)) stop("a logical selection must not contain missing values")
    return(which(sel))
  }
  if (is.character(sel) || is.factor(sel)) {
    sel <- as.character(sel)
    if (is.null(fit$labels)) stop("the hypotheses have no names, so select them by index")
    idx <- match(sel, fit$labels)
    if (anyNA(idx)) stop("unknown hypothesis names: ",
                         paste(utils::head(sel[is.na(idx)], 5), collapse = ", "))
    return(unique(idx))
  }
  if (is.numeric(sel)) {
    if (anyNA(sel) || any(sel != round(sel)) || any(sel < 1) || any(sel > m))
      stop("indices must be whole numbers between 1 and ", m)
    return(unique(as.integer(sel)))
  }
  stop("a selection must be a logical, numeric or character vector")
}

Try the posthocbounds package in your browser

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

posthocbounds documentation built on Nov. 28, 2026, 1:08 a.m.