OSCR

Integrated Multi-Tissue Transcriptomics Reveals Antagonistic Pleiotropy in Aging and Alzheimer's Disease.

Code ↔ Paper

18 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.

14 blocks of code here have a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.

The 18 matches
  1. [1] § Methods › WGCNA analysis and AP module/gene scoring ↔ 10_modules_AP.R, lines 316 to 342 · score 0.87 · TOMType, mergeCutHeight, minModuleSize, soft thresholding power, networkType, WGCNA · block oscr:b:87R9FH40D90CR-R · Report a mismatch
  2. [2] § Methods › Functional enrichment of AP-derived gene sets ↔ 09_go_kegg_enrichment.R, lines 67 to 121 · score 0.81 · clusterProfiler, p.adjust, hsa, simplify, CC, MF · block oscr:b:HFKJ10PCGM80T-L · Report a mismatch
  3. [3] § Methods › Cell-state enrichment analysis and cell type-adjusted differential expression ↔ 07_optional_gsva_deconv.R, lines 209 to 229 · score 0.81 · C8 brain cell, Brain cell state, neuron, pericyte, endothelial, excitatory · block oscr:b:D6QPRG8R4NX9C-J · Report a mismatch
  4. [4] § Methods › Functional enrichment of AP-derived gene sets ↔ withDevelopment_section.R, lines 1318 to 1444 · score 0.81 · Entrez IDs, clusterProfiler, hsa, CC, MF, BP · block oscr:b:J72ZZAN08JQG6-X · Report a mismatch
  5. [5] § Methods › Pathway and TF analyses ↔ 05_tf_activity.R, lines 290 to 345 · score 0.81 · TF activities, AP overlap, AP weighted, DoRothEA, TFs, regulons · block oscr:b:A8MD1V1G78DAH-M · Report a mismatch
  6. [6] § Methods › WGCNA analysis and AP module/gene scoring ↔ 10_modules_AP.R, lines 316 to 342 · score 0.79 · merge cut height, soft thresholding power, module AP, module gene, WGCNA, network · block oscr:b:87R9FH40D90CR-R · Report a mismatch
  7. [7] § Methods › Gene classification, prioritization, and AP metrics ↔ 02_consensus_meta.R, lines 89 to 158 · score 0.75 · divergence score, discordant Age, shared score, log2FC, log10, consensus · block oscr:b:AS2A7TJXYE1ZE-0 · Report a mismatch
  8. [8] § Methods › Pathway and TF analyses ↔ 03_pathway_antagonism.R, lines 16 to 39 · score 0.69 · fgseaMultilevel, fgseaSimple, permutations, NES, Pathway, antagonism · block oscr:b:N1ETA835A24GQ-D · Report a mismatch
  9. [9] § Methods › WGCNA analysis and AP module/gene scoring ↔ 10_modules_AP.R, lines 807 to 845 · score 0.66 · ego networks, scoring genes, AP class, AP scores, hub, exported · block oscr:b:5VGH7A093MRNC-K · Report a mismatch
  10. [10] § Methods › Covariate and brain-only sensitivity audits ↔ 04_ap_candidates.R, lines 665 to 718 · score 0.60 · AD brain meta, aging meta, AP candidates, filtered, prioritization, class · block oscr:b:YJ88QKMFJFEVX-3 · Report a mismatch
  11. [11] § Methods › Cross-condition integration and meta-analysis ↔ 01_prepare_universe.R, lines 71 to 122 · score 0.58 · HGNC symbols, gene symbol, log2FC, Ensembl · block oscr:b:F9P5SQBPX1D0W-8 · Report a mismatch
  12. [12] § Methods › Gene classification, prioritization, and AP metrics ↔ 02_consensus_meta.R, lines 89 to 158 · score 0.58 · Aging pleiotropy, aging contrasts, log2FC, consensus, prioritization, AD · block oscr:b:AS2A7TJXYE1ZE-0 · Report a mismatch
  13. [13] § Methods › Cross-condition integration and meta-analysis ↔ 04_ap_candidates.R, lines 156 to 189 · score 0.57 · HGNC symbols, gene symbol, log2fc, Ensembl, AP · block oscr:b:B1DG8PJJ4VZNY-3 · Report a mismatch
  14. [14] § Results › TF activity antagonism between healthy aging and AD ↔ 05_tf_activity.R, lines 290 to 345 · score 0.55 · TF activity, DoRothEA, regulons, NES, map, antagonism · block oscr:b:A8MD1V1G78DAH-M · Report a mismatch
  15. [15] § Results › Cell state-adjusted robustness of AD-associated AP signals ↔ 07_optional_gsva_deconv.R, lines 209 to 229 · score 0.53 · Cell state, endothelial, excitatory, astrocyte, inhibitory, oligodendrocyte · block oscr:b:D6QPRG8R4NX9C-J · Report a mismatch
  16. [16] § Results › Integrated hallmark pathway across brain aging and AD ↔ utils.R, lines 109 to 117 · score 0.53 · SharedDown, SharedUp, AP Vulnerability, AP Resilience, quadrant, pathways · block oscr:b:XWF0NMDH79TQZ-K · Report a mismatch
  17. [17] § Results › Integrated hallmark pathway across brain aging and AD ↔ 05_tf_activity.R, lines 147 to 155 · score 0.52 · SharedDown, SharedUp, AP Vulnerability, AP Resilience, quadrant, map · block oscr:b:YCDH1V3F0N7T0-8 · Report a mismatch
  18. [18] § Methods › WGCNA analysis and AP module/gene scoring ↔ 10_modules_AP.R, lines 1 to 60 · score 0.51 · aging samples, finite, young, GSE48350, WGCNA, Weighted · block oscr:b:84MXGGKEN509Z-8 · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

R · 1,242 lines · 59 KB · no license · 4 matches

  1. #!/usr/bin/env Rscript
  2. # =============================================================================
  3. # 10_modules_AP_consensus.R — UPDATED FULL SCRIPT (robust covariates)
  4. # Uses ONLY:
  5. # - results_aging_brain/GSE48350_samples_ALL_tissues_Young_vs_Old.csv
  6. # (all brain healthy aging samples; includes young + old; 150 total)
  7. # - results_AD/samples_ALL_tissues_ageGT59.csv (take only rows with group == "AD")
  8. # for sample annotation.
  9. # =============================================================================
  10. suppressPackageStartupMessages({
  11. library(dplyr); library(readr); library(stringr); library(tidyr)
  12. library(purrr); library(tibble); library(ggplot2); library(scales)
  13. library(WGCNA)
  14. suppressWarnings({
  15. ok_igraph <- requireNamespace("igraph", quietly=TRUE)
  16. ok_ggraph <- requireNamespace("ggraph", quietly=TRUE) && requireNamespace("tidygraph", quietly=TRUE)
  17. })
  18. })
  19. set.seed(2371)
  20. allowWGCNAThreads()
  21. options(stringsAsFactors = FALSE)
  22. # ------------------ Config / IO ----------------------------------------------
  23. source("utils.R")
  24. load(".config_env.RData") # expects: AGE_BRAIN_EXPR_RDS, AD_BRAIN_EXPR_RDS, outdir, AP_COLORS, PNG_DPI, REGION_P_FDR
  25. dir.create(file.path(outdir, "wgcna"), FALSE, TRUE)
  26. .dirnets <- file.path(outdir, "wgcna", "networks"); dir.create(.dirnets, FALSE, TRUE)
  27. # CSVs (override via env)
  28. AD_SAMPLES_CSV <- Sys.getenv("AD_SAMPLES_CSV",
  29. unset = file.path("results_AD","samples_ALL_tissues_ageGT59.csv"))
  30. HEALTHY_SAMPLES_CSV <- Sys.getenv("HEALTHY_SAMPLES_CSV",
  31. unset = file.path("results_aging_brain","GSE48350_samples_ALL_tissues_Young_vs_Old.csv"))
  32. # Tunables
  33. CONSENSUS_TOPK_GENES <- as.integer(Sys.getenv("CONSENSUS_TOPK_GENES", unset="15000"))
  34. MIN_FINITE_PROP <- as.numeric(Sys.getenv("MIN_FINITE_PROP", unset="0.80"))
  35. MIN_FINITE_MIN <- as.integer(Sys.getenv("MIN_FINITE_MIN", unset="12"))
  36. NETWORK_MAX_GENES <- as.integer(Sys.getenv("NETWORK_MAX_GENES", unset="400"))
  37. EDGE_TOPK_PER_GENE <- as.integer(Sys.getenv("EDGE_TOPK_PER_GENE", unset="5"))
  38. EDGE_MIN_TOM <- as.numeric(Sys.getenv("EDGE_MIN_TOM", unset="0.05"))
  39. EDGE_MIN_ADJ <- as.numeric(Sys.getenv("EDGE_MIN_ADJ", unset="0.10"))
  40. TOP_HUBS_PER_MODULE <- as.integer(Sys.getenv("TOP_HUBS_PER_MODULE", unset="10"))
  41. MIN_MODULE_SIZE <- as.integer(Sys.getenv("MIN_MODULE_SIZE", unset="120"))
  42. MIN_EDGES_TARGET <- as.integer(Sys.getenv("MIN_EDGES_TARGET", unset="40"))
  43. MIN_EDGE_MIN_TOM <- as.numeric(Sys.getenv("MIN_EDGE_MIN_TOM", unset="0.01"))
  44. MIN_EDGE_MIN_ADJ <- as.numeric(Sys.getenv("MIN_EDGE_MIN_ADJ", unset="0.02"))
  45. FORCE_EXPORT_IF_EMPTY<- as.logical(Sys.getenv("FORCE_EXPORT_IF_EMPTY",unset="TRUE"))
  46. TOP_EXPORT <- as.integer(Sys.getenv("AP_TOP_MODULE_EXPORT", unset="6"))
  47. TOP_EGO_PER_CLASS <- as.integer(Sys.getenv("TOP_EGO_PER_CLASS", unset="15"))
  48. # Optional weightings
  49. AP_SCORE_USE_KME <- as.logical(Sys.getenv("AP_SCORE_USE_KME", unset="FALSE"))
  50. AP_MODULE_USE_KME_WEIGHTS <- as.logical(Sys.getenv("AP_MODULE_USE_KME_WEIGHTS", unset="TRUE"))
  51. `%||%` <- function(a, b) if (!is.null(a) && length(a)>0 && !all(is.na(a))) a else b
  52. log_msg <- function(...) cat(format(Sys.time(), "[%Y-%m-%d %H:%M:%S]"), sprintf(...), "\n")
  53. psafe <- function(p) pmax(pmin(as.numeric(p), 1), .Machine$double.xmin)
  54. stopifnot(file.exists(AGE_BRAIN_EXPR_RDS), file.exists(AD_BRAIN_EXPR_RDS))
  55. stopifnot(file.exists(AD_SAMPLES_CSV), file.exists(HEALTHY_SAMPLES_CSV))
  56. # ------------------ Helpers: IO & metadata -----------------------------------
  57. read_samples_table <- function(path){
  58. tryCatch(readr::read_csv(path, show_col_types=FALSE),
  59. error=function(e) tryCatch(readr::read_tsv(path, show_col_types=FALSE),
  60. error=function(e2) readr::read_delim(path, delim="\t", show_col_types=FALSE)))
  61. }
  62. load_expr_meta <- function(path) {
  63. obj <- readRDS(path)
  64. if (is.list(obj) && all(c("expr","meta") %in% names(obj))) {
  65. expr <- as.matrix(obj$expr); meta <- as.data.frame(obj$meta)
  66. } else if (is.matrix(obj) || is.data.frame(obj)) {
  67. expr <- as.matrix(obj); meta <- data.frame(sample_id=colnames(expr))
  68. } else stop("Unsupported RDS format at ", path)
  69. if (is.null(rownames(expr))) stop("Expression must have rownames=gene identifiers.")
  70. if (!"sample_id" %in% names(meta)) meta$sample_id <- rownames(meta) %||% colnames(expr)
  71. meta <- meta %>% distinct(sample_id, .keep_all=TRUE)
  72. keep <- intersect(colnames(expr), meta$sample_id)
  73. list(expr=expr[, keep, drop=FALSE], meta=meta[match(keep, meta$sample_id), , drop=FALSE])
  74. }
  75. coerce_meta <- function(meta, context=c("healthy","ad")) {
  76. context <- match.arg(context)
  77. nm <- tolower(names(meta))
  78. pick <- function(cands) { i <- which(nm %in% cands); if (length(i)) names(meta)[i[1]] else NA }
  79. age_col <- pick(c("age","age_years","ages","age_at_death","age_at_sampling"))
  80. dz_col <- pick(c("disease","diagnosis","dx","ad_status","group","phenotype"))
  81. sex_col <- pick(c("sex","gender"))
  82. bat_col <- pick(c("batch","plate","run","study_batch"))
  83. reg_col <- pick(c("region","brain_region","tissue","area","region_raw"))
  84. meta$age <- if (!is.na(age_col)) suppressWarnings(as.numeric(meta[[age_col]])) else NA_real_
  85. if (!is.na(dz_col)) {
  86. v <- as.character(meta[[dz_col]])
  87. is_ad <- grepl("\\b(ad|alz|alzheimer|case|patient|disease)\\b", v, TRUE)
  88. is_ctrl <- grepl("\\b(ctrl|control|cn|healthy|normal)\\b", v, TRUE)
  89. meta$disease <- ifelse(is_ad, 1L, ifelse(is_ctrl, 0L, NA_integer_))
  90. } else meta$disease <- if (context=="ad") NA_integer_ else 0L
  91. meta$sex <- if (!is.na(sex_col)) as.character(meta[[sex_col]]) else NA_character_
  92. meta$batch <- if (!is.na(bat_col)) as.character(meta[[bat_col]]) else NA_character_
  93. meta$region <- if (!is.na(reg_col)) as.character(meta[[reg_col]]) else NA_character_
  94. meta$context <- context
  95. meta
  96. }
  97. merge_external_info <- function(meta, csv_path, dataset_label=""){
  98. if (!file.exists(csv_path)) return(meta)
  99. ext <- read_samples_table(csv_path)
  100. nm <- tolower(names(ext))
  101. pick <- function(...) { cands <- c(...); i <- which(nm %in% tolower(cands)); if (length(i)) names(ext)[i[1]] else NA }
  102. idc <- pick("sample_id","gsm","id","sample","geo_accession")
  103. if (is.na(idc)) { log_msg("[%s] No sample_id-like column in %s; skipping merge.", dataset_label, csv_path); return(meta) }
  104. ext <- ext %>% mutate(sample_id = as.character(.data[[idc]]))
  105. agec <- pick("age","age_years","Age","AgeYears")
  106. sexc <- pick("sex","gender")
  107. regc <- pick("region","brain_region","tissue","area","region_raw")
  108. tisc <- pick("tissue","Tissue")
  109. aggc <- pick("age_group","Age_group","AGE_GROUP")
  110. if (!is.na(agec)) ext$age <- suppressWarnings(as.numeric(ext[[agec]]))
  111. if (!is.na(sexc)) ext$sex <- as.character(ext[[sexc]])
  112. if (!is.na(regc)) ext$region <- as.character(ext[[regc]])
  113. if (!is.na(tisc)) ext$tissue <- as.character(ext[[tisc]])
  114. if (!is.na(aggc)) ext$age_group <- as.character(ext[[aggc]])
  115. meta2 <- meta %>%
  116. left_join(ext %>% select(sample_id, any_of(c("age","sex","region","tissue","age_group"))), by="sample_id")
  117. for (col in c("age","sex","region","tissue","age_group")) {
  118. new <- paste0(col, ".y"); old <- paste0(col, ".x")
  119. if (new %in% names(meta2)) { meta2[[col]] <- meta2[[new]] %||% meta2[[old]]; meta2[[new]] <- NULL; meta2[[old]] <- NULL }
  120. }
  121. meta2
  122. }
  123. # ------------------ Cleaning & math ------------------------------------------
  124. harmonize_gene_names <- function(E) {
  125. rn <- rownames(E)
  126. rn <- gsub("\\s+", "", rn)
  127. rn <- gsub("\\.\\d+$", "", rn)
  128. rownames(E) <- toupper(rn)
  129. E
  130. }
  131. dedup_by_maxvar <- function(E) {
  132. rn <- rownames(E)
  133. if (anyDuplicated(rn)) {
  134. idxs <- split(seq_along(rn), rn)
  135. pick <- vapply(idxs, function(ix){ vv <- apply(E[ix,,drop=FALSE], 1, stats::var, na.rm=TRUE); ix[which.max(vv)][1] }, integer(1))
  136. E <- E[pick,,drop=FALSE]; rownames(E) <- names(pick)
  137. }
  138. E
  139. }
  140. median_impute_rows <- function(E) {
  141. for (i in seq_len(nrow(E))) {
  142. v <- E[i,]; ok <- is.finite(v)
  143. if (!all(ok)) { if (any(ok)) { med <- stats::median(v[ok]); v[!ok] <- med; E[i,] <- v } else { E[i,] <- 0 } }
  144. }
  145. E
  146. }
  147. clean_expression <- function(E, name="") {
  148. log_msg("[%s] raw: %s genes x %s samples", name, nrow(E), ncol(E))
  149. E <- harmonize_gene_names(E) |> dedup_by_maxvar()
  150. finite_counts <- rowSums(is.finite(E))
  151. min_needed <- max(MIN_FINITE_MIN, ceiling(MIN_FINITE_PROP * ncol(E)))
  152. keep <- finite_counts >= min_needed
  153. if (!any(keep)) stop(sprintf("[%s] No genes pass finite filter.", name))
  154. E <- E[keep,,drop=FALSE] |> median_impute_rows()
  155. v <- apply(E, 1, stats::var)
  156. E <- E[v > 0,, drop=FALSE]
  157. log_msg("[%s] cleaned: %s genes x %s samples (min finite per gene %s)", name, nrow(E), ncol(E), min_needed)
  158. E
  159. }
  160. sel_top_var_consensus <- function(E1, E2, k=15000, tag="CONS") {
  161. v1 <- apply(E1, 1, stats::var); v2 <- apply(E2, 1, stats::var)
  162. r1 <- rank(-v1, ties.method="average"); r2 <- rank(-v2, ties.method="average")
  163. rs <- r1 + r2; k <- min(k, length(rs))
  164. keep <- names(sort(rs))[seq_len(k)]
  165. log_msg("[%s] choosing top %s / %s shared genes by consensus variance", tag, k, length(rs))
  166. list(E1=E1[keep,,drop=FALSE], E2=E2[keep,,drop=FALSE], genes=keep)
  167. }
  168. std_me_names <- function(x) paste0("ME", sprintf("%02d", as.integer(gsub("^ME","", as.character(x)))))
  169. # ===== NEW: robust covariate utilities =======================================
  170. sanitize_covars <- function(covs, sample_order=NULL) {
  171. if (is.null(covs) || ncol(covs)==0) return(NULL)
  172. covs <- as.data.frame(covs, stringsAsFactors = FALSE)
  173. if (!is.null(sample_order)) {
  174. covs <- covs[match(sample_order, rownames(covs)), , drop=FALSE]
  175. }
  176. for (j in names(covs)) {
  177. v <- covs[[j]]
  178. if (is.character(v) || is.logical(v)) covs[[j]] <- droplevels(factor(v))
  179. }
  180. keep <- vapply(covs, function(col) any(is.finite(col) | !is.na(col)), logical(1))
  181. covs <- covs[, keep, drop=FALSE]
  182. if (ncol(covs)==0) return(NULL)
  183. drop_j <- logical(ncol(covs))
  184. for (j in seq_along(covs)) {
  185. v <- covs[[j]]
  186. if (is.factor(v)) {
  187. v <- droplevels(v)
  188. if (nlevels(v) < 2) drop_j[j] <- TRUE else covs[[j]] <- v
  189. } else if (is.numeric(v)) {
  190. if (all(!is.finite(v)) || stats::var(v[is.finite(v)])==0) drop_j[j] <- TRUE
  191. }
  192. }
  193. covs <- covs[, !drop_j, drop=FALSE]
  194. if (ncol(covs)==0) return(NULL)
  195. covs
  196. }
  197. drop_collinear <- function(y, covs, thr=0.98) {
  198. if (is.null(covs) || ncol(covs)==0) return(NULL)
  199. mm <- tryCatch(model.matrix(~ . , data=cbind.data.frame(covs)), error=function(e) NULL)
  200. if (is.null(mm)) return(NULL)
  201. mm <- mm[, colnames(mm)!="(Intercept)", drop=FALSE]
  202. if (ncol(mm) <= 1) return(as.data.frame(covs))
  203. C <- suppressWarnings(cor(mm, use="pairwise.complete.obs"))
  204. diag(C) <- 0
  205. to_drop <- c()
  206. while (TRUE) {
  207. mx <- suppressWarnings(max(abs(C), na.rm=TRUE))
  208. if (!is.finite(mx) || mx < thr) break
  209. ij <- which(abs(C) == mx, arr.ind=TRUE)[1,]
  210. jdrop <- colnames(C)[ij[2]]
  211. to_drop <- c(to_drop, jdrop)
  212. keep <- setdiff(colnames(C), to_drop)
  213. if (length(keep) < 2) break
  214. C <- C[keep, keep, drop=FALSE]
  215. }
  216. if (length(to_drop)) {
  217. keep <- setdiff(colnames(mm), to_drop)
  218. return(as.data.frame(covs)) # keep sanitized original; mm used only for checks
  219. }
  220. as.data.frame(covs)
  221. }
  222. # ===== Associations ===========================================================
  223. assoc_linear <- function(y, x, covars=NULL, min_n=4) {
  224. df <- data.frame(y=y, x=x)
  225. if (!is.null(covars)) df <- cbind(df, covars)
  226. df <- df[complete.cases(df), ]
  227. if (nrow(df) < min_n || sd(df$x, na.rm=TRUE) == 0) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
  228. fit <- tryCatch(lm(y ~ x + ., df), error=function(e) NULL)
  229. if (is.null(fit)) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
  230. s <- summary(fit)$coefficients
  231. if (!"x" %in% rownames(s)) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
  232. c(beta=unname(s["x","Estimate"]), se=unname(s["x","Std. Error"]), p=unname(s["x","Pr(>|t|)"]), n=nrow(df))
  233. }
  234. assoc_binary <- function(y, x, covars=NULL, min_n=6) {
  235. df <- data.frame(y=y, x=x)
  236. if (!is.null(covars)) df <- cbind(df, covars)
  237. df <- df[complete.cases(df), ]
  238. ux <- unique(df$x); ux <- ux[is.finite(ux)]
  239. if (length(ux) < 2 || nrow(df) < min_n) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
  240. fit <- tryCatch(lm(y ~ x + ., df), error=function(e) NULL)
  241. if (is.null(fit)) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
  242. s <- summary(fit)$coefficients
  243. if (!"x" %in% rownames(s)) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
  244. c(beta=unname(s["x","Estimate"]), se=unname(s["x","Std. Error"]), p=unname(s["x","Pr(>|t|)"]), n=unname(nrow(df)))
  245. }
  246. fisher_combine_p <- function(pvals){ pvals <- psafe(pvals); 1 - pchisq(-2*sum(log(pvals)), df=2*length(pvals)) }
  247. # ------------------ Load datasets --------------------------------------------
  248. age_ds <- load_expr_meta(AGE_BRAIN_EXPR_RDS); age_ds$meta <- coerce_meta(age_ds$meta, "healthy")
  249. ad_ds <- load_expr_meta(AD_BRAIN_EXPR_RDS); ad_ds$meta <- coerce_meta(ad_ds$meta, "ad")
  250. # Merge external info
  251. # Healthy aging annotations from GSE48350_samples_ALL_tissues_Young_vs_Old.csv (brain)
  252. age_ds$meta <- merge_external_info(age_ds$meta, HEALTHY_SAMPLES_CSV, "GSE48350_healthy")
  253. # AD annotations from samples_ALL_tissues_ageGT59.csv (filter to AD rows only)
  254. ad_ds$meta <- merge_external_info(ad_ds$meta, AD_SAMPLES_CSV, "AD>59")
  255. # AD ids from CSV — take only group == "AD" if 'group' column exists; else assume all rows are AD
  256. ad_csv_raw <- read_samples_table(AD_SAMPLES_CSV)
  257. stopifnot("sample_id" %in% names(ad_csv_raw))
  258. grp_col <- names(ad_csv_raw)[tolower(names(ad_csv_raw))=="group"] %||% NA
  259. ad_csv <- if (is.na(grp_col)) {
  260. log_msg("Note: 'group' not found in AD CSV; assuming all rows are AD.")
  261. ad_csv_raw
  262. } else {
  263. dplyr::filter(ad_csv_raw, grepl("^\\s*AD\\s*$", .data[[grp_col]], ignore.case = TRUE))
  264. }
  265. stopifnot(nrow(ad_csv)>0)
  266. ad_ids <- intersect(colnames(ad_ds$expr), as.character(ad_csv$sample_id))
  267. stopifnot(length(ad_ids)>0)
  268. # ------------------ Healthy-only for CONSENSUS -------------------------------
  269. # Healthy aging cohort from GSE48350 CSV (all brain healthy samples; young + old)
  270. expr_age_healthy <- age_ds$expr[, intersect(colnames(age_ds$expr),
  271. age_ds$meta$sample_id[(age_ds$meta$disease %||% 0) == 0]), drop=FALSE]
  272. # Controls from AD dataset (explicitly exclude AD ids)
  273. expr_ctrl_healthy <- ad_ds$expr[, intersect(colnames(ad_ds$expr),
  274. ad_ds$meta$sample_id[(ad_ds$meta$disease %||% 0) == 0 &
  275. !(ad_ds$meta$sample_id %in% ad_ids)]), drop=FALSE]
  276. EA0 <- clean_expression(expr_age_healthy, "GSE48350_healthy")
  277. EC0 <- clean_expression(expr_ctrl_healthy, "GSE48350_controls")
  278. # Shared gene universe and top-K consensus
  279. genes_shared <- intersect(rownames(EA0), rownames(EC0))
  280. EA_shared <- EA0[genes_shared,,drop=FALSE]
  281. EC_shared <- EC0[genes_shared,,drop=FALSE]
  282. cons <- sel_top_var_consensus(EA_shared, EC_shared, k=CONSENSUS_TOPK_GENES, tag="CONS")
  283. EA <- cons$E1; EC <- cons$E2; genes_cons <- cons$genes
  284. # WGCNA consensus on healthy brains
  285. DatA <- as.data.frame(t(EA)); DatC <- as.data.frame(t(EC))
  286. pick_power <- function(X){ sft <- tryCatch(pickSoftThreshold(X, networkType="signed", verbose=0), error=function(e) NULL); pe <- if (!is.null(sft)) sft$powerEstimate else NA_real_; if (!is.finite(pe)) 6 else pe }
  287. pA <- pick_power(DatA); pC <- pick_power(DatC)
  288. cons_power <- floor(median(c(pA,pC), na.rm=TRUE)); if (!is.finite(cons_power)) cons_power <- 6
  289. log_msg("Consensus soft-threshold power: %s (A=%s, C=%s) with %s genes", cons_power, pA, pC, length(genes_cons))
  290. multiExpr <- list(HealthyA= list(data=DatA), HealthyC= list(data=DatC))
  291. net_cons <- tryCatch(
  292. blockwiseConsensusModules(
  293. multiExpr,
  294. power=cons_power, networkType="signed", TOMType="signed",
  295. minModuleSize=MIN_MODULE_SIZE, reassignThreshold=0,
  296. mergeCutHeight=0.25, numericLabels=TRUE, pamRespectsDendro=FALSE, verbose=2
  297. ),
  298. error=function(e){
  299. log_msg("Consensus failed: %s. Falling back to single-dataset (HealthyA).", conditionMessage(e))
  300. single <- blockwiseModules(DatA, power=cons_power, networkType="signed", TOMType="signed",
  301. minModuleSize=MIN_MODULE_SIZE, reassignThreshold=0,
  302. mergeCutHeight=0.25, numericLabels=TRUE, pamRespectsDendro=FALSE, verbose=2)
  303. list(colors = single$colors, dendrograms = single$dendrograms, blockGenes = single$blockGenes)
  304. }
  305. )
  306. cons_colors <- net_cons$colors; names(cons_colors) <- colnames(DatA)
  307. module_df <- tibble(
  308. gene = names(cons_colors),
  309. module_label = as.integer(cons_colors),
  310. module = std_me_names(as.integer(cons_colors))
  311. )
  312. write_csv(module_df, file.path(outdir, "wgcna", "Consensus_modules_genes.csv"))
  313. # ------------------ Eigengenes helper ----------------------------------------
  314. compute_MEs <- function(EgxS, colors_vec, prefix="") {
  315. if (is.null(EgxS) || ncol(EgxS) < 2) { log_msg("%s compute_MEs: not enough samples (%s).", prefix, ncol(EgxS)); return(NULL) }
  316. genes <- intersect(rownames(EgxS), names(colors_vec))
  317. cols <- colors_vec[genes]; cols <- cols[!is.na(cols) & cols != 0]
  318. genes <- names(cols)
  319. if (length(genes) < 3) { log_msg("%s compute_MEs: <3 non-grey genes.", prefix); return(NULL) }
  320. X <- as.data.frame(t(EgxS[genes, , drop=FALSE]))
  321. MEs <- tryCatch(orderMEs(moduleEigengenes(X, colors=cols, excludeGrey=TRUE)$eigengenes),
  322. error=function(e){ log_msg("%s compute_MEs: %s", prefix, conditionMessage(e)); NULL })
  323. if (!is.null(MEs)) { rownames(MEs) <- rownames(X); colnames(MEs) <- std_me_names(colnames(MEs)) }
  324. MEs
  325. }
  326. # ------------------ Cohorts (age metadata, continuous) -----------------------
  327. age_meta1 <- age_ds$meta %>%
  328. mutate(disease = 0L) %>%
  329. mutate(age = suppressWarnings(as.numeric(age))) %>% filter(is.finite(age))
  330. age_meta2 <- ad_ds$meta %>%
  331. mutate(disease = ifelse(sample_id %in% ad_ids, 1L, disease)) %>%
  332. mutate(disease = ifelse(is.na(disease), 0L, disease)) %>% filter(disease==0) %>%
  333. mutate(age = suppressWarnings(as.numeric(age))) %>% filter(is.finite(age))
  334. E_age1 <- EA[, intersect(colnames(EA), age_meta1$sample_id), drop=FALSE]
  335. E_age2 <- EC[, intersect(colnames(EC), age_meta2$sample_id), drop=FALSE]
  336. # 3) AD vs Control (>59) in GSE48350
  337. ctrl_59_meta <- ad_ds$meta %>%
  338. mutate(disease = ifelse(sample_id %in% ad_ids, 1L, disease),
  339. disease = ifelse(is.na(disease), 0L, disease),
  340. age = suppressWarnings(as.numeric(age))) %>%
  341. filter(disease==0, is.finite(age), age > 59)
  342. ad_59_ids <- intersect(colnames(ad_ds$expr), ad_ids)
  343. region_pick <- function(df){
  344. if ("region_raw" %in% names(df)) df$region_raw else if ("region" %in% names(df)) df$region else if ("tissue" %in% names(df)) df$tissue else rep(NA_character_, nrow(df))
  345. }
  346. ad_meta <- tibble(sample_id = ad_59_ids, disease=1L) %>%
  347. left_join(ad_csv %>% transmute(sample_id=as.character(sample_id),
  348. age = suppressWarnings(as.numeric(age)),
  349. sex = as.character(sex),
  350. region = region_pick(ad_csv),
  351. tissue = as.character(tissue)), by="sample_id")
  352. ctrl_meta <- ctrl_59_meta %>% select(sample_id, age, sex, region, tissue, disease)
  353. ad_ctrl_meta <- bind_rows(ad_meta %>% mutate(context="ad"),
  354. ctrl_meta %>% mutate(context="control")) %>%
  355. mutate(age = suppressWarnings(as.numeric(age)))
  356. AD_full0 <- ad_ds$expr %>% harmonize_gene_names() %>% { .[intersect(rownames(.), genes_cons), , drop=FALSE] }
  357. E_ad_ctrl59 <- AD_full0[, intersect(colnames(AD_full0), ad_ctrl_meta$sample_id), drop=FALSE] |> median_impute_rows()
  358. log_msg("[AD>59] genes=%s samples=%s (AD=%s, CTRL=%s)",
  359. nrow(E_ad_ctrl59), ncol(E_ad_ctrl59),
  360. sum(ad_ctrl_meta$disease==1, na.rm=TRUE),
  361. sum(ad_ctrl_meta$disease==0, na.rm=TRUE))
  362. # ------------------ Module-trait heatmaps (eigengene view) -------------------
  363. mod_trait_heatmap <- function(MEs, meta, mode=c("age","ad"), prefix=""){
  364. if (is.null(MEs) || ncol(MEs)==0) { log_msg("%s heatmap: no eigengenes; skipping.", prefix); return(invisible(NULL)) }
  365. mode <- match.arg(mode)
  366. traits <- if (mode=="age") data.frame(age = suppressWarnings(as.numeric(meta$age)))
  367. else data.frame(disease = suppressWarnings(as.numeric(meta$disease)))
  368. rownames(traits) <- meta$sample_id
  369. keep <- intersect(rownames(MEs), rownames(traits))
  370. if (length(keep) < 3) { log_msg("%s heatmap: <3 overlapping samples. Skipping.", prefix); return(invisible(NULL)) }
  371. MEs <- MEs[keep,,drop=FALSE]; traits <- traits[keep,,drop=FALSE]
  372. safe_cor_p <- function(x, y){
  373. ok <- is.finite(x) & is.finite(y); n <- sum(ok); if (n < 3) return(c(cor=NA_real_, p=NA_real_))
  374. x <- x[ok]; y <- y[ok]; if (sd(x)==0 || sd(y)==0) return(c(cor=NA_real_, p=NA_real_))
  375. r <- suppressWarnings(cor(x, y, method="pearson")); if (!is.finite(r)) return(c(cor=NA_real_, p=NA_real_))
  376. tstat <- r * sqrt((n-2)/(1 - r^2)); p <- 2 * stats::pt(-abs(tstat), df=n-2); c(cor=r, p=p)
  377. }
  378. C <- matrix(NA_real_, nrow=ncol(MEs), ncol=ncol(traits), dimnames=list(colnames(MEs), colnames(traits))); P <- C
  379. for (i in seq_len(ncol(MEs))) for (j in seq_len(ncol(traits))) { res <- safe_cor_p(MEs[,i], traits[,j]); C[i,j] <- res[1]; P[i,j] <- res[2] }
  380. if (all(!is.finite(C))) { log_msg("%s heatmap: all correlations NA. Skipping.", prefix); return(invisible(NULL)) }
  381. lab <- paste0(sprintf("%.2f", C), "\n(", ifelse(is.finite(P), sprintf("%.1e", P), "NA"), ")")
  382. df <- as.data.frame(as.table(C)); names(df) <- c("ME","Trait","Cor"); df$P <- as.vector(P); df$lab <- as.vector(lab)
  383. p <- ggplot(df, aes(Trait, ME, fill=Cor, label=lab)) +
  384. geom_tile() + geom_text(size=3) +
  385. scale_fill_gradient2(low="#2166AC", mid="white", high="#B2182B", midpoint=0, na.value="grey85") +
  386. labs(title=paste0(prefix, " module–trait relationships (", mode, ")"), x=NULL, y=NULL) +
  387. theme_minimal(base_size=12)
  388. safe_ggsave(file.path(outdir, "wgcna", paste0(prefix, "_module_trait_heatmap_", mode)), p, w=6.8, h=0.5 + 0.25*max(1, nrow(C)), dpi=PNG_DPI)
  389. }
  390. # ------------------ Module associations (eigengene) --------------------------
  391. MEs_age1 <- compute_MEs(E_age1, cons_colors, prefix="GSE48350_AgingCont")
  392. MEs_age2 <- compute_MEs(E_age2, cons_colors, prefix="GSE48350Ctrl_AgingCont")
  393. MEs_ad59 <- compute_MEs(E_ad_ctrl59, cons_colors, prefix="GSE48350_AD>59")
  394. mod_trait_heatmap(MEs_age1, age_meta1, mode="age", prefix="GSE48350_AgingCont")
  395. mod_trait_heatmap(MEs_age2, age_meta2, mode="age", prefix="GSE48350Ctrl_AgingCont")
  396. mod_trait_heatmap(MEs_ad59, ad_ctrl_meta, mode="ad", prefix="GSE48350_AD")
  397. # ======== KEY FIX: robust covariate building for association tests ===========
  398. build_covars <- function(meta, include=c("sex","batch","region","tissue","age")) {
  399. use_cols <- intersect(include, names(meta))
  400. if (!length(use_cols)) return(NULL)
  401. covs <- meta[, use_cols, drop=FALSE]
  402. rownames(covs) <- meta$sample_id
  403. sanitize_covars(covs)
  404. }
  405. test_binary_trait <- function(MEs, meta, trait, include_covars=c("sex","batch","region","tissue","age")){
  406. if (is.null(MEs) || ncol(MEs)==0) return(tibble(module=character(), beta=numeric(), p=numeric(), FDR=numeric()))
  407. stopifnot(trait %in% names(meta))
  408. keep <- intersect(rownames(MEs), meta$sample_id)
  409. if (length(keep) < 6) return(tibble(module=character(), beta=numeric(), p=numeric(), FDR=numeric()))
  410. MEs <- MEs[keep,,drop=FALSE]
  411. mm <- meta[match(keep, meta$sample_id), , drop=FALSE]
  412. covs_raw <- build_covars(mm, include=include_covars)
  413. covs <- sanitize_covars(covs_raw, sample_order=rownames(MEs))
  414. if (!is.null(covs)) {
  415. covs <- drop_collinear(as.numeric(mm[[trait]]), covs, thr=0.98)
  416. }
  417. out <- bind_rows(lapply(colnames(MEs), function(m){
  418. y <- as.numeric(MEs[,m])
  419. a <- assoc_binary(y, as.numeric(mm[[trait]]), covs, min_n=6)
  420. tibble(module=m, beta=as.numeric(a["beta"]), p=as.numeric(a["p"]))
  421. }))
  422. out$p <- psafe(out$p); out$FDR <- p.adjust(out$p, "BH"); out
  423. }
  424. res_age_mod1 <- test_binary_trait(MEs_age1, age_meta1 %>% mutate(age_group = ifelse(age > 59,1L,0L)), "age_group", include_covars=c("sex","batch","region","tissue"))
  425. res_age_mod2 <- test_binary_trait(MEs_age2, age_meta2 %>% mutate(age_group = ifelse(age > 59,1L,0L)), "age_group", include_covars=c("sex","batch","region","tissue"))
  426. res_ad_mod <- test_binary_trait(MEs_ad59, ad_ctrl_meta, "disease", include_covars=c("sex","batch","region","tissue","age"))
  427. res_age_mod1$module <- std_me_names(res_age_mod1$module)
  428. res_age_mod2$module <- std_me_names(res_age_mod2$module)
  429. res_ad_mod$module <- std_me_names(res_ad_mod$module)
  430. combine_age_modules <- function(a1, a2){
  431. if (nrow(a1)>0 && nrow(a2)>0) {
  432. a1 %>% rename(beta1=beta, p1=p, FDR1=FDR) %>%
  433. full_join(a2 %>% rename(beta2=beta, p2=p, FDR2=FDR), by="module") %>%
  434. mutate(beta = rowMeans(cbind(beta1, beta2), na.rm=TRUE),
  435. p = fisher_combine_p(na.omit(c(psafe(p1), psafe(p2)))),
  436. FDR = p.adjust(psafe(p), "BH")) %>%
  437. select(module, beta, p, FDR, beta1, beta2, p1, p2, FDR1, FDR2)
  438. } else {
  439. a <- if (nrow(a1)>0) a1 else a2
  440. a %>% rename(beta=beta, p=p, FDR=FDR)
  441. }
  442. }
  443. age_combined_mod <- combine_age_modules(res_age_mod1, res_age_mod2)
  444. ap_direction <- function(a, b) {
  445. res <- rep(NA_character_, length(a))
  446. res[a > 0 & b > 0] <- "AgeUp-ADDown (AP_Resilience)"
  447. res[a < 0 & b < 0] <- "AgeDown-ADUp (AP_Vulnerability)"
  448. res[is.na(res)] <- "Other"; res
  449. }
  450. call_ap_modules <- function(df_age, df_ad) {
  451. df <- full_join(
  452. df_age %>% select(module, beta_age=beta, p_age=p, FDR_age=FDR),
  453. df_ad %>% select(module, beta_ad=beta, p_ad=p, FDR_ad=FDR),
  454. by="module"
  455. ) %>%
  456. mutate(p_age = psafe(p_age), p_ad = psafe(p_ad),
  457. direction = ap_direction(beta_age, -beta_ad),
  458. AP_score = (sign(beta_age) * -sign(beta_ad)) * ( -log10(p_age) + -log10(p_ad) ),
  459. age_sig = FDR_age < REGION_P_FDR,
  460. ad_sig = FDR_ad < REGION_P_FDR)
  461. df
  462. }
  463. AP_modules <- call_ap_modules(age_combined_mod, res_ad_mod)
  464. sizes <- module_df %>% count(module, name="module_size")
  465. AP_modules <- AP_modules %>%
  466. left_join(sizes, by="module") %>%
  467. mutate(AP_class = case_when(
  468. direction == "AgeUp-ADDown (AP_Resilience)" ~ "AP_Resilience",
  469. direction == "AgeDown-ADUp (AP_Vulnerability)" ~ "AP_Vulnerability",
  470. TRUE ~ "Other")) %>%
  471. arrange(desc(AP_score))
  472. write_csv(AP_modules, file.path(outdir, "AP_modules.csv"))
  473. # ------------------ Hubs (kME) -----------------------------------------------
  474. hub_scores <- function(module_df, EgxS) {
  475. split(module_df$gene, module_df$module) %>%
  476. imap_dfr(function(genes, m) {
  477. g <- intersect(genes, rownames(EgxS))
  478. if (length(g) < 3 || ncol(EgxS) < 2) return(tibble(module=m, gene=NA_character_, kME=NA_real_))
  479. datExpr <- t(EgxS[g, , drop=FALSE])
  480. ME <- WGCNA::moduleEigengenes(datExpr, rep(1, ncol(datExpr)))$eigengenes[,1]
  481. kME <- suppressWarnings(cor(datExpr, ME, use="pairwise.complete.obs"))
  482. tibble(module=m, gene=colnames(datExpr), kME=as.numeric(kME)) %>% arrange(desc(kME)) %>% head(TOP_HUBS_PER_MODULE)
  483. })
  484. }
  485. age_hubs <- hub_scores(module_df, EA)
  486. ctrl_hubs <- hub_scores(module_df, EC)
  487. write_csv(age_hubs, file.path(outdir, "AP_module_hubs_GSE48350_healthy.csv"))
  488. write_csv(ctrl_hubs, file.path(outdir, "AP_module_hubs_GSE48350_controls.csv"))
  489. # -------------------- export summary -----------------------------------------
  490. write_csv(AP_modules, file.path(outdir, "AP_modules_summary_from_genes.csv"))
  491. cat("Quadrant plot and module summary saved in:", outdir, "\n")
  492. # ============================================================================#
  493. # ================= AP gene-level scoring (AGE = CONTINUOUS) =================#
  494. # ============================================================================#
  495. log_msg("Scoring genes for AP importance (age=continuous per cohort, meta-analyzed)...")
  496. # Covariates
  497. cov_age1 <- build_covars(age_meta1, include=c("sex","batch","region","tissue"))
  498. cov_age2 <- build_covars(age_meta2, include=c("sex","batch","region","tissue"))
  499. cov_ad <- build_covars(ad_ctrl_meta, include=c("sex","batch","region","tissue","age"))
  500. cov_ad <- drop_collinear(as.numeric(setNames(ad_ctrl_meta$disease, ad_ctrl_meta$sample_id)[colnames(E_ad_ctrl59)]), cov_ad, thr=0.98)
  501. # Align matrices & traits
  502. align_cols <- function(E, ids) E[, intersect(colnames(E), ids), drop=FALSE]
  503. Eg_age1 <- align_cols(E_age1, age_meta1$sample_id)
  504. Eg_age2 <- align_cols(E_age2, age_meta2$sample_id)
  505. Eg_ad <- align_cols(E_ad_ctrl59, ad_ctrl_meta$sample_id)
  506. x_age1 <- setNames(scale(age_meta1$age)[,1], age_meta1$sample_id) # scaled
  507. x_age2 <- setNames(scale(age_meta2$age)[,1], age_meta2$sample_id)
  508. x_ad <- setNames(ad_ctrl_meta$disease, ad_ctrl_meta$sample_id)
  509. # Association matrices
  510. do_assoc_matrix_cont <- function(EgxS, x, covars, min_n=4) {
  511. if (is.null(EgxS) || ncol(EgxS) < min_n) {
  512. log_msg("Assoc matrix (continuous): too few samples (%s).", ncol(EgxS));
  513. return(tibble(gene=character(), beta=numeric(), se=numeric(), p=numeric()))
  514. }
  515. if (!is.null(covars)) {
  516. covars <- sanitize_covars(covars, sample_order=colnames(EgxS))
  517. }
  518. genes <- rownames(EgxS)
  519. purrr::map_dfr(genes, function(g){
  520. y <- EgxS[g, ]
  521. a <- assoc_linear(y, x[colnames(EgxS)], covars, min_n=min_n)
  522. tibble(gene=g, beta=as.numeric(a["beta"]), se=as.numeric(a["se"]), p=psafe(a["p"]))
  523. })
  524. }
  525. do_assoc_matrix_bin <- function(EgxS, x, covars, min_n=6) {
  526. if (is.null(EgxS) || ncol(EgxS) < min_n) {
  527. log_msg("Assoc matrix (binary): too few samples (%s).", ncol(EgxS));
  528. return(tibble(gene=character(), beta=numeric(), se=numeric(), p=numeric()))
  529. }
  530. if (!is.null(covars)) {
  531. covars <- sanitize_covars(covars, sample_order=colnames(EgxS))
  532. }
  533. genes <- rownames(EgxS)
  534. purrr::map_dfr(genes, function(g){
  535. y <- EgxS[g, ]
  536. a <- assoc_binary(y, x[colnames(EgxS)], covars, min_n=min_n)
  537. tibble(gene=g, beta=as.numeric(a["beta"]), se=as.numeric(a["se"]), p=psafe(a["p"]))
  538. })
  539. }
  540. ga1 <- do_assoc_matrix_cont(Eg_age1, x_age1, cov_age1, min_n=4) %>% rename(beta_age1=beta, se_age1=se, p_age1=p)
  541. ga2 <- do_assoc_matrix_cont(Eg_age2, x_age2, cov_age2, min_n=4) %>% rename(beta_age2=beta, se_age2=se, p_age2=p)
  542. gad <- do_assoc_matrix_bin (Eg_ad, x_ad, cov_ad, min_n=6) %>% rename(beta_ad=beta, se_ad=se, p_ad=p)
  543. # Combine aging cohorts (inverse-variance for beta, Fisher for p)
  544. combine_age_genes <- function(ga1, ga2){
  545. full_join(ga1, ga2, by="gene") %>%
  546. mutate(
  547. beta_age = case_when(
  548. is.finite(beta_age1) & is.finite(beta_age2) & is.finite(se_age1) & is.finite(se_age2) ~ {
  549. w1 <- 1/(se_age1^2); w2 <- 1/(se_age2^2); (beta_age1*w1 + beta_age2*w2)/(w1+w2)
  550. },
  551. is.finite(beta_age1) ~ beta_age1,
  552. is.finite(beta_age2) ~ beta_age2,
  553. TRUE ~ NA_real_
  554. ),
  555. p_age = {
  556. pvec <- c(psafe(p_age1), psafe(p_age2)); pvec <- pvec[is.finite(pvec)]
  557. if (length(pvec)==0) NA_real_ else fisher_combine_p(pvec)
  558. }
  559. ) %>% select(gene, beta_age, p_age)
  560. }
  561. age_comb <- combine_age_genes(ga1, ga2)
  562. # Build gene table
  563. gene_tbl <- tibble(gene=genes_cons) %>%
  564. left_join(age_comb, by="gene") %>%
  565. left_join(gad %>% select(gene, beta_ad, p_ad), by="gene")
  566. # FDR (p.adjust keeps NA if p is NA)
  567. gene_tbl$p_age <- as.numeric(gene_tbl$p_age)
  568. gene_tbl$p_ad <- as.numeric(gene_tbl$p_ad)
  569. gene_tbl$FDR_age <- p.adjust(gene_tbl$p_age, "BH")
  570. gene_tbl$FDR_ad <- p.adjust(gene_tbl$p_ad, "BH")
  571. # Attach module + kME from healthy matrices
  572. all_kME <- function(E, module_df) {
  573. split(module_df$gene, module_df$module) %>%
  574. imap_dfr(function(gset, m){
  575. g <- intersect(gset, rownames(E))
  576. if (length(g) < 3 || ncol(E) < 2) return(tibble(gene=character(), module=m, kME=numeric()))
  577. datExpr <- t(E[g, , drop=FALSE]); ME <- WGCNA::moduleEigengenes(datExpr, rep(1, ncol(datExpr)))$eigengenes[,1]
  578. k <- suppressWarnings(cor(datExpr, ME, use="pairwise.complete.obs"))
  579. tibble(gene=colnames(datExpr), module=m, kME=as.numeric(k))
  580. })
  581. }
  582. kME_A <- all_kME(EA, module_df)
  583. kME_C <- all_kME(EC, module_df)
  584. kME_tbl <- full_join(kME_A %>% rename(kME_A=kME), kME_C %>% rename(kME_C=kME), by=c("gene","module")) %>%
  585. mutate(kME_mean = rowMeans(cbind(kME_A, kME_C), na.rm=TRUE))
  586. gene_tbl <- gene_tbl %>%
  587. left_join(module_df %>% select(gene, module), by="gene") %>%
  588. left_join(kME_tbl %>% select(gene, kME_A, kME_C, kME_mean), by="gene")
  589. # ------------------ AP gene metrics (normalized) -----------------------------
  590. p_or_one <- function(p) ifelse(is.na(p), 1, psafe(p))
  591. AP_antagonism <- sign(gene_tbl$beta_age) * -sign(gene_tbl$beta_ad)
  592. AP_antagonism[is.na(AP_antagonism)] <- 0
  593. AP_sig_sum <- (-log10(p_or_one(gene_tbl$p_age))) + (-log10(p_or_one(gene_tbl$p_ad)))
  594. effect_sum <- abs(gene_tbl$beta_age) + abs(gene_tbl$beta_ad)
  595. kme_w <- if (isTRUE(AP_SCORE_USE_KME)) pmax(gene_tbl$kME_mean, 0) else 1
  596. AP_score_raw <- AP_antagonism * effect_sum * AP_sig_sum * kme_w
  597. norm_minmax01 <- function(x){
  598. xf <- x[is.finite(x)]
  599. if (!length(xf) || length(unique(xf)) == 1) return(rep(0.5, length(x)))
  600. rng <- range(xf)
  601. (x - rng[1]) / (rng[2] - rng[1])
  602. }
  603. robust_z <- function(x){
  604. m <- stats::median(x[is.finite(x)], na.rm=TRUE)
  605. s <- stats::mad(x[is.finite(x)], constant=1.4826, na.rm=TRUE)
  606. if (!is.finite(s) || s==0) return(rep(0, length(x)))
  607. (x - m) / s
  608. }
  609. percentile_0_100 <- function(x){
  610. r <- rank(x, na.last="keep", ties.method="average")
  611. 100 * (r - 1) / (sum(is.finite(x)) - 1)
  612. }
  613. AP_score_norm01 <- norm_minmax01(AP_score_raw)
  614. AP_score_z <- robust_z(AP_score_raw)
  615. AP_score_percentile <- percentile_0_100(AP_score_raw)
  616. # Per-gene AP Z (for module aggregation; sign-aware)
  617. z_from_beta_p <- function(beta, p) {
  618. pp <- p_or_one(p)
  619. zz <- sign(beta) * qnorm(1 - pp/2)
  620. zz[!is.finite(zz)] <- 0
  621. zz
  622. }
  623. Z_age <- z_from_beta_p(gene_tbl$beta_age, gene_tbl$p_age)
  624. Z_ad <- z_from_beta_p(-gene_tbl$beta_ad, gene_tbl$p_ad) # minus sign encodes AP (AD down = resilience)
  625. Z_AP_gene <- (Z_age + Z_ad) / sqrt(2) # Stouffer combine (equal weights)
  626. # Store gene outputs
  627. gene_tbl$AP_antagonism <- AP_antagonism
  628. gene_tbl$AP_sig_sum <- AP_sig_sum
  629. gene_tbl$AP_score_gene_raw <- AP_score_raw
  630. gene_tbl$AP_score_gene_norm01 <- AP_score_norm01
  631. gene_tbl$AP_score_gene_z <- AP_score_z
  632. gene_tbl$AP_score_gene_percentile <- AP_score_percentile
  633. gene_tbl$Z_age <- Z_age
  634. gene_tbl$Z_ad <- Z_ad
  635. gene_tbl$Z_AP_gene <- Z_AP_gene
  636. gene_tbl$AP_score_gene <- AP_score_norm01 # alias used by downstream code
  637. ap_class_gene <- function(b_age, b_ad) {
  638. aa <- sign(b_age) * -sign(b_ad)
  639. ifelse(aa > 0 & sign(b_age) > 0, "AP_Resilience",
  640. ifelse(aa > 0 & sign(b_age) < 0, "AP_Vulnerability", "Other"))
  641. }
  642. gene_tbl$AP_class_gene <- ap_class_gene(gene_tbl$beta_age, gene_tbl$beta_ad)
  643. AP_genes_ranked <- gene_tbl %>%
  644. arrange(desc(AP_score_gene_norm01)) %>%
  645. select(gene, module, kME_A, kME_C, kME_mean,
  646. beta_age, p_age, FDR_age,
  647. beta_ad, p_ad, FDR_ad,
  648. AP_antagonism, AP_sig_sum, AP_class_gene,
  649. AP_score_gene_raw, AP_score_gene_norm01, AP_score_gene_z, AP_score_gene_percentile,
  650. Z_age, Z_ad, Z_AP_gene,
  651. AP_score_gene)
  652. readr::write_csv(AP_genes_ranked, file.path(outdir, "wgcna", "AP_genes_ranked.csv"))
  653. # ------------------ Gene-aggregated AP per module ----------------------------
  654. log_msg("Aggregating AP evidence across genes within modules (Stouffer Z)...")
  655. w_gene <- if (isTRUE(AP_MODULE_USE_KME_WEIGHTS)) pmax(gene_tbl$kME_mean, 0) else rep(1, nrow(gene_tbl))
  656. w_gene[!is.finite(w_gene)] <- 0
  657. agg_stouffer <- function(z, w){
  658. ok <- is.finite(z) & is.finite(w) & w > 0
  659. if (!any(ok)) return(NA_real_)
  660. sum(w[ok] * z[ok]) / sqrt(sum((w[ok])^2))
  661. }
  662. AP_modules_geneAgg <- gene_tbl %>%
  663. group_by(module) %>%
  664. summarise(
  665. n_genes = n(),
  666. n_antagonism = sum(AP_antagonism > 0, na.rm=TRUE),
  667. frac_antagonism= n_antagonism / n_genes,
  668. mean_AP_norm01 = mean(AP_score_gene_norm01, na.rm=TRUE),
  669. top10_AP_norm01= {
  670. k <- ceiling(0.10 * n_genes)
  671. if (k < 1) k <- 1
  672. mean(head(sort(AP_score_gene_norm01, decreasing=TRUE), k), na.rm=TRUE)
  673. },
  674. Z_from_genes = agg_stouffer(Z_AP_gene, w_gene[match(cur_data_all()$gene, gene_tbl$gene)]),
  675. p_from_genes = 2*pnorm(-abs(Z_from_genes))
  676. ) %>%
  677. ungroup() %>%
  678. mutate(FDR_from_genes = p.adjust(p_from_genes, "BH")) %>%
  679. arrange(p_from_genes)
  680. readr::write_csv(AP_modules_geneAgg, file.path(outdir, "wgcna", "AP_modules_geneAggregated.csv"))
  681. AP_modules_combined <- AP_modules %>%
  682. select(module, beta_age, p_age, FDR_age, beta_ad, p_ad, FDR_ad, AP_score, AP_class, module_size) %>%
  683. rename(EG_beta_age=beta_age, EG_p_age=p_age, EG_FDR_age=FDR_age,
  684. EG_beta_ad=beta_ad, EG_p_ad=p_ad, EG_FDR_ad=FDR_ad, EG_AP_score=AP_score, EG_AP_class=AP_class) %>%
  685. full_join(AP_modules_geneAgg, by="module")
  686. readr::write_csv(AP_modules_combined, file.path(outdir, "wgcna", "AP_modules_combined.csv"))
  687. # ---------- Ego networks for top genes ---------------------------------------
  688. .sim_cache <- new.env(parent=emptyenv())
  689. get_similarity_for_module <- function(mod, wobj) {
  690. key <- paste0(mod, "_", wobj$name)
  691. if (!is.null(.sim_cache[[key]])) return(.sim_cache[[key]])
  692. genes_m <- (wobj$module_df %>% filter(module==mod))$gene
  693. genes_m <- intersect(genes_m, rownames(wobj$expr))
  694. if (length(genes_m) < 5) return(NULL)
  695. datExpr <- t(wobj$expr[genes_m, , drop=FALSE])
  696. S <- NULL; ok <- TRUE
  697. tryCatch({ TOM <- WGCNA::TOMsimilarityFromExpr(datExpr, power=wobj$power, networkType=wobj$networkType); colnames(TOM) <- rownames(TOM) <- colnames(datExpr); S <<- TOM }, error=function(e){ ok <<- FALSE })
  698. if (!ok || is.null(S)) { Adj <- WGCNA::adjacency(datExpr, power=wobj$power, type=wobj$networkType); colnames(Adj) <- rownames(Adj) <- colnames(datExpr); S <- Adj }
  699. .sim_cache[[key]] <- S; S
  700. }
  701. export_gene_ego <- function(gene, mod, wobj, topk=15) {
  702. S <- get_similarity_for_module(mod, wobj)
  703. if (is.null(S) || !(gene %in% colnames(S))) return(invisible(NULL))
  704. v <- S[, gene]; v <- v[names(v) != gene]; v <- sort(v, decreasing=TRUE)
  705. nbrs <- head(names(v[v > 0]), min(topk, sum(v > 0)))
  706. if (!length(nbrs)) return(invisible(NULL))
  707. nodes <- unique(c(gene, nbrs))
  708. sub <- S[nodes, nodes, drop=FALSE]
  709. edges <- as.data.frame(as.table(sub), stringsAsFactors=FALSE)
  710. names(edges) <- c("from","to","weight")
  711. edges <- edges %>% filter(from < to, weight > 0)
  712. base <- file.path(outdir, "wgcna", "networks", paste0(wobj$name, "_", mod, "_ego_", make.names(gene)))
  713. write_csv(edges, paste0(base, "_edges.csv"))
  714. readr::write_csv(tibble(gene=nodes), paste0(base, "_nodes.csv"))
  715. if (ok_igraph && ok_ggraph && nrow(edges) > 0) {
  716. g <- igraph::graph_from_data_frame(edges, directed=FALSE, vertices=tibble(name=nodes))
  717. p <- ggraph::ggraph(g, layout="fr") + ggraph::geom_edge_link(alpha=0.3) +
  718. ggraph::geom_node_point(size=3, alpha=0.9) +
  719. ggraph::geom_node_text(aes(label=name), repel=TRUE, size=3) +
  720. ggplot2::labs(title=paste0("Ego network: ", gene, " (", mod, ")")) +
  721. ggplot2::theme_void(base_size=12)
  722. safe_ggsave(paste0(base, "_plot"), p, w=6.5, h=5.5, dpi=PNG_DPI)
  723. }
  724. }
  725. topR <- AP_genes_ranked %>% filter(AP_class_gene=="AP_Resilience", module!="ME00") %>% head(200)
  726. topV <- AP_genes_ranked %>% filter(AP_class_gene=="AP_Vulnerability", module!="ME00") %>% head(200)
  727. if (nrow(topR)==0) topR <- AP_genes_ranked %>% filter(module!="ME00") %>% arrange(desc(AP_sig_sum)) %>% head(200)
  728. if (nrow(topV)==0) topV <- AP_genes_ranked %>% filter(module!="ME00") %>% arrange(desc(AP_sig_sum)) %>% head(200)
  729. topR_pick <- topR %>% arrange(desc(AP_score_gene_norm01)) %>% head(TOP_EGO_PER_CLASS)
  730. topV_pick <- topV %>% arrange(desc(AP_score_gene_norm01)) %>% head(TOP_EGO_PER_CLASS)
  731. if (nrow(topR_pick)+nrow(topV_pick) == 0) {
  732. log_msg("No top AP genes to export ego networks for.")
  733. } else {
  734. wobj_export <- list(name="ConsensusOn_GSE48350", module_df=module_df, expr=EC, power=cons_power, networkType="signed")
  735. for (row in seq_len(nrow(topR_pick))) export_gene_ego(topR_pick$gene[row], topR_pick$module[row], wobj_export)
  736. for (row in seq_len(nrow(topV_pick))) export_gene_ego(topV_pick$gene[row], topV_pick$module[row], wobj_export)
  737. log_msg("Exported ego networks for top AP genes (per class).")
  738. }
  739. # ---- Save combined objects for reproducibility ----
  740. saveRDS(list(
  741. modules = module_df,
  742. AP_modules = AP_modules,
  743. AP_modules_geneAgg = AP_modules_geneAgg,
  744. AP_modules_combined = AP_modules_combined,
  745. AP_genes = AP_genes_ranked,
  746. hubs_age = age_hubs,
  747. hubs_ctrl = ctrl_hubs,
  748. power = cons_power,
  749. colors = cons_colors,
  750. genes_cons = genes_cons,
  751. AP_SCORE_USE_KME = AP_SCORE_USE_KME,
  752. AP_MODULE_USE_KME_WEIGHTS = AP_MODULE_USE_KME_WEIGHTS
  753. ), file = file.path(outdir, "wgcna", "AP_wgcna_objects.rds"))
  754. # ------------------ Quadrant plot (eigengene view) ---------------------------
  755. suppressPackageStartupMessages({ library(ggrepel); library(scales); library(readr); library(dplyr); library(ggplot2) })
  756. # Load the combined module table produced above
  757. mods <- readr::read_csv(file.path(outdir, "wgcna", "AP_modules_combined.csv"), show_col_types = FALSE)
  758. # If EG_AP_class already exists, use it; otherwise infer from EG betas
  759. infer_class <- function(b_age, b_ad) {
  760. if (is.finite(b_age) && is.finite(b_ad)) {
  761. if (b_age > 0 && b_ad < 0) "AP_Resilience"
  762. else if (b_age < 0 && b_ad > 0) "AP_Vulnerability"
  763. else "Other"
  764. } else "Other"
  765. }
  766. AP_COLORS <- c("AP_Resilience"="#009E73", "AP_Vulnerability"="#D55E00", "Other"="grey70")
  767. AP_modules_plot <- mods %>%
  768. mutate(
  769. AP_class = if (!is.null(EG_AP_class)) EG_AP_class else mapply(infer_class, EG_beta_age, EG_beta_ad),
  770. x = EG_beta_age,
  771. y = -EG_beta_ad,
  772. size_raw = pmax(0,
  773. -log10(pmax(EG_p_age, .Machine$double.xmin)) +
  774. -log10(pmax(EG_p_ad, .Machine$double.xmin))
  775. ),
  776. size_raw = ifelse(is.finite(size_raw), size_raw, 0),
  777. size_s = scales::rescale(
  778. pmin(size_raw, stats::quantile(size_raw[size_raw>0], 0.99, na.rm=TRUE)),
  779. to = c(2.5, 9),
  780. from = range(size_raw[size_raw>0], na.rm=TRUE)
  781. )
  782. )
  783. plt_quad <- ggplot(AP_modules_plot, aes(x = x, y = y)) +
  784. geom_hline(yintercept = 0, linetype = 2, linewidth = 0.3) +
  785. geom_vline(xintercept = 0, linetype = 2, linewidth = 0.3) +
  786. geom_point(aes(color = AP_class, size = size_s), alpha = 0.9) +
  787. ggrepel::geom_text_repel(aes(label = module),
  788. min.segment.length = 0, seed = 42,
  789. box.padding = 0.25, point.padding = 0.2,
  790. size = 3.2, color = "grey20", max.overlaps = Inf) +
  791. scale_color_manual(values = AP_COLORS, name = "AP Class", drop = FALSE) +
  792. scale_size_identity(guide = "legend", name = "-log10(p_age)+-log10(p_ad)") +
  793. labs(
  794. x = "Module effect (Healthy Aging, β_age; eigengene)",
  795. y = "Module effect in AD (−β_ad; eigengene)",
  796. title = "AP Module Quadrant Plot (Aging vs AD)"
  797. ) +
  798. coord_equal(expand = TRUE) +
  799. theme_minimal(base_size = 12) +
  800. theme(legend.position = "right")
  801. dir.create(file.path(outdir, "wgcna"), showWarnings = FALSE, recursive = TRUE)
  802. safe_ggsave(file.path(outdir, "wgcna", "fig_modules_quadrant_AP_modules_from_EG"), plt_quad, w = 7.5, h = 6.5, dpi = PNG_DPI)
  803. # ==================== High-AP modules: plots + gene composition ==============
  804. suppressPackageStartupMessages({ library(dplyr); library(readr); library(ggplot2); library(ggrepel); library(scales); })
  805. mods <- read_csv(file.path(outdir, "wgcna", "AP_modules_combined.csv"), show_col_types = FALSE)
  806. genes <- read_csv(file.path(outdir, "wgcna", "AP_genes_ranked.csv"), show_col_types = FALSE)
  807. # --- Selection knobs (override via env) --------------------------------------
  808. AP_HIGHSCORE_MIN <- as.numeric(Sys.getenv("AP_HIGHSCORE_MIN", unset = NA)) # e.g. 4
  809. AP_TOP_N <- as.integer(Sys.getenv("AP_TOP_N", unset = 6)) # fallback if none pass threshold
  810. # Helper: pick high-AP modules by eigengene-level score (antagonism-weighted)
  811. pick_high_ap <- function(df, min_score = NA, top_n = 6){
  812. d <- df %>% mutate(EG_AP_abs = abs(EG_AP_score))
  813. if (is.finite(min_score)) {
  814. keep <- d %>% filter(EG_AP_abs >= min_score)
  815. if (nrow(keep) > 0) return(keep)
  816. }
  817. d %>% slice_max(order_by = EG_AP_abs, n = top_n, with_ties = FALSE)
  818. }
  819. mods_sel <- pick_high_ap(mods, AP_HIGHSCORE_MIN, AP_TOP_N)
  820. if (nrow(mods_sel) == 0) {
  821. warning("No modules selected for plotting; check thresholds.")
  822. } else {
  823. # -------------- Plot 1: Quadrant for selected modules (eigengene stats) ---
  824. infer_class <- function(b_age, b_ad) {
  825. if (is.finite(b_age) && is.finite(b_ad)) {
  826. if (b_age > 0 && b_ad < 0) "AP_Resilience"
  827. else if (b_age < 0 && b_ad > 0) "AP_Vulnerability"
  828. else "Other"
  829. } else "Other"
  830. }
  831. AP_COLORS <- c("AP_Resilience" = "#009E73",
  832. "AP_Vulnerability" = "#D55E00",
  833. "Other" = "grey70")
  834. plot_df <- mods_sel %>%
  835. mutate(
  836. AP_class = if ("EG_AP_class" %in% names(.)) EG_AP_class else mapply(infer_class, EG_beta_age, EG_beta_ad),
  837. x = EG_beta_age,
  838. y = -EG_beta_ad,
  839. size_raw = pmax(0,
  840. -log10(pmax(EG_p_age, .Machine$double.xmin)) +
  841. -log10(pmax(EG_p_ad, .Machine$double.xmin))
  842. ),
  843. size_raw = ifelse(is.finite(size_raw), size_raw, 0),
  844. size_s = scales::rescale(
  845. pmin(size_raw, quantile(size_raw[size_raw>0], 0.99, na.rm=TRUE)),
  846. to = c(2.5, 9),
  847. from = range(size_raw[size_raw>0], na.rm=TRUE)
  848. )
  849. )
  850. plt_quad_hi <- ggplot(plot_df, aes(x = x, y = y)) +
  851. geom_hline(yintercept = 0, linetype = 2, linewidth = 0.3) +
  852. geom_vline(xintercept = 0, linetype = 2, linewidth = 0.3) +
  853. geom_point(aes(color = AP_class, size = size_s), alpha = 0.9) +
  854. ggrepel::geom_text_repel(aes(label = module),
  855. seed = 42, box.padding = 0.25, point.padding = 0.2,
  856. size = 3.2, color = "grey20", min.segment.length = 0) +
  857. scale_color_manual(values = AP_COLORS, name = "AP Class", drop = FALSE) +
  858. scale_size_identity(guide = "legend", name = "-log10(p_age)+-log10(p_ad)") +
  859. labs(
  860. title = "High-AP Modules (eigengene view)",
  861. x = "β_age (Healthy aging, eigengene)",
  862. y = "−β_ad (AD vs Control, eigengene)",
  863. subtitle = sprintf("Selected by |AP score|%s",
  864. if (is.finite(AP_HIGHSCORE_MIN)) paste0(" ≥ ", AP_HIGHSCORE_MIN) else
  865. paste0(" — top ", AP_TOP_N))
  866. ) +
  867. coord_equal(expand = TRUE) +
  868. theme_minimal(base_size = 12) +
  869. theme(legend.position = "right")
  870. safe_ggsave(file.path(outdir, "wgcna", "fig_quadrant_highAP_modules"), plt_quad_hi, w = 7.5, h = 6.5, dpi = PNG_DPI)
  871. # --------- Composition: #genes per module by AP_class_gene (gene-level) ----
  872. comp_long <- genes %>%
  873. semi_join(mods_sel %>% select(module), by = "module") %>%
  874. mutate(AP_class_gene = factor(AP_class_gene, levels = c("AP_Resilience","AP_Vulnerability","Other"))) %>%
  875. count(module, AP_class_gene, name = "n_genes") %>%
  876. group_by(module) %>%
  877. mutate(total_genes = sum(n_genes), frac = n_genes / total_genes) %>%
  878. ungroup()
  879. # Save a tidy composition table (answers your “are you determining the numbers?” → yes)
  880. write_csv(comp_long, file.path(outdir, "wgcna", "highAP_modules_gene_composition.csv"))
  881. # -------------- Plot 2: Stacked bars by gene AP class (counts & fraction) --
  882. plt_counts <- ggplot(comp_long, aes(x = module, y = n_genes, fill = AP_class_gene)) +
  883. geom_col(width = 0.8, color = "white") +
  884. scale_fill_manual(values = c("AP_Resilience"="#009E73","AP_Vulnerability"="#D55E00","Other"="grey70"),
  885. name = "Gene AP class") +
  886. labs(title = "Gene composition of high-AP modules",
  887. subtitle = "Counts by AP_Resilience / AP_Vulnerability / Other",
  888. x = "Module", y = "# genes") +
  889. theme_minimal(base_size = 12) +
  890. theme(legend.position = "right")
  891. safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_modules_gene_counts"), plt_counts, w = 8, h = 5, dpi = PNG_DPI)
  892. plt_frac <- ggplot(comp_long, aes(x = module, y = frac, fill = AP_class_gene)) +
  893. geom_col(width = 0.8, color = "white") +
  894. scale_y_continuous(labels = percent_format()) +
  895. scale_fill_manual(values = c("AP_Resilience"="#009E73","AP_Vulnerability"="#D55E00","Other"="grey70"),
  896. name = "Gene AP class") +
  897. labs(title = "Gene composition of high-AP modules",
  898. subtitle = "Fraction within each module",
  899. x = "Module", y = "Fraction") +
  900. theme_minimal(base_size = 12) +
  901. theme(legend.position = "right")
  902. safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_modules_gene_fractions"), plt_frac, w = 8, h = 5, dpi = PNG_DPI)
  903. # ================== SINGLE FIGURE: Lollipop (top) + Donuts (bottom) ==================
  904. suppressPackageStartupMessages({
  905. library(dplyr); library(readr); library(ggplot2); library(scales)
  906. })
  907. has_patchwork <- requireNamespace("patchwork", quietly = TRUE)
  908. mods <- readr::read_csv(file.path(outdir, "wgcna", "AP_modules_combined.csv"), show_col_types = FALSE)
  909. genes <- readr::read_csv(file.path(outdir, "wgcna", "AP_genes_ranked.csv"), show_col_types = FALSE)
  910. # -------- selection knobs (change via env if you like) --------
  911. AP_HIGHSCORE_MIN <- as.numeric(Sys.getenv("AP_HIGHSCORE_MIN", unset = NA)) # e.g., 4
  912. AP_TOP_N <- as.integer(Sys.getenv("AP_TOP_N", unset = 6)) # top-N if no cutoff
  913. pick_high_ap <- function(df, min_score = NA, top_n = 6){
  914. d <- df %>% mutate(EG_AP_abs = abs(EG_AP_score))
  915. if (is.finite(min_score)) {
  916. keep <- d %>% filter(EG_AP_abs >= min_score)
  917. if (nrow(keep) > 0) return(keep)
  918. }
  919. d %>% slice_max(order_by = EG_AP_abs, n = top_n, with_ties = FALSE)
  920. }
  921. mods_sel <- pick_high_ap(mods, AP_HIGHSCORE_MIN, AP_TOP_N) %>%
  922. arrange(desc(abs(EG_AP_score))) %>%
  923. mutate(module = factor(module, levels = unique(module)))
  924. if (nrow(mods_sel) == 0) {
  925. warning("No modules selected — lower AP_HIGHSCORE_MIN or increase AP_TOP_N.");
  926. } else {
  927. AP_COLORS <- c("AP_Resilience"="#009E73","AP_Vulnerability"="#D55E00","Other"="grey70")
  928. # -------------------- TOP: Lollipop rank by |AP score| ---------------------
  929. p_top <- ggplot(mods_sel, aes(y = module, x = abs(EG_AP_score))) +
  930. geom_segment(aes(yend = module, x = 0, xend = abs(EG_AP_score)), linewidth = 1, alpha = 0.45) +
  931. geom_point(aes(color = EG_AP_class,
  932. size = -log10(pmax(EG_p_age, .Machine$double.xmin)) +
  933. -log10(pmax(EG_p_ad, .Machine$double.xmin))),
  934. alpha = 0.95) +
  935. scale_color_manual(values = AP_COLORS, drop = FALSE, name = "AP class") +
  936. scale_size_continuous(range = c(3, 9), name = expression(-log[10](p[age])+-log[10](p[AD]))) +
  937. labs(title = "High-AP modules", subtitle = "Ranked by |AP score| (eigengene)",
  938. x = "|AP score|", y = NULL) +
  939. theme_minimal(base_size = 12) +
  940. theme(legend.position = "right", panel.grid.major.y = element_blank())
  941. # --------------- BOTTOM: Donut row of gene-class composition ---------------
  942. comp <- genes %>%
  943. semi_join(mods_sel %>% select(module), by = "module") %>%
  944. mutate(AP_class_gene = factor(AP_class_gene, levels = c("AP_Resilience","AP_Vulnerability","Other")),
  945. module = factor(module, levels = levels(mods_sel$module))) %>%
  946. count(module, AP_class_gene, name = "n") %>%
  947. group_by(module) %>% mutate(frac = n/sum(n)) %>% ungroup()
  948. p_bottom <- ggplot(comp, aes(x = 2, y = frac, fill = AP_class_gene)) +
  949. geom_col(width = 0.6, color = "white") +
  950. coord_polar(theta = "y") +
  951. facet_wrap(~ module, nrow = 1) +
  952. scale_fill_manual(values = AP_COLORS, name = "Gene AP class") +
  953. xlim(0.5, 2.6) +
  954. labs(title = NULL, subtitle = NULL) +
  955. theme_void(base_size = 12) +
  956. theme(legend.position = "right",
  957. strip.text = element_text(face = "bold"))
  958. # ---------------------- Stack (donut at the bottom) ------------------------
  959. dir.create(file.path(outdir, "wgcna"), recursive = TRUE, showWarnings = FALSE)
  960. if (has_patchwork) {
  961. fig <- p_top / p_bottom + patchwork::plot_layout(heights = c(2, 1), guides = "collect")
  962. safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_lollipop_plus_donuts"), fig, w = 11, h = 7.5, dpi = PNG_DPI)
  963. } else {
  964. # Save separately if patchwork isn’t installed
  965. safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_lollipop"), p_top, w = 11, h = 5.0, dpi = PNG_DPI)
  966. safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_donuts"), p_bottom, w = 11, h = 3.0, dpi = PNG_DPI)
  967. }
  968. # Also write the composition table (counts + fractions) for the figure
  969. readr::write_csv(comp, file.path(outdir, "wgcna", "highAP_modules_gene_composition_for_donuts.csv"))
  970. }
  971. # ---------------- Top genes per module (10 highest AP_score_gene) ----------
  972. TOP_GENES_PER_MODULE <- as.integer(Sys.getenv("TOP_GENES_PER_MODULE", unset = "10"))
  973. top_genes <- genes %>%
  974. semi_join(mods_sel %>% dplyr::select(module), by = "module") %>%
  975. dplyr::group_by(module) %>%
  976. dplyr::slice_max(order_by = AP_score_gene, n = TOP_GENES_PER_MODULE, with_ties = FALSE) %>%
  977. dplyr::ungroup() %>%
  978. # build a per-module ordering key so each facet sorts independently
  979. dplyr::group_by(module) %>%
  980. dplyr::arrange(AP_score_gene, .by_group = TRUE) %>%
  981. dplyr::mutate(key = paste(module, gene, sep = "::")) %>%
  982. dplyr::ungroup()
  983. # lock factor levels using the per-module order
  984. key_levels <- top_genes %>%
  985. dplyr::group_by(module) %>%
  986. dplyr::arrange(AP_score_gene, .by_group = TRUE) %>%
  987. dplyr::pull(key)
  988. top_genes$key <- factor(top_genes$key, levels = unique(key_levels))
  989. p_topgenes <- ggplot(top_genes,
  990. aes(x = AP_score_gene, y = key, color = AP_class_gene)) +
  991. geom_segment(aes(x = 0, xend = AP_score_gene, y = key, yend = key),
  992. alpha = 0.45, linewidth = 0.9) +
  993. geom_point(size = 2.6, alpha = 0.95) +
  994. scale_color_manual(values = AP_COLORS,
  995. name = "Gene AP class",
  996. breaks = c("AP_Resilience","AP_Vulnerability","Other"),
  997. drop = FALSE) +
  998. scale_y_discrete(labels = function(x) sub(".*::", "", x)) +
  999. facet_wrap(~ module, scales = "free_y") +
  1000. labs(
  1001. title = sprintf("Top %d genes by AP score (per module)", TOP_GENES_PER_MODULE),
  1002. x = "AP_score_gene (normalized 0–1)", y = NULL
  1003. ) +
  1004. coord_cartesian(clip = "off") +
  1005. theme_minimal(base_size = 12) +
  1006. theme(
  1007. legend.position = "right",
  1008. strip.text = element_text(face = "bold"),
  1009. panel.grid.major.y = element_blank()
  1010. )
  1011. safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_top_genes_per_module"),
  1012. p_topgenes, w = 11, h = 6.5, dpi = PNG_DPI)
  1013. # export the exact list that appears in the plot
  1014. readr::write_csv(top_genes %>%
  1015. dplyr::transmute(module, gene,
  1016. AP_score_gene,
  1017. AP_class_gene,
  1018. beta_age, p_age, FDR_age,
  1019. beta_ad, p_ad, FDR_ad,
  1020. kME_mean),
  1021. file.path(outdir, "wgcna", "top_genes_per_module_for_figure.csv"))
  1022. # Also print a quick text summary to the log
  1023. log_msg("High-AP modules selected: %s", paste(sort(unique(mods_sel$module)), collapse=", "))
  1024. log_msg("Composition table written to: %s",
  1025. file.path(outdir, "wgcna", "highAP_modules_gene_composition.csv"))
  1026. # ======================= ALL MODULES: where are the strong genes? =======================
  1027. suppressPackageStartupMessages({ library(dplyr); library(readr); library(ggplot2); library(ggrepel); library(scales) })
  1028. # knobs (override via env)
  1029. AP_GENE_MIN_NORM <- as.numeric(Sys.getenv("AP_GENE_MIN_NORM", unset = "0.70")) # threshold on AP_score_gene_norm01
  1030. TOP_GENES_PER_MOD <- as.integer(Sys.getenv("TOP_GENES_PER_MOD", unset = "3")) # labels per module
  1031. # Ensure factor order: rank modules globally by |EG_AP_score| when available
  1032. mods_ranked <- mods %>%
  1033. mutate(EG_AP_abs = abs(EG_AP_score)) %>%
  1034. arrange(desc(EG_AP_abs)) %>%
  1035. mutate(module = factor(module, levels = unique(module)))
  1036. genes2 <- genes %>%
  1037. mutate(AP_class_gene = factor(AP_class_gene, levels = c("AP_Resilience","AP_Vulnerability","Other"))) %>%
  1038. left_join(mods_ranked %>% select(module, EG_AP_abs), by = "module") %>%
  1039. mutate(module = factor(module, levels = levels(mods_ranked$module)))
  1040. # ---------- (1) Heatmap: counts of high-AP genes per module × gene AP class ----------
  1041. hi_counts <- genes2 %>%
  1042. filter(is.finite(AP_score_gene_norm01)) %>%
  1043. mutate(is_high = AP_score_gene_norm01 >= AP_GENE_MIN_NORM) %>%
  1044. group_by(module, AP_class_gene) %>%
  1045. summarise(n_high = sum(is_high, na.rm = TRUE), .groups = "drop")
  1046. # Fill missing combos with zero for a clean heatmap
  1047. all_mods <- levels(genes2$module)
  1048. all_class <- levels(genes2$AP_class_gene)
  1049. hi_counts <- tidyr::complete(hi_counts, module = all_mods, AP_class_gene = all_class, fill = list(n_high = 0))
  1050. p_heat <- ggplot(hi_counts, aes(x = AP_class_gene, y = module, fill = n_high)) +
  1051. geom_tile(color = "white", linewidth = 0.3) +
  1052. scale_fill_gradient(low = "grey95", high = "black", name = "# high-AP genes") +
  1053. scale_x_discrete(position = "top") +
  1054. labs(
  1055. title = sprintf("High-AP genes across ALL modules (threshold: ≥ %.2f)", AP_GENE_MIN_NORM),
  1056. x = "Gene AP class", y = "Module (ranked by |EG AP|)"
  1057. ) +
  1058. theme_minimal(base_size = 12) +
  1059. theme(panel.grid = element_blank(), axis.text.x = element_text(face = "bold"))
  1060. safe_ggsave(file.path(outdir, "wgcna", "fig_allModules_highAP_heatmap"), p_heat, w = 6.5, h = max(6, 0.25*length(all_mods)), dpi = PNG_DPI)
  1061. # ---------- (2) Small multiples: top K genes per module (labels) ---------------
  1062. topK_per_module <- genes2 %>%
  1063. group_by(module) %>%
  1064. arrange(desc(AP_score_gene_norm01), .by_group = TRUE) %>%
  1065. slice_head(n = TOP_GENES_PER_MOD) %>%
  1066. ungroup() %>%
  1067. mutate(label = paste0(gene, " (", scales::number(AP_score_gene_norm01, accuracy = 0.01), ")"))
  1068. # If some modules are tiny, ensure at least one row
  1069. topK_per_module <- topK_per_module %>% filter(!is.na(module))
  1070. p_smallmult <- ggplot(topK_per_module,
  1071. aes(x = AP_score_gene_norm01, y = reorder(label, AP_score_gene_norm01))) +
  1072. geom_col(aes(fill = AP_class_gene), width = 0.8, color = "white") +
  1073. geom_vline(xintercept = AP_GENE_MIN_NORM, linetype = 2, linewidth = 0.3) +
  1074. facet_wrap(~ module, ncol = 3, scales = "free_y") +
  1075. scale_fill_manual(values = AP_COLORS, name = "Gene AP class") +
  1076. scale_x_continuous(limits = c(0, 1), labels = label_number(accuracy = 0.1)) +
  1077. labs(
  1078. title = sprintf("Top %d genes per module by AP score (normalized 0–1)", TOP_GENES_PER_MOD),
  1079. subtitle = "ALL modules; dotted line = high-AP threshold",
  1080. x = "AP_score_gene (norm.)", y = NULL
  1081. ) +
  1082. theme_minimal(base_size = 12) +
  1083. theme(legend.position = "right",
  1084. strip.text = element_text(face = "bold"),
  1085. panel.grid.major.y = element_blank())
  1086. safe_ggsave(file.path(outdir, "wgcna", "fig_allModules_topK_genes"), p_smallmult, w = 11, h = 10, dpi = PNG_DPI)
  1087. # Export tidy tables used in these figures
  1088. readr::write_csv(hi_counts, file.path(outdir, "wgcna", "allModules_highAP_geneClass_counts.csv"))
  1089. readr::write_csv(topK_per_module, file.path(outdir, "wgcna", "allModules_topK_genes.csv"))
  1090. # Log a quick heads-up
  1091. log_msg("All-modules figures saved: high-AP heatmap + top-%d genes per module. Threshold=%.2f",
  1092. TOP_GENES_PER_MOD, AP_GENE_MIN_NORM)
  1093. }
  1094. log_msg("Done. Wrote:\n - %s\n - %s\n - %s\n - %s\n - %s\n - %s",
  1095. file.path(outdir, "AP_modules.csv"),
  1096. file.path(outdir, "wgcna", "AP_modules_geneAggregated.csv"),
  1097. file.path(outdir, "wgcna", "AP_modules_combined.csv"),
  1098. file.path(outdir, "wgcna"),
  1099. file.path(outdir, "wgcna", "networks"),
  1100. file.path(outdir, "wgcna", "AP_genes_ranked.csv"))

10_modules_AP.R at commit 377f6ae, no license · at the source

Overview

  1. Department of Bioinformatics, Julius-Maximilians-Universität Würzburg, Würzburg, Germany
  2. Department of Bioengineering, Marmara University, Istanbul, Turkey
Institutions: University of Würzburg (Germany); Marmara University (Türkiye)
Journal: Computational and structural biotechnology journal, volume 35, issue 1, article 0134
Dates: received 30 March 2026; accepted 21 May 2026; published online 8 June 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.34133/csbj.0134 · PMID 42267139 · PMCID PMC13243799 · OpenAlex W7162071788
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: genetics / omics (modality), human (organism), Alzheimer's / dementia (population), cellular / molecular (subfield)
Methods: Statistics, Smoothing, state filtering, decompositions, Preprocessing, Connectivity
Topic: Single-cell and spatial transcriptomics (Molecular Biology, Biochemistry, Genetics and Molecular Biology), according to OpenAlex
Citations: not cited yet (Europe PMC); 95 references in the paper

Abstract

Aging is the strongest risk factor for Alzheimer’s disease (AD); however, some individuals age without major cognitive decline, suggesting that resilience and vulnerability may be associated with distinct molecular trajectories. To investigate these trajectories, we performed an integrated transcriptomic analysis of human dermal fibroblasts (GSE113957) and multi-region brain profiles (GSE48350), extending previous dataset-specific studies that focused primarily on age prediction, regional variation, or synaptic/immune signatures. Healthy aging and AD were compared within a novel antagonistic pleiotropy (AP) framework. This approach prioritized genes and candidate transcriptional regulators with opposing age and disease-associated expression patterns. Across tissues, healthy aging was associated with relative preservation of metabolic, mitochondrial, and lipid-homeostatic programs, whereas AD was associated with suppression of these programs alongside greater inflammatory and immune pathway activity. AP-Vulnerability genes (Age↓/AD↑), including TAC1, FREM3, and SLC25A46, declined with age but were induced in AD. Conversely, AP-Resilience genes (Age↑/AD↓), including PTH2, PPDPF, and NEFH, increased during healthy aging but were reduced in AD. Pathway analyses suggested an association between metabolic programs and resilience, and between immune activation and vulnerability. Transcription-factor inference prioritized PPARG, NFE2L2, and TEAD4 as candidate resilience-associated regulators, showing directionally opposite patterns relative to immune- and developmental-related regulators in AD.

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 18 matches between paragraphs and lines of code.

salihoglu/Alzheimer_AP

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 377f6aed20f1984d011e84b99e5ed5cd2db0c811, 30 March 2026
Languages: R (14)
Size: 15 files, 14 scripts
Software Heritage: not archived
Found in: “Data Availability”
Holds: README
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: tidyverse (10 files), ggplot2 (9 files), clusterProfiler (2 files), igraph (1 file), patchwork (1 file), pheatmap (1 file), SingleCellExperiment (1 file), WGCNA (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
15 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;
  • 14 scripts, each with its path and the digest of its content;
  • 18 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

Datasets cited

Data Availability

https://github.com/salihoglu/Alzheimer_AP

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, 4 authors, 88 references.

Cite

This paper

Salihoglu, R., Can, Ş., Dandekar, T., & Bencurova, E. (2026). Integrated Multi-Tissue Transcriptomics Reveals Antagonistic Pleiotropy in Aging and Alzheimer's Disease. Computational and structural biotechnology journal, 35(1), 0134. https://doi.org/10.34133/csbj.0134

BibTeX

@article{salihoglu2026integrated,
author = {Salihoglu, Rana and Can, Şehnaz and Dandekar, Thomas and Bencurova, Elena},
title = {{Integrated Multi-Tissue Transcriptomics Reveals Antagonistic Pleiotropy in Aging and Alzheimer's Disease}},
journal = {Computational and structural biotechnology journal},
year = {2026},
month = jun,
volume = {35},
number = {1},
pages = {0134},
publisher = {AAAS Science Partner Journal Program},
issn = {2001-0370},
doi = {10.34133/csbj.0134},
url = {https://doi.org/10.34133/csbj.0134},
pmid = {42267139},
pmcid = {PMC13243799}
}

RIS

TY - JOUR
AU - Salihoglu, Rana
AU - Can, Şehnaz
AU - Dandekar, Thomas
AU - Bencurova, Elena
TI - Integrated Multi-Tissue Transcriptomics Reveals Antagonistic Pleiotropy in Aging and Alzheimer's Disease
T2 - Computational and structural biotechnology journal
J2 - Comput Struct Biotechnol J
PY - 2026
DA - 2026/06/08
VL - 35
IS - 1
SP - 0134
SN - 2001-0370
PB - AAAS Science Partner Journal Program
DO - 10.34133/csbj.0134
UR - https://doi.org/10.34133/csbj.0134
LA - en
ER -

CSL-JSON

{
"id": "10.34133/csbj.0134",
"type": "article-journal",
"title": "Integrated Multi-Tissue Transcriptomics Reveals Antagonistic Pleiotropy in Aging and Alzheimer's Disease",
"container-title": "Computational and structural biotechnology journal",
"author": [
{
"family": "Salihoglu",
"given": "Rana"
},
{
"family": "Can",
"given": "Şehnaz"
},
{
"family": "Dandekar",
"given": "Thomas"
},
{
"family": "Bencurova",
"given": "Elena"
}
],
"container-title-short": "Comput Struct Biotechnol J",
"volume": "35",
"issue": "1",
"page": "0134",
"DOI": "10.34133/csbj.0134",
"PMID": "42267139",
"PMCID": "PMC13243799",
"ISSN": "2001-0370",
"publisher": "AAAS Science Partner Journal Program",
"URL": "https://doi.org/10.34133/csbj.0134",
"language": "en",
"issued": {
"date-parts": [
[
2026,
6,
8
]
]
}
}

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.1016/j.crmeth.2023.100498 [code]
hdWGCNA identifies co-expression networks in high-dimensional transcriptomics data.
Journal: Cell reports methods
In common: WGCNA, SingleCellExperiment, igraph, 3 other tools, Alzheimer's / dementia, genetics / omics, cellular / molecular, 5 references
[2] doi:10.1186/s13024-025-00892-3 [code]
Molecular hallmarks of excitatory and inhibitory neuronal resilience to Alzheimer's disease.
Journal: Molecular neurodegeneration
In common: SingleCellExperiment, clusterProfiler, igraph, 3 other tools, Alzheimer's / dementia, genetics / omics, cellular / molecular, 4 references
[3] doi:10.1038/s41540-025-00539-5 [code]
Translational disease modeling of peripheral blood identifies type 2 diabetes biomarkers predictive of Alzheimer's disease.
Journal: NPJ systems biology and applications
In common: clusterProfiler, igraph, pheatmap, 3 other tools, Alzheimer's / dementia, genetics / omics, 4 references
[4] doi:10.1016/j.cell.2025.06.031 [code]
Single-cell multiregion epigenomic rewiring in Alzheimer's disease progression and cognitive resilience.
Journal: Cell
In common: SingleCellExperiment, igraph, pheatmap, 3 other tools, Alzheimer's / dementia, genetics / omics, cellular / molecular, 3 references
[5] doi:10.1186/s13059-025-03552-3 [code]
Benchmark of cellular deconvolution methods using a multi-assay dataset from postmortem human prefrontal cortex.
Journal: Genome biology
In common: SingleCellExperiment, clusterProfiler, pheatmap, 3 other tools, genetics / omics, 4 references
[6] doi:10.34133/csbj.0108 [code]
Latent Factor Modeling Reveals Unexpected Spatial Heterogeneity in Human Alzheimer's Disease Brain Transcriptomes.
Journal: Computational and structural biotechnology journal
In common: clusterProfiler, pheatmap, ggplot2, 1 other tool, Alzheimer's / dementia, genetics / omics, cellular / molecular, 6 references
[7] doi:10.1038/s41588-021-00976-y [code]
Genetic analysis of the human microglial transcriptome across brain regions, aging and disease pathologies.
Journal: Nature genetics
In common: igraph, pheatmap, patchwork, 2 other tools, Alzheimer's / dementia, genetics / omics, cellular / molecular, 5 references
[8] doi:10.1093/nar/gkae172 [code]
Comprehensive transcriptome analysis reveals altered mRNA splicing and post-transcriptional changes in the aged mouse brain.
Journal: Nucleic acids research
In common: WGCNA, clusterProfiler, pheatmap, 2 other tools, genetics / omics, cellular / molecular, 5 references
[9] doi:10.1038/s41586-025-09662-z [code]
Lymphoid gene expression supports neuroprotective microglia function.
Journal: Nature
In common: SingleCellExperiment, pheatmap, patchwork, 2 other tools, Alzheimer's / dementia, cellular / molecular, 5 references
[10] doi:10.1002/alz.71804
A meta-refined human Alzheimer's disease-associated gene subset shows partial mouse-model pathway correspondence and limited cross-cohort machine-learning transportability.
Journal: Alzheimer's & dementia : the journal of the Alzheimer's Association
In common: Alzheimer's / dementia, genetics / omics, cellular / molecular, 10 references

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.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.34133/csbj.0134.svg)](https://openscicode.org/badge/doi/10.34133/csbj.0134)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.34133/csbj.0134.svg
   :target: https://openscicode.org/badge/doi/10.34133/csbj.0134
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.34133/csbj.0134"><img src="https://openscicode.org/badge/doi/10.34133/csbj.0134.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge 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: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

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