inst/nami_simulations/simulation_code/helpers.R

create_setup <- function(repl, N, P, truetau, lambda) {
  setups <- expand.grid(repl, N, P, truetau, lambda)
  setups$seed <- round(runif(nrow(setups)) * 1e8)
}

get_results <- function(m, parm, level = 0.95, type = c("Wald", "score")) {
  type <- match.arg(type)
  stopifnot(parm %in% names(coef(m)))
  stopifnot(length(parm) == 1L)
  if (type == "score") {
      sc <- score_test(m, parm = parm, level = level, 
                       confint = TRUE)
      return(list(tau = coef(m)[parm], se = sqrt(vcov(m)[parm,parm]),
                  score = sc$conf.int, pvalue = sc$p.value[[1]]))
  }
  lf <- paste(parm, "=0")
  cc <- glht(m, linfct = lf, coef. = function(x) coef(x, fixed = FALSE))
  ret <- list(tau = coef(m)[parm], se = sqrt(vcov(m)[parm,parm]), 
              lambda = NA,
              wald = confint(cc, level = level)$confint[, c("lwr", "upr")],
              pvalue = summary(cc)$test$pvalue[[1]])
  if (inherits(m, "mmlt")) {
      ret$lambda <- coef(m, type = "Lambda")
      nm <- dimnames(ret$lambda)[[2L]]
      ### we want (Y, X1, ..., XP)
      idx <- match(c("y", sort(nm[nm != "y"])), nm)
      ret$lambda <- mvtnorm:::aperm.invchol(ret$lambda, perm = idx)
      ret$lambda <- invcholD(ret$lambda, D = 1 / diagonals(ret$lambda))
  }
  return(ret)
}

get_packages <- function(pkgs) {
  rpkgs <- sapply(pkgs, require, character.only = TRUE)
  if (!all(rpkgs)) sapply(pkgs[!rpkgs], install.packages)
  rpkgs <- sapply(pkgs, require, character.only = TRUE)
  if (!all(rpkgs)) stop("could not attach all required packages")
}


simulate_zwx <- function(N = 1000L, P = 1L, lambda = 0, pisetup = "C", RCT = TRUE, seed = NULL) {

  ### set and re-set seed
  if (!exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) {
    runif(1)
  } 
  if (is.null(seed)) {
    RNGstate <- get(".Random.seed", envir = .GlobalEnv)
  } else {
    R.seed <- get(".Random.seed", envir = .GlobalEnv)
    set.seed(seed)
    RNGstate <- structure(seed, kind = as.list(RNGkind()))
    on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv))
  }
  ### sample size
  N <- round(N)
  
  ### number of covariates
  J <- P + 1 ### (Y, X1, ..., XP)

  ### transformation function h_1(X_1)
  h1 <- function(y) qnorm(pchisq(y, df = 5, log = TRUE), log = TRUE)
  h1inv <- function(z) qchisq(pnorm(z, log = TRUE), df = 5, log = TRUE)

  ### names for data set
  nm <- c("y", nmx <- paste0("x", 1:(J - 1)))

  ### set-up correlation structure:
  ### (Y, X1) with lambda
  ### (X2, ..., XP) with .5
  prm <- c(lambda, 
           rep(0, P - 1), 	     ### Y indep. X2, ..., XP
           rep(.5, P * (P - 1) / 2)) ### X1, ..., XP dependent
  L <- ltMatrices(prm, names = nm, byrow = FALSE)
  ### always standardize
  L <- invcholD(L)

  ### sample latent normals
  Z <- matrix(rnorm(2 * N * J), nrow = J)
  d <- as.data.frame(t(solve(L, Z)))

  ### treatment assignment 
  ### RCT
  if (RCT) {
      ### RCT with 1:1 allocation
      d$w <- gl(2, N, labels = c("ctrl", "trt"))
  } else {
      ### observational: propensities 
      ### similar to pi_C from Dandl et al. DOI:10.1214/23-AOAS1799
      stopifnot(P > 1L)
      if (pisetup == "C") {
         pi <- with(d, plogis(-(x1 + x2)))
      } else if (pisetup == "D") {
         pi <- with(d, 1/(1 + exp(-x1) + exp(-x2)))
      }
      ### treatment 
      d$w <- factor(rbinom(nrow(d), prob = pi, size = 1), levels = 0:1, 
                    labels = c("ctrl", "trt"))
      xnnames <- names(d)[grep("x", names(d))]
      X <- d[, xnnames, drop = FALSE]
      rf <- randomForest(x = X, y = d$w)
      pihat <- predict(rf, type = "prob")[, "trt"]
      attr(d, "pi") <- pi
      attr(d, "pihat") <- pihat
      
      
      
      
  }

  ### X1 ~ Chisq(5)
  d$x1 <- h1inv(d$x1)
  ### Xj ~ t_j, j = 2, ..., P
  if (P > 1) {
      for (j in 2:P)
          d[[paste0("x", j)]] <- qt(pnorm(d[[paste0("x", j)]], log = TRUE), 
                                    log = TRUE, df = j)
  }

  attr(d, "u") <- runif(nrow(d)) ### for independent censoring
  return(d)
}

generate_cont <- function(N = 1000L, P = 1L, parm = c(truetau = 0, lambda = 0), 
                          pisetup = NULL, seed = NULL, RCT) {

  #<NOTE> Watch out with seeds!
  
  d <- simulate_zwx(N = N, P = P, lambda = parm[["lambda"]], 
                    pisetup = pisetup, seed = seed, RCT = RCT) 
  
  ### counterfactuals
  Y0 <- d$y
  Y1 <- d$y + parm["truetau"]   ### Y ~ N(0, 1)
  d$y <- ifelse(d$w == "trt", Y1, Y0)
 
  attr(d, "lambda") <- parm["lambda"]

  return(d)
}

generate_bin <- function(N = 1000L, P = 1L, parm = c(truetau = 0, lambda = 0), pisetup = NULL,
            seed = NULL, RCT) {

  #<NOTE> Watch out with seeds!
  
  d <- simulate_zwx(N = N, P = P, lambda = parm[["lambda"]], pisetup = pisetup, seed = seed, RCT = RCT) 
  
  ### Transform normally distributed Y back to distribution of interest
  Y0 <- factor(qlogis(pnorm(d$y)) > 0, levels = c(FALSE, TRUE), labels = c("fail", "succ"))
  Y1 <- factor(qlogis(pnorm(d$y)) > -parm["truetau"], levels = c(FALSE, TRUE), labels = c("fail", "succ"))
  d$y <- Y0
  d$y[d$w == "trt"] <- Y1[d$w == "trt"]
 
  attr(d, "lambda") <- parm["lambda"]

  return(d)
}

generate_surv <- function(N = 1000L, P = 1L, parm = c(truetau = 0, lambda = 0, betacens = 0), 
            pisetup = NULL, seed = NULL, RCT) {

  #<NOTE> Watch out with seeds!
  
  d <- simulate_zwx(N = N, P = P, lambda = parm[["lambda"]], pisetup = pisetup, seed = seed, RCT = RCT) 

  ### Transform normally distributed Z to Weibull distribution of interest
  cloglog <- function(u) log(-log1p(-u))
  Y0 <- exp(cloglog(pnorm(d$y)) / 1.5)
  Y1 <- exp((cloglog(pnorm(d$y)) - parm["truetau"]) / 1.5)
  d$y <- ifelse(d$w == "trt", Y1, Y0)
  
  ### Censoring indicator 
  C0 <- exp((cloglog(attr(d, "u")) - parm["betacens"]) / 1.5)
  C1 <- exp((cloglog(attr(d, "u")) - parm["truetau"] - parm["betacens"]) / 1.5)
  d$event <- ifelse(d$w == "trt", Y1 < C1, Y0 < C0)
  d$y <- ifelse(d$w == "trt", pmin(Y1, C1), pmin(Y0, C0))

  d$y <- with(d, Surv(y, event = event))
  attr(d, "lambda") <- parm["lambda"]

  return(d) 
}


fun_w <- function(instance, FUN, ...) {
  mYw <- FUN(y ~ w, data = instance)
  pos <- grep("w", names(coef(mYw)))
  get_results(mYw, names(coef(mYw))[pos])
}

fun_cw <- function(instance, FUN, oracle = FALSE, ...) {
  if (!oracle) {
    pi <- attr(instance, "pihat")
  } else {
    pi <- attr(instance, "pi")
  }
  instance$w <- (0:1)[instance$w] - pi
  fun_w(instance, FUN = FUN, ...)
}

fun_ipw <- function(instance, FUN, oracle = FALSE, ...) {
  if (!oracle) {
    pi <- attr(instance, "pihat")
    if (any(pi %in% c(0, 1))) {
      pi <-  as.numeric(trim(pi, at = 0.9, treat = instance$w, lower = TRUE))
    }
  } else {
    pi <- attr(instance, "pi")
  }
  ipw <- ((0:1)[instance$w]/pi) + ((1 - (0:1)[instance$w])/(1 - pi))
  mYw <- FUN(y ~ w, data = instance, weights = ipw)
  pos <- grep("w", names(coef(mYw)))
  get_results(mYw, names(coef(mYw))[pos])
}

fun_ipw_oracle <- function(instance, FUN, ...) {
  fun_ipw(instance, FUN, oracle = TRUE, ...)
}

fun_wx <- function(instance, FUN, ...) {
  xnnames <- names(instance)[grep("x", names(instance))]
  formulastring <- paste0("y ~ w + ", paste(xnnames, collapse = " + "))
  mYwx <- FUN(as.formula(formulastring), data = instance)
  pos <- grep("w", names(coef(mYwx)))
  get_results(mYwx, names(coef(mYwx))[pos])
}

fun_mmlt <- function(instance, FUN, center = FALSE, ipw = FALSE, oracle = FALSE, ...) { 
  if (ipw | center) {
    if (oracle) {
      pi <- attr(instance, "pi")
    } else {
      pi <- attr(instance, "pihat")
    }
  }
  if (ipw) {
    if (!oracle & any(pi %in% c(0, 1))) {
      pi <-  as.numeric(trim(pi, at = 0.9, treat = instance$w, lower = TRUE))
    }
    wght <- ((0:1)[instance$w]/pi) + ((1 - (0:1)[instance$w])/(1 - pi))
  } else {
    wght <- NULL
  }
  if (center) {
      instance$w <- (0:1)[instance$w] - pi
  }
  mx <- BoxCox(x1 ~ 1, data = instance, weights = wght)
  myw <- FUN(y ~ w, data = instance, weights = wght)
  xnnames <- names(instance)[grep("x", names(instance))]
  if (length(xnnames) == 1) {
    m <- mmlt(mx, myw, data = instance, theta = c(coef(as.mlt(mx), fixed = FALSE), coef(as.mlt(myw), fixed = FALSE), attr(instance, "lambda")))
  } else {
    mods <- list()
    for (i in 2:length(xnnames)) {
      mods[[i-1]] <- BoxCox(as.formula(paste(xnnames[i], "~ 1")), data = instance, weights = wght)
    }
    l <- c(mods, list(mx), list(myw))
    theta <- lapply(l, function(m) coef(as.mlt(m), fixed = FALSE))
    J <- length(xnnames) + 1
    theta <- c(do.call("c", theta), rep(.5, J * (J - 1) / 2 - 1), attr(instance, "lambda")) 
    m <- do.call(mmlt, c(l, list(theta = theta, data = instance)))
  }
  pos <- grep("w", names(coef(m)))
  get_results(m, names(coef(m))[pos])
}

fun_mmlt_ipw <- function(instance, FUN, ...) {
  fun_mmlt(instance, FUN, ipw = TRUE, oracle = FALSE)
}

fun_mmlt_ipw_oracle <- function(instance, FUN, ...) {
  fun_mmlt(instance, FUN, ipw = TRUE, oracle = TRUE)
}

fun_mmlt_cw <- function(instance, FUN, ...) {
  fun_mmlt(instance, FUN, center = TRUE)
}

fun_mmlt_cw_oracle <- function(instance, FUN, ...) {
  fun_mmlt(instance, FUN, center = TRUE, oracle = TRUE)
}

fun <- function(job, N, P, truetau, lambda, pisetup, seed, ...) {
  d <- generate_data(N = N, P = P, parm = c(truetau = truetau, lambda = lambda), 
                     pisetup = pisetup, seed = seed)
  return(d)
}

fun_linear_w <- function(instance, ...) {
  fun_w(instance, FUN = Lm, ...)
}

fun_linear_wx <- function(instance, ...) {
  fun_wx(instance, FUN = Lm, ...)
}

fun_mmlt_linear <- function(instance, ...) {
  fun_mmlt(instance, FUN = Lm, ...)
}

fun_polr_w <- function(instance, ...) {
  fun_w(instance, FUN = Polr, ...)
}

fun_polr_wx <- function(instance, ...) {
  fun_wx(instance, FUN = Polr, ...)
}

fun_mmlt_polr <- function(instance, ...) {
  fun_mmlt(instance, FUN = Polr, ...)
}

fun_coxph_w <- function(instance, ...) {
  fun_w(instance, FUN = Coxph, ...)
}

fun_coxph_wx <- function(instance, ...) {
  fun_wx(instance, FUN = Coxph, ...)
}

fun_mmlt_coxph <- function(instance, ...) {
  fun_mmlt(instance, FUN = Coxph, ...)
}

extract_results <- function(reg) {
  rpkg <- require(data.table)
  if (!rpkg) {
    install.packages(data.table)
    require(data.table)
  }
  res <- ijoin(
    getJobPars(reg = reg),
    reduceResultsDataTable(reg = reg, fun = function(x) as.list(x))
  )
  res$result <- lapply(res$result, function(rr) {
    if (inherits(rr$lambda, "ltMatrices")) {   
      lmd <- as.array(invcholD(rr$lambda))
      lmdx <- lmd["x1", "y", 1]
      selvars <- names(sort(abs(lmd[, "y", 1]), decreasing = TRUE))
      selvars <- setdiff(selvars, "y")
      rr$lambda <- lmdx 
      rr$selvars <- selvars[1] == "x1"
    } else {
      rr$selvars <- NA
      rr$lambda <- NA 
    }
    rr$wald1 <- rr$wald[[1]]
    rr$wald2 <- rr$wald[[2]]
    rr$wald <- NULL
    return(rr)
  })
  probpars <- rbindlist(res$prob.pars, use.names = TRUE, fill = TRUE)
  setnames(probpars, "lambda", "truelambda")
  respars <- rbindlist(res$result, use.names = TRUE, fill = TRUE)
  res <- cbind(res[, .(job.id, problem, algorithm)], probpars, respars)

  # save time 
  rtime <- batchtools::getJobStatus(reg = reg)[,c("job.id", "time.running")]
  rtime$time.running <- as.numeric(rtime$time.running)
  res <- merge(res, rtime, by = "job.id")
  return(res)
}

Try the tram package in your browser

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

tram documentation built on Nov. 23, 2026, 5:07 p.m.