OSCR

Double shrinkage transfer causal learning: An application to alzheimer's disease.

Code ↔ Paper

5 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 5 matches · 2 of them tie a paragraph to a whole file, not to given lines: weak matches, whose lines are not tinted
  1. [1] § 2. Materials and methods › 2.3. Proposed method › 2.3.3 Estimation of causal effect. ↔ simulate_dstcl_main.R, lines 156–206 · score 0.70 · l1 regularized, lambda.min, lambda.1se, error, alpha, glmnet
  2. [2] § 2. Materials and methods › 2.3. Proposed method › 2.3.3 Estimation of causal effect. ↔ real_data_analysis_template.R, lines 334–393 · score 0.64 · lambda.min, lambda.1se, deviance, fold, binomial, alpha
  3. [3] § 3. Simulation › 3.3. Simulation results ↔ glmtrans.R, the whole file · a weak match · score 0.54 · lambda.min, lambda.1se, penalty, bias, fit
  4. [4] § 3. Simulation › 3.3. Simulation results ↔ simulate_dstcl_main.R, lines 156–206 · score 0.53 · lambda.min, lambda.1se, penalty, fit, DSTCL, Simulation
  5. [5] § 3. Simulation › 3.2. Simulation scenarios ↔ glmtrans.R, the whole file · a weak match · score 0.50 · lambda.min, lambda.1se, penalty

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

R · 685 lines · 24 KB · no license · 2 matches

  1. required_pkgs <- c(
  2. "MASS", "glmnet", "Matrix", "parallel",
  3. "DoubleML", "mlr3", "mlr3learners", "tmle",
  4. "ranger", "e1071", "SuperLearner"
  5. )
  6. missing_pkgs <- required_pkgs[!sapply(required_pkgs, requireNamespace, quietly = TRUE)]
  7. if (length(missing_pkgs) > 0) {
  8. stop("Missing packages: ", paste(missing_pkgs, collapse = ", "),
  9. "\nPlease install them before running this simulation script.")
  10. }
  11. suppressPackageStartupMessages({
  12. library(MASS)
  13. library(glmnet)
  14. library(Matrix)
  15. library(parallel)
  16. library(DoubleML)
  17. library(mlr3)
  18. library(mlr3learners)
  19. library(tmle)
  20. library(ranger)
  21. library(e1071)
  22. library(SuperLearner)
  23. })
  24. if (requireNamespace("lgr", quietly = TRUE)) {
  25. lgr::get_logger("mlr3")$set_threshold("warn")
  26. }
  27. get_script_dir <- function() {
  28. cmd.args <- commandArgs(FALSE)
  29. file.arg <- cmd.args[grep("^--file=", cmd.args)]
  30. if (length(file.arg) > 0) dirname(normalizePath(sub("^--file=", "", file.arg[1]))) else getwd()
  31. }
  32. CODE_DIR <- get_script_dir()
  33. PROJECT_DIR <- normalizePath(file.path(CODE_DIR, ".."), mustWork = FALSE)
  34. output_dir <- file.path(PROJECT_DIR, "results")
  35. dir.create(output_dir, recursive = TRUE, showWarnings = FALSE)
  36. source(file.path(CODE_DIR, "gen_latest.R"))
  37. source(file.path(CODE_DIR, "glmtrans.R"))
  38. set.seed(321)
  39. #E(z=1)=0.5, link = 'logit'
  40. n=50 # 50,200,1000,2000
  41. m=1000
  42. p=100
  43. nsim=200 #模拟次数
  44. B=500#重抽样次数
  45. BOOT_CORES <- max(1, min(15, parallel::detectCores() - 1))
  46. BOOT_CLUSTER <- NULL
  47. ######################################
  48. ## setting
  49. alpha1 <- c(0.2, rep(0.3,5),rep(0.6,45),rep(0,50)) #source. ps
  50. alpha2 <- c(-0.2, rep(-0.3,5),rep(0.6,45),rep(0,50)) #target. ps
  51. beta1.t <- c(1, rep(0.3,3),rep(-0.3,2),rep(0.8,25),rep(-0.8,20),rep(0,50))
  52. beta1.c <- c(-1, rep(0.3,3),rep(-0.3,2),rep(0.8,25),rep(-0.8,20),rep(0,50))
  53. beta2.t <- c(-1, rep(-0.3,3),rep(0.3,2),rep(0.8,25),rep(-0.8,20),rep(0,50))
  54. beta2.c <- c(1, rep(-0.3,3),rep(0.3,2),rep(0.8,25),rep(-0.8,20),rep(0,50))
  55. sigmoid <- function(x) 1 / (1 + exp(-x))
  56. ######################################
  57. ## 最小诊断记录对象
  58. ######################################
  59. REG_DIAG <- data.frame()
  60. RUN_STATUS <- data.frame()
  61. ESTIMATOR_TIME <- rep(NA, nsim)
  62. BOOTSTRAP_TIME <- rep(NA, nsim)
  63. TOTAL_TIME <- rep(NA, nsim)
  64. CURRENT_SIM <- NA
  65. CURRENT_STAGE <- "main"
  66. SAVE_REG_DIAG <- TRUE
  67. METHOD_NAMES <- c(
  68. "naive_diff",
  69. "oracle_dr",
  70. "target_lasso_dr",
  71. "doubleml_glmnet_ranger",
  72. "doubleml_svm_ranger",
  73. "tmle_glmnet",
  74. "glmtrans2old",
  75. "dstcl_transfer"
  76. )
  77. MAIN_METHOD_TIME_SUM <- matrix(0, nsim, length(METHOD_NAMES))
  78. MAIN_METHOD_TIME_COUNT <- matrix(0, nsim, length(METHOD_NAMES))
  79. BOOT_METHOD_TIME_SUM <- matrix(0, nsim, length(METHOD_NAMES))
  80. BOOT_METHOD_TIME_COUNT <- matrix(0, nsim, length(METHOD_NAMES))
  81. colnames(MAIN_METHOD_TIME_SUM) <- METHOD_NAMES
  82. colnames(MAIN_METHOD_TIME_COUNT) <- METHOD_NAMES
  83. colnames(BOOT_METHOD_TIME_SUM) <- METHOD_NAMES
  84. colnames(BOOT_METHOD_TIME_COUNT) <- METHOD_NAMES
  85. record_method_time <- function(method_index, elapsed_sec) {
  86. if (is.na(CURRENT_SIM)) return(invisible(NULL))
  87. if (is.character(method_index)) method_index <- match(method_index, METHOD_NAMES)
  88. if (is.na(method_index)) return(invisible(NULL))
  89. if (CURRENT_STAGE == "bootstrap") {
  90. BOOT_METHOD_TIME_SUM[CURRENT_SIM, method_index] <<-
  91. BOOT_METHOD_TIME_SUM[CURRENT_SIM, method_index] + elapsed_sec
  92. BOOT_METHOD_TIME_COUNT[CURRENT_SIM, method_index] <<-
  93. BOOT_METHOD_TIME_COUNT[CURRENT_SIM, method_index] + 1
  94. } else {
  95. MAIN_METHOD_TIME_SUM[CURRENT_SIM, method_index] <<-
  96. MAIN_METHOD_TIME_SUM[CURRENT_SIM, method_index] + elapsed_sec
  97. MAIN_METHOD_TIME_COUNT[CURRENT_SIM, method_index] <<-
  98. MAIN_METHOD_TIME_COUNT[CURRENT_SIM, method_index] + 1
  99. }
  100. invisible(NULL)
  101. }
  102. add_reg_diag <- function(fit, method, component) {
  103. d <- fit$diag
  104. d$sim <- CURRENT_SIM
  105. d$method <- method
  106. d$component <- component
  107. diag_cols <- c("sim", "method", "component",
  108. "nfolds_used", "lambda_rule",
  109. "source_lambda", "correction_lambda",
  110. "nonzero_source", "nonzero_delta", "nonzero_final",
  111. "prop_nonzero_source", "prop_nonzero_delta", "prop_nonzero_final",
  112. "l1_source", "l1_delta", "l1_final",
  113. "n_try_correction", "converged")
  114. missing_cols <- setdiff(diag_cols, names(d))
  115. for (col in missing_cols) {
  116. d[[col]] <- NA
  117. }
  118. d <- d[, diag_cols]
  119. return(d)
  120. }
  121. ######################################
  122. ## 估计函数(baseline + DR + transfer)
  123. or <- function(x,z,beta.t,beta.c){
  124. mean((as.matrix(x)%*%beta.t)-(as.matrix(x)%*%beta.c))
  125. }
  126. ipw <- function(y,z,x,alpha){
  127. p <- sigmoid(as.matrix(x)%*%alpha)
  128. p <- pmin(pmax(p,1e-4),1-1e-4)
  129. sum(y*z/p)/sum(z/p) - sum(y*(1-z)/(1-p))/sum((1-z)/(1-p))
  130. }
  131. dr <- function(y,z,x,alpha,beta.t,beta.c){
  132. ps <- sigmoid(as.matrix(x)%*%alpha)
  133. ps <- pmin(pmax(ps,1e-4),1-1e-4)
  134. mu1 <- as.matrix(x)%*%beta.t
  135. mu0 <- as.matrix(x)%*%beta.c
  136. mean((mu1-mu0)+(z*(y-mu1))/ps-((1-z)*(y-mu0))/(1-ps))
  137. }
  138. glmtrans2old <- function(target=target, source = source, family = "gaussian", lambda = lambda,
  139. type.measure=type.measure, alpha = 1, nfolds = nfolds,
  140. intercept=intercept, penalty.factor=penalty.factor) {
  141. ## Purpose:
  142. ## Reproduce the original l1-TCL comparison method. The source model is
  143. ## fitted by ordinary GLM, followed by an L1-regularized target correction.
  144. beta1 <- glm(y ~ ., family = family, data = source)$coefficients
  145. offset <- as.numeric(as.matrix(target[, -1]) %*% beta1[-1]) + beta1[1]
  146. n.try <- 0
  147. while (TRUE) {
  148. cv.fit.correct <- try(
  149. cv.glmnet(
  150. x = as.matrix(target[, -1]),
  151. y = as.matrix(target[, 1]),
  152. offset = offset,
  153. alpha = 1,
  154. nfolds = nfolds,
  155. intercept = intercept,
  156. type.measure = type.measure,
  157. family = family,
  158. grouped = FALSE,
  159. penalty.factor = penalty.factor
  160. ),
  161. silent = TRUE
  162. )
  163. if (!inherits(cv.fit.correct, "try-error")) break
  164. n.try <- n.try + 1
  165. if (n.try > 10) stop("Errors occur during the debiasing step!!!")
  166. }
  167. if (lambda == "lambda.min") {
  168. lambda.fit <- cv.fit.correct$lambda.min
  169. coef.correct <- coef(cv.fit.correct, s = cv.fit.correct$lambda.min)
  170. } else if (lambda == "lambda.1se") {
  171. lambda.fit <- cv.fit.correct$lambda.1se
  172. coef.correct <- coef(cv.fit.correct, s = cv.fit.correct$lambda.1se)
  173. } else {
  174. stop("lambda must be either 'lambda.min' or 'lambda.1se'")
  175. }
  176. beta <- beta1 + coef.correct
  177. obj <- list(
  178. beta = beta,
  179. family = family,
  180. fitting.list = list(beta1 = beta1, delta_a = coef.correct),
  181. lambda = lambda.fit
  182. )
  183. class(obj) <- "glmtrans"
  184. return(obj)
  185. }
  186. estimate_doubleml_glmnet_ranger <- function(y.t, z.t, x.t) {
  187. data_dml <- DoubleMLData$new(
  188. data = data.frame(y = y.t, d = z.t, x.t),
  189. y_col = "y",
  190. d_cols = "d"
  191. )
  192. ml_g <- lrn("regr.cv_glmnet")
  193. ml_m <- lrn("classif.ranger", predict_type = "prob")
  194. dml_irm <- DoubleMLIRM$new(data_dml, ml_g = ml_g, ml_m = ml_m, n_folds = 3)
  195. dml_irm$fit()
  196. as.numeric(dml_irm$coef)
  197. }
  198. estimate_doubleml_svm_ranger <- function(y.t, z.t, x.t) {
  199. data_dml <- DoubleMLData$new(
  200. data = data.frame(y = y.t, d = z.t, x.t),
  201. y_col = "y",
  202. d_cols = "d"
  203. )
  204. ml_g <- lrn("regr.svm")
  205. ml_m <- lrn("classif.ranger", predict_type = "prob")
  206. dml_irm <- DoubleMLIRM$new(data_dml, ml_g = ml_g, ml_m = ml_m, n_folds = 3)
  207. dml_irm$fit()
  208. as.numeric(dml_irm$coef)
  209. }
  210. estimate_tmle_glmnet <- function(y.t, z.t, x.t) {
  211. tmleresult <- tmle(
  212. y.t, z.t, x.t,
  213. family = "gaussian",
  214. Q.SL.library = "SL.glmnet",
  215. g.SL.library = "SL.glmnet"
  216. )
  217. as.numeric(tmleresult$estimates$ATE$psi)
  218. }
  219. run_safe_method <- function(method_name, expr) {
  220. method.start <- proc.time()[3]
  221. ans <- tryCatch(expr, error = function(e) NA_real_)
  222. record_method_time(method_name, proc.time()[3] - method.start)
  223. ans
  224. }
  225. init_boot_cluster <- function() {
  226. if (BOOT_CORES <= 1) return(NULL)
  227. cl <- parallel::makeCluster(BOOT_CORES)
  228. boot_wd <- getwd()
  229. parallel::clusterCall(cl, setwd, boot_wd)
  230. parallel::clusterEvalQ(cl, {
  231. suppressPackageStartupMessages({
  232. library(MASS)
  233. library(glmnet)
  234. library(Matrix)
  235. library(DoubleML)
  236. library(mlr3)
  237. library(mlr3learners)
  238. library(tmle)
  239. library(ranger)
  240. library(e1071)
  241. library(SuperLearner)
  242. })
  243. if (requireNamespace("lgr", quietly = TRUE)) {
  244. lgr::get_logger("mlr3")$set_threshold("warn")
  245. }
  246. NULL
  247. })
  248. parallel::clusterExport(
  249. cl,
  250. varlist = c(
  251. "m", "n", "p", "METHOD_NAMES",
  252. "alpha1", "alpha2", "beta1.t", "beta1.c", "beta2.t", "beta2.c",
  253. "sigmoid", "dr", "record_method_time", "add_reg_diag", "estimator",
  254. "bootstrap_one", "glmtrans2", "glmtrans2old",
  255. "estimate_doubleml_glmnet_ranger", "estimate_doubleml_svm_ranger",
  256. "estimate_tmle_glmnet", "run_safe_method"
  257. ),
  258. envir = .GlobalEnv
  259. )
  260. parallel::clusterSetRNGStream(cl, 321)
  261. cat("Initialized PSOCK cluster with", BOOT_CORES, "workers\n")
  262. flush.console()
  263. cl
  264. }
  265. ######################################
  266. ## estimator 主函数
  267. ######################################
  268. estimator <- function(data_s,data_t){
  269. ATE <- rep(NA, length(METHOD_NAMES))
  270. names(ATE) <- METHOD_NAMES
  271. y.s<-data_s[,1]; z.s<-data_s[,2]; x.s<-data_s[,c(-1,-2)]
  272. data_s<-data_s[,-3]; colnames(data_s)[1:2]<-c('y','z')
  273. y.t<-data_t[,1]; z.t<-data_t[,2]; x.t<-data_t[,c(-1,-2)]
  274. data_t<-data_t[,-3]; colnames(data_t)[1:2]<-c('y','z')
  275. ATE["naive_diff"] <- run_safe_method(
  276. "naive_diff",
  277. mean(y.t[z.t==1]) - mean(y.t[z.t==0])
  278. )
  279. ATE["oracle_dr"] <- run_safe_method(
  280. "oracle_dr",
  281. dr(y.t,z.t,x.t,alpha2,beta2.t,beta2.c)
  282. )
  283. if(sum(z.t)==n||sum(z.t)==0) stop("Target treatment has only one class")
  284. # target lasso, estimate alpha beta.t beta.c
  285. x.t1=x.t[z.t==1,]
  286. y.t1=y.t[z.t==1]
  287. x.t0=x.t[z.t==0,]
  288. y.t0=y.t[z.t==0]
  289. x.s1=x.s[z.s==1,]
  290. y.s1=y.s[z.s==1]
  291. x.s0=x.s[z.s==0,]
  292. y.s0=y.s[z.s==0]
  293. ATE["target_lasso_dr"] <- run_safe_method("target_lasso_dr", {
  294. lamda<-cv.glmnet(as.matrix(x.t), as.matrix(z.t), family = "binomial", alpha = 1,
  295. type.measure="deviance", nfolds = min(5, length(z.t)), intercept = T, grouped=F)
  296. target.ps <- glmnet(x.t, z.t, family = "binomial", alpha = 1, intercept = F, lambda = lamda$lambda.1se)
  297. lamda<-cv.glmnet(as.matrix(x.t0), as.matrix(y.t0), family = "gaussian", alpha = 1,
  298. type.measure = "mse", nfolds = min(5, length(y.t0)), grouped=F)
  299. target.or.c <- glmnet(x.t0, y.t0, family = "gaussian", alpha = 1, intercept = TRUE, lambda = lamda$lambda.1se)
  300. lamda<-cv.glmnet(as.matrix(x.t1), as.matrix(y.t1), family = "gaussian", alpha = 1,
  301. type.measure = "mse", nfolds = min(5, length(y.t1)), grouped=F)
  302. target.or.t <- glmnet(x.t1, y.t1, family = "gaussian", alpha = 1, intercept = TRUE, lambda = lamda$lambda.1se)
  303. dr(y.t,z.t,x.t,target.ps$beta,target.or.t$beta,target.or.c$beta)
  304. })
  305. penalty.factor = rep(1,p)
  306. ps.target<-data_t[,-1]
  307. colnames(ps.target)[1]<-"y"
  308. ps.source<-data_s[,-1]
  309. colnames(ps.source)[1]<-"y"
  310. ATE["doubleml_glmnet_ranger"] <- run_safe_method(
  311. "doubleml_glmnet_ranger",
  312. estimate_doubleml_glmnet_ranger(y.t, z.t, x.t)
  313. )
  314. ATE["doubleml_svm_ranger"] <- run_safe_method(
  315. "doubleml_svm_ranger",
  316. estimate_doubleml_svm_ranger(y.t, z.t, x.t)
  317. )
  318. ATE["tmle_glmnet"] <- run_safe_method(
  319. "tmle_glmnet",
  320. estimate_tmle_glmnet(y.t, z.t, x.t)
  321. )
  322. ATE["glmtrans2old"] <- run_safe_method("glmtrans2old", {
  323. old_alpha<-glmtrans2old(target=ps.target, source = ps.source, family = "binomial", lambda = "lambda.1se", type.measure="deviance",
  324. alpha = 1, nfolds = min(5,nrow(ps.target)), intercept=F, penalty.factor=penalty.factor)
  325. or.t.target<-data.frame(cbind(y.t1,x.t1[,-1]))
  326. names(or.t.target)[1]<-c("y")
  327. or.t.source<-data.frame(cbind(y.s1,x.s1[,-1]))
  328. names(or.t.source)[1]<-c("y")
  329. old_beta.t <- glmtrans2old(target = or.t.target, source = or.t.source, family = "gaussian", lambda = "lambda.1se", type.measure="mse",
  330. alpha = 1, nfolds = min(5,length(y.t1)), intercept=T, penalty.factor=penalty.factor)
  331. or.c.target<-data.frame(cbind(y.t0,x.t0[,-1]))
  332. names(or.c.target)[1]<-c("y")
  333. or.c.source<-data.frame(cbind(y.s0,x.s0[,-1]))
  334. names(or.c.source)[1]<-c("y")
  335. old_beta.c <- glmtrans2old(target = or.c.target, source = or.c.source, family = "gaussian", lambda = "lambda.1se", type.measure="mse",
  336. alpha = 1, nfolds = min(5,length(y.t0)), intercept=T, penalty.factor=penalty.factor)
  337. dr(y.t,z.t,x.t,old_alpha$beta,old_beta.t$beta,old_beta.c$beta)
  338. })
  339. method.start <- proc.time()[3]
  340. tran_alpha3<-glmtrans2(target=ps.target, source = ps.source, family = "binomial", lambda = "lambda.1se", type.measure="deviance",
  341. alpha = 1, nfolds = min(5,nrow(ps.target)), intercept=F, penalty.factor=penalty.factor)
  342. or.t.target<-data.frame(cbind(y.t1,x.t1[,-1]))
  343. names(or.t.target)[1]<-c("y")
  344. or.t.source<-data.frame(cbind(y.s1,x.s1[,-1]))
  345. names(or.t.source)[1]<-c("y")
  346. tran_beta3.t <- glmtrans2(target = or.t.target, source = or.t.source, family = "gaussian", lambda = "lambda.1se", type.measure="mse",
  347. alpha = 1, nfolds = min(5,length(y.t1)), intercept=T, penalty.factor=penalty.factor)
  348. or.c.target<-data.frame(cbind(y.t0,x.t0[,-1]))
  349. names(or.c.target)[1]<-c("y")
  350. or.c.source<-data.frame(cbind(y.s0,x.s0[,-1]))
  351. names(or.c.source)[1]<-c("y")
  352. tran_beta3.c <- glmtrans2(target = or.c.target, source = or.c.source, family = "gaussian", lambda = "lambda.1se", type.measure="mse",
  353. alpha = 1, nfolds = min(5,length(y.t0)), intercept=T, penalty.factor=penalty.factor)
  354. if (SAVE_REG_DIAG) {
  355. REG_DIAG <<- rbind(
  356. REG_DIAG,
  357. add_reg_diag(tran_alpha3, "DSTCL", "PS"),
  358. add_reg_diag(tran_beta3.t, "DSTCL", "OR_treated"),
  359. add_reg_diag(tran_beta3.c, "DSTCL", "OR_control")
  360. )
  361. }
  362. ATE["dstcl_transfer"] <- dr(y.t,z.t,x.t,tran_alpha3$beta,tran_beta3.t$beta,tran_beta3.c$beta)
  363. record_method_time("dstcl_transfer", proc.time()[3] - method.start)
  364. return(ATE)
  365. }
  366. bootstrap_one <- function(i) {
  367. SAVE_REG_DIAG <<- FALSE
  368. CURRENT_STAGE <<- "bootstrap"
  369. CURRENT_SIM <<- sim_id_boot
  370. MAIN_METHOD_TIME_SUM <<- matrix(0, 1, length(METHOD_NAMES))
  371. MAIN_METHOD_TIME_COUNT <<- matrix(0, 1, length(METHOD_NAMES))
  372. BOOT_METHOD_TIME_SUM <<- matrix(0, sim_id_boot, length(METHOD_NAMES))
  373. BOOT_METHOD_TIME_COUNT <<- matrix(0, sim_id_boot, length(METHOD_NAMES))
  374. colnames(BOOT_METHOD_TIME_SUM) <<- METHOD_NAMES
  375. colnames(BOOT_METHOD_TIME_COUNT) <<- METHOD_NAMES
  376. data_ss <- data_s_boot[sample(1:m,m,replace=TRUE),]
  377. data_tt <- data_t_boot[sample(1:n,n,replace=TRUE),]
  378. fit.i <- try(estimator(data_ss,data_tt), silent = TRUE)
  379. if (inherits(fit.i, "try-error")) {
  380. list(
  381. index = i,
  382. ate = rep(NA, length(METHOD_NAMES)),
  383. time_sum = rep(0, length(METHOD_NAMES)),
  384. time_count = rep(0, length(METHOD_NAMES)),
  385. error = as.character(fit.i)
  386. )
  387. } else {
  388. list(
  389. index = i,
  390. ate = fit.i,
  391. time_sum = as.numeric(BOOT_METHOD_TIME_SUM[sim_id_boot, ]),
  392. time_count = as.numeric(BOOT_METHOD_TIME_COUNT[sim_id_boot, ]),
  393. error = NA_character_
  394. )
  395. }
  396. }
  397. ######################################
  398. ## bootstrap 函数
  399. ######################################
  400. boo <- function(data_s,data_t,B){
  401. ATE_B <- matrix(NA,B,length(METHOD_NAMES))
  402. old.save <- SAVE_REG_DIAG
  403. old.stage <- CURRENT_STAGE
  404. SAVE_REG_DIAG <<- FALSE
  405. CURRENT_STAGE <<- "bootstrap"
  406. on.exit({
  407. SAVE_REG_DIAG <<- old.save
  408. CURRENT_STAGE <<- old.stage
  409. }, add = TRUE)
  410. sim_id <- CURRENT_SIM
  411. cat(" Bootstrap 1 to", B, "of", B,
  412. "in simulation", sim_id, "using", BOOT_CORES, "workers with load balancing\n")
  413. flush.console()
  414. if (is.null(BOOT_CLUSTER)) {
  415. data_s_boot <<- data_s
  416. data_t_boot <<- data_t
  417. sim_id_boot <<- sim_id
  418. boot_res <- lapply(seq_len(B), bootstrap_one)
  419. rm(data_s_boot, data_t_boot, sim_id_boot, envir = .GlobalEnv)
  420. } else {
  421. data_s_boot <- data_s
  422. data_t_boot <- data_t
  423. sim_id_boot <- sim_id
  424. parallel::clusterExport(
  425. BOOT_CLUSTER,
  426. varlist = c("data_s_boot", "data_t_boot", "sim_id_boot"),
  427. envir = environment()
  428. )
  429. boot_res <- parallel::parLapplyLB(BOOT_CLUSTER, seq_len(B), bootstrap_one)
  430. }
  431. for (res in boot_res) {
  432. ATE_B[res$index, ] <- res$ate
  433. BOOT_METHOD_TIME_SUM[sim_id, ] <<- BOOT_METHOD_TIME_SUM[sim_id, ] + res$time_sum
  434. BOOT_METHOD_TIME_COUNT[sim_id, ] <<- BOOT_METHOD_TIME_COUNT[sim_id, ] + res$time_count
  435. }
  436. return(ATE_B)
  437. }
  438. ######################################
  439. ## 主模拟循环
  440. ######################################
  441. EST <- matrix(NA,nsim,length(METHOD_NAMES))
  442. cover<- matrix(NA,nsim,length(METHOD_NAMES))
  443. colnames(EST) <- METHOD_NAMES
  444. colnames(cover) <- METHOD_NAMES
  445. True_ate<-rep(-2,length(METHOD_NAMES))
  446. BOOT_CLUSTER <- init_boot_cluster()
  447. on.exit({
  448. if (!is.null(BOOT_CLUSTER)) {
  449. parallel::stopCluster(BOOT_CLUSTER)
  450. }
  451. }, add = TRUE)
  452. for(k in 1:nsim){
  453. sim.start <- proc.time()[3]
  454. cat("Starting simulation", k, "of", nsim, "\n")
  455. flush.console()
  456. data<-gen.transfer.train(m,n,p,alpha1,alpha2,beta1.t,beta1.c,beta2.t,beta2.c,scenario="ps_correct")
  457. data_s<-as.data.frame(data[["data.source"]])
  458. data_t<-as.data.frame(data[["data.target"]])
  459. CURRENT_SIM <<- k
  460. CURRENT_STAGE <<- "main"
  461. est.start <- proc.time()[3]
  462. fit.k <- try(estimator(data_s,data_t), silent = TRUE)
  463. ESTIMATOR_TIME[k] <- proc.time()[3] - est.start
  464. if (inherits(fit.k, "try-error")) {
  465. cat("Simulation", k, "main estimator failed:\n", as.character(fit.k), "\n")
  466. flush.console()
  467. EST[k,] <- NA
  468. RUN_STATUS <- rbind(
  469. RUN_STATUS,
  470. data.frame(sim = k, status = "failed", message = as.character(fit.k),
  471. estimator_runtime_sec = ESTIMATOR_TIME[k],
  472. bootstrap_runtime_sec = NA,
  473. total_runtime_sec = NA)
  474. )
  475. } else {
  476. EST[k,] <- fit.k
  477. RUN_STATUS <- rbind(
  478. RUN_STATUS,
  479. data.frame(sim = k, status = "ok", message = NA,
  480. estimator_runtime_sec = ESTIMATOR_TIME[k],
  481. bootstrap_runtime_sec = NA,
  482. total_runtime_sec = NA)
  483. )
  484. }
  485. boot.start <- proc.time()[3]
  486. ATE_B<-boo(data_s,data_t,B)
  487. BOOTSTRAP_TIME[k] <- proc.time()[3] - boot.start
  488. upper<-apply(ATE_B,2,function(x)quantile(x,0.975,na.rm=TRUE))
  489. lower<-apply(ATE_B,2,function(x)quantile(x,0.025,na.rm=TRUE))
  490. cover[k,]<-ifelse(((True_ate-lower)>-1e-06)&((True_ate-upper)<1e-06),1,0)
  491. TOTAL_TIME[k] <- proc.time()[3] - sim.start
  492. RUN_STATUS[RUN_STATUS$sim == k, "bootstrap_runtime_sec"] <- BOOTSTRAP_TIME[k]
  493. RUN_STATUS[RUN_STATUS$sim == k, "total_runtime_sec"] <- TOTAL_TIME[k]
  494. cat("Completed", k, "of", nsim,
  495. "simulations; estimator:", round(ESTIMATOR_TIME[k], 2), "sec;",
  496. "bootstrap:", round(BOOTSTRAP_TIME[k], 2), "sec;",
  497. "total:", round(TOTAL_TIME[k], 2), "sec\n")
  498. sim_method_total <- BOOT_METHOD_TIME_SUM[k, ]
  499. sim_method_count <- BOOT_METHOD_TIME_COUNT[k, ]
  500. sim_method_mean <- ifelse(sim_method_count > 0, sim_method_total / sim_method_count, NA)
  501. top_methods <- order(sim_method_total, decreasing = TRUE)[1:min(3, length(METHOD_NAMES))]
  502. cat(" Slowest bootstrap methods in simulation", k, ":\n")
  503. for (idx in top_methods) {
  504. if (sim_method_count[idx] > 0) {
  505. cat(" -", METHOD_NAMES[idx],
  506. "total:", round(sim_method_total[idx], 2), "sec;",
  507. "mean:", round(sim_method_mean[idx], 2), "sec;",
  508. "n:", sim_method_count[idx], "\n")
  509. }
  510. }
  511. flush.console()
  512. }
  513. ######################################
  514. ## 结果整理与保存
  515. ######################################
  516. True_ate <- -2
  517. BIAS<-colMeans(EST,na.rm=TRUE)-True_ate
  518. SD<-apply(EST,2,sd,na.rm=TRUE)
  519. MSE<-apply(EST,2,function(x)mean((x-True_ate)^2,na.rm=TRUE))
  520. Coverage<-colMeans(cover,na.rm=TRUE)
  521. result<-data.frame(
  522. "Method"=METHOD_NAMES,
  523. "Bias"=round(BIAS,2),
  524. "SD"=round(SD,2),
  525. "MSE"=round(MSE,2),
  526. "Coverage"=round(Coverage,2)
  527. )
  528. print(result)
  529. runtime_summary <- data.frame(
  530. mean_estimator_runtime_sec = mean(ESTIMATOR_TIME, na.rm = TRUE),
  531. median_estimator_runtime_sec = median(ESTIMATOR_TIME, na.rm = TRUE),
  532. mean_bootstrap_runtime_sec = mean(BOOTSTRAP_TIME, na.rm = TRUE),
  533. median_bootstrap_runtime_sec = median(BOOTSTRAP_TIME, na.rm = TRUE),
  534. mean_total_runtime_sec = mean(TOTAL_TIME, na.rm = TRUE),
  535. median_total_runtime_sec = median(TOTAL_TIME, na.rm = TRUE),
  536. sd_total_runtime_sec = sd(TOTAL_TIME, na.rm = TRUE),
  537. min_total_runtime_sec = min(TOTAL_TIME, na.rm = TRUE),
  538. max_total_runtime_sec = max(TOTAL_TIME, na.rm = TRUE),
  539. n_failed = sum(RUN_STATUS$status != "ok"),
  540. failure_rate = mean(RUN_STATUS$status != "ok")
  541. )
  542. main_method_total <- colSums(MAIN_METHOD_TIME_SUM, na.rm = TRUE)
  543. main_method_count <- colSums(MAIN_METHOD_TIME_COUNT, na.rm = TRUE)
  544. bootstrap_method_total <- colSums(BOOT_METHOD_TIME_SUM, na.rm = TRUE)
  545. bootstrap_method_count <- colSums(BOOT_METHOD_TIME_COUNT, na.rm = TRUE)
  546. method_time_summary <- data.frame(
  547. method_index = seq_along(METHOD_NAMES),
  548. method = METHOD_NAMES,
  549. main_total_sec = main_method_total,
  550. main_count = main_method_count,
  551. main_mean_sec = ifelse(main_method_count > 0, main_method_total / main_method_count, NA),
  552. bootstrap_total_sec = bootstrap_method_total,
  553. bootstrap_count = bootstrap_method_count,
  554. bootstrap_mean_sec = ifelse(bootstrap_method_count > 0, bootstrap_method_total / bootstrap_method_count, NA)
  555. )
  556. bootstrap_method_time_by_sim <- do.call(
  557. rbind,
  558. lapply(1:nsim, function(sim_id) {
  559. total <- BOOT_METHOD_TIME_SUM[sim_id, ]
  560. count <- BOOT_METHOD_TIME_COUNT[sim_id, ]
  561. data.frame(
  562. sim = sim_id,
  563. method_index = seq_along(METHOD_NAMES),
  564. method = METHOD_NAMES,
  565. bootstrap_total_sec = as.numeric(total),
  566. bootstrap_count = as.numeric(count),
  567. bootstrap_mean_sec = ifelse(count > 0, as.numeric(total) / as.numeric(count), NA)
  568. )
  569. })
  570. )
  571. if (nrow(REG_DIAG) > 0) {
  572. reg_summary <- aggregate(
  573. cbind(nfolds_used,
  574. nonzero_source, nonzero_delta, nonzero_final,
  575. prop_nonzero_source, prop_nonzero_delta, prop_nonzero_final,
  576. l1_source, l1_delta, l1_final,
  577. source_lambda, correction_lambda,
  578. n_try_correction) ~ method + component,
  579. data = REG_DIAG,
  580. FUN = function(x) mean(x, na.rm = TRUE),
  581. na.action = na.pass
  582. )
  583. reg_lambda_summary <- aggregate(
  584. lambda_rule ~ method + component,
  585. data = REG_DIAG,
  586. FUN = function(x) {
  587. x <- unique(na.omit(x))
  588. if (length(x) == 0) NA_character_ else paste(x, collapse = ";")
  589. },
  590. na.action = na.pass
  591. )
  592. reg_summary <- merge(
  593. reg_summary,
  594. reg_lambda_summary,
  595. by = c("method", "component"),
  596. all.x = TRUE
  597. )
  598. } else {
  599. reg_summary <- data.frame()
  600. }
  601. write.csv(result,file = file.path(output_dir, "result_main_ps_50_2000_200_6.csv"))
  602. write.csv(EST,file = file.path(output_dir, "EST_main_ps_50_2000_200_6.csv"))
  603. write.csv(cover,file = file.path(output_dir, "cover_main_ps_50_2000_200_6.csv"))
  604. write.csv(REG_DIAG, file = file.path(output_dir, "regularization_diagnostics_raw_main_ps_50_2000_200_6.csv"), row.names = FALSE)
  605. write.csv(reg_summary, file = file.path(output_dir, "regularization_diagnostics_summary_main_ps_50_2000_200_6.csv"), row.names = FALSE)
  606. write.csv(RUN_STATUS, file = file.path(output_dir, "run_status_main_ps_50_2000_200_6.csv"), row.names = FALSE)
  607. write.csv(runtime_summary, file = file.path(output_dir, "runtime_summary_main_ps_50_2000_200_6.csv"), row.names = FALSE)
  608. write.csv(method_time_summary, file = file.path(output_dir, "method_time_summary_main_ps_50_2000_200_6.csv"), row.names = FALSE)
  609. write.csv(bootstrap_method_time_by_sim, file = file.path(output_dir, "bootstrap_method_time_main_ps_50_2000_200_6.csv"), row.names = FALSE)

simulate_dstcl_main.R at commit cca9e24, no license · at the source

Overview

Authors: Yunxin Shi1, Lulu Pan1, Yu Hu1, Yongfu Yu1, Guoyou Qin1
  1. Department of Biostatistics, Key Laboratory of Public Health Safety of Ministry of Education, NHC Key Laboratory for Health Technology Assessment, School of Public Health, Fudan University, Shanghai, China
Institutions: Fudan University (China)
Journal: PLoS computational biology, volume 22, issue 8, article e1014706
Dates: received 20 February 2026; accepted 11 August 2026; published online 24 August 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1371/journal.pcbi.1014706 · PMID 42636277 · PMCID PMC13533430 · OpenAlex W7204095745
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: human (organism), Alzheimer's / dementia (population)
Methods: Machine learning, Statistics
MeSH: Alzheimer Disease*, Amyloid beta-Peptides, Biomarkers, Black or African American, Computational Biology, Computer Simulation, Humans, Neuroimaging, Peptide Fragments (* major topic)
Journal subjects: People and places, Population groupings, Ethnicities, African American people, Medicine and Health Sciences, Mental Health and Psychiatry, Dementia, Alzheimer's Disease, Neurology, Medical Conditions, Neurodegenerative Diseases, Research and Analysis Methods, Simulation and Modeling, Computer and Information Sciences, Artificial Intelligence, Machine Learning, Biology and Life Sciences, Anatomy, Body Fluids, Cerebrospinal Fluid, Physiology, Nervous System, Cell biology, Chromosome biology, Chromatin, Chromatin modification, DNA methylation, Genetics, Epigenetics, Gene expression, DNA, DNA modification, Biochemistry, Nucleic acids, Biomarkers, Health Care, Health Care Policy, Treatment Guidelines
Topic: Bayesian Modeling and Causal Inference (Artificial Intelligence, Computer Science), according to OpenAlex
Funding: National Natural Science Foundation of China (82473724, 82273730); Shanghai Municipal Science and Technology Major Project (ZD2021CY001); Shanghai Talent Programs (BJKJ2024050); Shanghai Education Development Foundation and Shanghai Municipal Education Commission
Citations: not cited yet (Europe PMC); 27 references in the paper

Abstract

Amyloid-Beta 42 (ABeta42) is a key biomarker of cerebral amyloidosis in Alzheimer’s disease, and estimating its causal effect on subsequent cognitive outcomes is important for understanding disease progression in racial minority populations, such as African Americans. However, causal effect analyses in such populations are often challenged by limited sample sizes, leading to biased or unstable estimates when only target-population data are used. Existing transfer causal learning methods borrow information from a larger related source domain, but may be unstable when source-domain estimation is high-dimensional or when irrelevant covariates introduce noise into transferred nuisance models. We propose a double shrinkage transfer causal learning (DSTCL) estimator that regularizes both the initial source domain estimation and the source-target parameter differences, and then estimates causal effects using a doubly robust framework. We evaluated DSTCL in simulations under varying source sample sizes, inter-domain similarities, covariate dimensions, and other settings, and then applied it to the Alzheimer’s Disease Neuroimaging Initiative dataset using African American participants as the target domain and non-Hispanic White participants as the source domain. In simulations, DSTCL achieved small bias, low mean squared error, and stable confidence interval coverage, generally outperforming competing methods. In the ADNI application, lower baseline ABeta42, reflecting greater amyloid burden, was associated with worse 12-month cognitive performance among African American participants, with DSTCL producing the narrowest confidence interval among the methods compared. These findings suggest that DSTCL provides a practical framework for transfer causal inference in biomedical studies with limited target population.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above, with 5 matches between paragraphs and lines of code.

LESWinnie/DSTCL

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: cca9e2446b942bf93aad7eeeecc96ec807bee1fc, 13 July 2026
Languages: R (4)
Size: 5 files, 4 scripts
Software Heritage: not archived
Found in: “Data Availability”
Holds: README
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: glmnet (2 files), tidyverse (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
5 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 4 scripts, each with its path and the digest of its content;
  • 5 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data Availability

The R code for implementing DSTCL, generating the simulated data, and reproducing the analyses is publicly available on GitHub at https://github.com/LESWinnie/DSTCL. The simulated datasets can be generated using the code provided in the repository. The data used in the real-data application were obtained from the ADNI database (https://adni.loni.usc.edu/). Under the ADNI Data Use Agreement, participant-level data cannot be redistributed by the authors, but qualified researchers may apply for access at https://adni.loni.usc.edu/data-samples/adni-data/. The authors had no special access privileges.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 5 authors, 9 MeSH terms, 4 funders, 23 references.

Cite

This paper

Shi, Y., Pan, L., Hu, Y., Yu, Y., & Qin, G. (2026). Double shrinkage transfer causal learning: An application to alzheimer's disease. PLoS computational biology, 22(8), e1014706. https://doi.org/10.1371/journal.pcbi.1014706

BibTeX

@article{shi2026double,
author = {Shi, Yunxin and Pan, Lulu and Hu, Yu and Yu, Yongfu and Qin, Guoyou},
title = {{Double shrinkage transfer causal learning: An application to alzheimer's disease}},
journal = {PLoS computational biology},
year = {2026},
month = aug,
volume = {22},
number = {8},
pages = {e1014706},
publisher = {PLOS},
issn = {1553-734X},
doi = {10.1371/journal.pcbi.1014706},
url = {https://doi.org/10.1371/journal.pcbi.1014706},
pmid = {42636277},
pmcid = {PMC13533430}
}

RIS

TY - JOUR
AU - Shi, Yunxin
AU - Pan, Lulu
AU - Hu, Yu
AU - Yu, Yongfu
AU - Qin, Guoyou
TI - Double shrinkage transfer causal learning: An application to alzheimer's disease
T2 - PLoS computational biology
J2 - PLoS Comput Biol
PY - 2026
DA - 2026/08/24
VL - 22
IS - 8
SP - e1014706
SN - 1553-734X
PB - PLOS
DO - 10.1371/journal.pcbi.1014706
UR - https://doi.org/10.1371/journal.pcbi.1014706
LA - en
ER -

CSL-JSON

{
"id": "10.1371/journal.pcbi.1014706",
"type": "article-journal",
"title": "Double shrinkage transfer causal learning: An application to alzheimer's disease",
"container-title": "PLoS computational biology",
"author": [
{
"family": "Shi",
"given": "Yunxin"
},
{
"family": "Pan",
"given": "Lulu"
},
{
"family": "Hu",
"given": "Yu"
},
{
"family": "Yu",
"given": "Yongfu"
},
{
"family": "Qin",
"given": "Guoyou"
}
],
"container-title-short": "PLoS Comput Biol",
"volume": "22",
"issue": "8",
"page": "e1014706",
"DOI": "10.1371/journal.pcbi.1014706",
"PMID": "42636277",
"PMCID": "PMC13533430",
"ISSN": "1553-734X",
"publisher": "PLOS",
"URL": "https://doi.org/10.1371/journal.pcbi.1014706",
"language": "en",
"issued": {
"date-parts": [
[
2026,
8,
24
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1186/s13073-026-01698-8 [code]
From aging to Alzheimer's disease: concordant brain DNA methylation changes in late life.
Journal: Genome medicine
In common: tidyverse, Alzheimer's / dementia, 3 references
[2] doi:10.3390/diagnostics16132029
FLAME: Federated Learning and Aggregated Multi-Model Ensemble for Multi-Class Alzheimer's Disease Stage Classification from Structured Clinical Data.
Journal: Diagnostics (Basel, Switzerland)
In common: Alzheimer's / dementia, 3 references
[3] doi:10.1038/s41586-026-10877-x [code]
Human brain organoids record the passage of time over multiple years.
Journal: Nature
In common: glmnet, tidyverse, 1 reference
[4] doi:10.1016/j.isci.2026.116439 [code]
Decoding the role of transcriptomic clocks in the human prefrontal cortex.
Journal: iScience
In common: glmnet, tidyverse, 1 reference
[5] doi:10.1038/s41380-026-03686-1 [code]
Early oligodendrocyte dysfunction signature in Alzheimer's disease: Insights from DNA methylomics and transcriptomics.
Journal: Molecular psychiatry
In common: tidyverse, Alzheimer's / dementia, 2 references
[6] doi:10.3389/fnagi.2026.1847611 [code]
APOE ε4-associated hippocampal atrophy trajectories across the Alzheimer's disease continuum: a systematic review, meta-analysis, and longitudinal validation.
Journal: Frontiers in aging neuroscience
In common: tidyverse, Alzheimer's / dementia, 2 references
[7] doi:10.1080/20002297.2026.2705667 [code]
Oral microbiota dysbiosis related to the cortical thinning and cognitive impairment in cerebral small vessel disease.
Journal: Journal of oral microbiology
In common: glmnet, tidyverse, Alzheimer's / dementia
[8] doi:10.1177/13872877261471049 [code]
Predicting future brain atrophy based on longitudinal MRI.
Journal: Journal of Alzheimer's disease : JAD
In common: glmnet, tidyverse, Alzheimer's / dementia
[9] doi:10.1002/advs.76205 [code]
CHCHD10 Mitigates Alzheimer's Disease-Related Phenotypes in Association With Epigenetic Remodeling in Directly Reprogrammed Neurons.
Journal: Advanced science (Weinheim, Baden-Wurttemberg, Germany)
In common: glmnet, tidyverse, Alzheimer's / dementia
[10] doi:10.1038/s43587-026-01149-4 [code]
The blood metabolome of brain health in midlife and influences of genes, microbiome and exposome.
Journal: Nature aging
In common: glmnet, tidyverse, Alzheimer's / dementia

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.