Integrated Multi-Tissue Transcriptomics Reveals Antagonistic Pleiotropy in Aging and Alzheimer's Disease.
The 18 matches
- [1] § Methods › WGCNA analysis and AP module/gene scoring ↔ 10_modules_AP.R, lines 316–342 · score 0.87 · TOMType, mergeCutHeight, minModuleSize, soft thresholding power, networkType, WGCNA
- [2] § Methods › Functional enrichment of AP-derived gene sets ↔ 09_go_kegg_enrichment.R, lines 67–121 · score 0.81 · clusterProfiler, p.adjust, hsa, simplify, CC, MF
- [3] § Methods › Cell-state enrichment analysis and cell type-adjusted differential expression ↔ 07_optional_gsva_deconv.R, lines 209–229 · score 0.81 · C8 brain cell, Brain cell state, neuron, pericyte, endothelial, excitatory
- [4] § Methods › Functional enrichment of AP-derived gene sets ↔ withDevelopment_section.R, lines 1318–1444 · score 0.81 · Entrez IDs, clusterProfiler, hsa, CC, MF, BP
- [5] § Methods › Pathway and TF analyses ↔ 05_tf_activity.R, lines 290–345 · score 0.81 · TF activities, AP overlap, AP weighted, DoRothEA, TFs, regulons
- [6] § Methods › WGCNA analysis and AP module/gene scoring ↔ 10_modules_AP.R, lines 316–342 · score 0.79 · merge cut height, soft thresholding power, module AP, module gene, WGCNA, network
- [7] § Methods › Gene classification, prioritization, and AP metrics ↔ 02_consensus_meta.R, lines 89–158 · score 0.75 · divergence score, discordant Age, shared score, log2FC, log10, consensus
- [8] § Methods › Pathway and TF analyses ↔ 03_pathway_antagonism.R, lines 16–39 · score 0.69 · fgseaMultilevel, fgseaSimple, permutations, NES, Pathway, antagonism
- [9] § Methods › WGCNA analysis and AP module/gene scoring ↔ 10_modules_AP.R, lines 807–845 · score 0.66 · ego networks, scoring genes, AP class, AP scores, hub, exported
- [10] § Methods › Covariate and brain-only sensitivity audits ↔ 04_ap_candidates.R, lines 665–718 · score 0.60 · AD brain meta, aging meta, AP candidates, filtered, prioritization, class
- [11] § Methods › Cross-condition integration and meta-analysis ↔ 01_prepare_universe.R, lines 71–122 · score 0.58 · HGNC symbols, gene symbol, log2FC, Ensembl
- [12] § Methods › Gene classification, prioritization, and AP metrics ↔ 02_consensus_meta.R, lines 89–158 · score 0.58 · Aging pleiotropy, aging contrasts, log2FC, consensus, prioritization, AD
- [13] § Methods › Cross-condition integration and meta-analysis ↔ 04_ap_candidates.R, lines 156–189 · score 0.57 · HGNC symbols, gene symbol, log2fc, Ensembl, AP
- [14] § Results › TF activity antagonism between healthy aging and AD ↔ 05_tf_activity.R, lines 290–345 · score 0.55 · TF activity, DoRothEA, regulons, NES, map, antagonism
- [15] § Results › Cell state-adjusted robustness of AD-associated AP signals ↔ 07_optional_gsva_deconv.R, lines 209–229 · score 0.53 · Cell state, endothelial, excitatory, astrocyte, inhibitory, oligodendrocyte
- [16] § Results › Integrated hallmark pathway across brain aging and AD ↔ utils.R, lines 109–117 · score 0.53 · SharedDown, SharedUp, AP Vulnerability, AP Resilience, quadrant, pathways
- [17] § Results › Integrated hallmark pathway across brain aging and AD ↔ 05_tf_activity.R, lines 147–155 · score 0.52 · SharedDown, SharedUp, AP Vulnerability, AP Resilience, quadrant, map
- [18] § Methods › WGCNA analysis and AP module/gene scoring ↔ 10_modules_AP.R, lines 1–60 · score 0.51 · aging samples, finite, young, GSE48350, WGCNA, Weighted
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 · 1,242 lines · 59 KB · no license · 4 matches
- #!/usr/bin/env Rscript
- # =============================================================================
- # 10_modules_AP_consensus.R — UPDATED FULL SCRIPT (robust covariates)
- # Uses ONLY:
- # - results_aging_brain/GSE48350_samples_ALL_tissues_Young_vs_Old.csv
- # (all brain healthy aging samples; includes young + old; 150 total)
- # - results_AD/samples_ALL_tissues_ageGT59.csv (take only rows with group == "AD")
- # for sample annotation.
- # =============================================================================
- suppressPackageStartupMessages({
- library(dplyr); library(readr); library(stringr); library(tidyr)
- library(purrr); library(tibble); library(ggplot2); library(scales)
- library(WGCNA)
- suppressWarnings({
- ok_igraph <- requireNamespace("igraph", quietly=TRUE)
- ok_ggraph <- requireNamespace("ggraph", quietly=TRUE) && requireNamespace("tidygraph", quietly=TRUE)
- })
- })
- set.seed(2371)
- allowWGCNAThreads()
- options(stringsAsFactors = FALSE)
- # ------------------ Config / IO ----------------------------------------------
- source("utils.R")
- load(".config_env.RData") # expects: AGE_BRAIN_EXPR_RDS, AD_BRAIN_EXPR_RDS, outdir, AP_COLORS, PNG_DPI, REGION_P_FDR
- dir.create(file.path(outdir, "wgcna"), FALSE, TRUE)
- .dirnets <- file.path(outdir, "wgcna", "networks"); dir.create(.dirnets, FALSE, TRUE)
- # CSVs (override via env)
- AD_SAMPLES_CSV <- Sys.getenv("AD_SAMPLES_CSV",
- unset = file.path("results_AD","samples_ALL_tissues_ageGT59.csv"))
- HEALTHY_SAMPLES_CSV <- Sys.getenv("HEALTHY_SAMPLES_CSV",
- unset = file.path("results_aging_brain","GSE48350_samples_ALL_tissues_Young_vs_Old.csv"))
- # Tunables
- CONSENSUS_TOPK_GENES <- as.integer(Sys.getenv("CONSENSUS_TOPK_GENES", unset="15000"))
- MIN_FINITE_PROP <- as.numeric(Sys.getenv("MIN_FINITE_PROP", unset="0.80"))
- MIN_FINITE_MIN <- as.integer(Sys.getenv("MIN_FINITE_MIN", unset="12"))
- NETWORK_MAX_GENES <- as.integer(Sys.getenv("NETWORK_MAX_GENES", unset="400"))
- EDGE_TOPK_PER_GENE <- as.integer(Sys.getenv("EDGE_TOPK_PER_GENE", unset="5"))
- EDGE_MIN_TOM <- as.numeric(Sys.getenv("EDGE_MIN_TOM", unset="0.05"))
- EDGE_MIN_ADJ <- as.numeric(Sys.getenv("EDGE_MIN_ADJ", unset="0.10"))
- TOP_HUBS_PER_MODULE <- as.integer(Sys.getenv("TOP_HUBS_PER_MODULE", unset="10"))
- MIN_MODULE_SIZE <- as.integer(Sys.getenv("MIN_MODULE_SIZE", unset="120"))
- MIN_EDGES_TARGET <- as.integer(Sys.getenv("MIN_EDGES_TARGET", unset="40"))
- MIN_EDGE_MIN_TOM <- as.numeric(Sys.getenv("MIN_EDGE_MIN_TOM", unset="0.01"))
- MIN_EDGE_MIN_ADJ <- as.numeric(Sys.getenv("MIN_EDGE_MIN_ADJ", unset="0.02"))
- FORCE_EXPORT_IF_EMPTY<- as.logical(Sys.getenv("FORCE_EXPORT_IF_EMPTY",unset="TRUE"))
- TOP_EXPORT <- as.integer(Sys.getenv("AP_TOP_MODULE_EXPORT", unset="6"))
- TOP_EGO_PER_CLASS <- as.integer(Sys.getenv("TOP_EGO_PER_CLASS", unset="15"))
- # Optional weightings
- AP_SCORE_USE_KME <- as.logical(Sys.getenv("AP_SCORE_USE_KME", unset="FALSE"))
- AP_MODULE_USE_KME_WEIGHTS <- as.logical(Sys.getenv("AP_MODULE_USE_KME_WEIGHTS", unset="TRUE"))
- `%||%` <- function(a, b) if (!is.null(a) && length(a)>0 && !all(is.na(a))) a else b
- log_msg <- function(...) cat(format(Sys.time(), "[%Y-%m-%d %H:%M:%S]"), sprintf(...), "\n")
- psafe <- function(p) pmax(pmin(as.numeric(p), 1), .Machine$double.xmin)
- stopifnot(file.exists(AGE_BRAIN_EXPR_RDS), file.exists(AD_BRAIN_EXPR_RDS))
- stopifnot(file.exists(AD_SAMPLES_CSV), file.exists(HEALTHY_SAMPLES_CSV))
- # ------------------ Helpers: IO & metadata -----------------------------------
- read_samples_table <- function(path){
- tryCatch(readr::read_csv(path, show_col_types=FALSE),
- error=function(e) tryCatch(readr::read_tsv(path, show_col_types=FALSE),
- error=function(e2) readr::read_delim(path, delim="\t", show_col_types=FALSE)))
- }
- load_expr_meta <- function(path) {
- obj <- readRDS(path)
- if (is.list(obj) && all(c("expr","meta") %in% names(obj))) {
- expr <- as.matrix(obj$expr); meta <- as.data.frame(obj$meta)
- } else if (is.matrix(obj) || is.data.frame(obj)) {
- expr <- as.matrix(obj); meta <- data.frame(sample_id=colnames(expr))
- } else stop("Unsupported RDS format at ", path)
- if (is.null(rownames(expr))) stop("Expression must have rownames=gene identifiers.")
- if (!"sample_id" %in% names(meta)) meta$sample_id <- rownames(meta) %||% colnames(expr)
- meta <- meta %>% distinct(sample_id, .keep_all=TRUE)
- keep <- intersect(colnames(expr), meta$sample_id)
- list(expr=expr[, keep, drop=FALSE], meta=meta[match(keep, meta$sample_id), , drop=FALSE])
- }
- coerce_meta <- function(meta, context=c("healthy","ad")) {
- context <- match.arg(context)
- nm <- tolower(names(meta))
- pick <- function(cands) { i <- which(nm %in% cands); if (length(i)) names(meta)[i[1]] else NA }
- age_col <- pick(c("age","age_years","ages","age_at_death","age_at_sampling"))
- dz_col <- pick(c("disease","diagnosis","dx","ad_status","group","phenotype"))
- sex_col <- pick(c("sex","gender"))
- bat_col <- pick(c("batch","plate","run","study_batch"))
- reg_col <- pick(c("region","brain_region","tissue","area","region_raw"))
- meta$age <- if (!is.na(age_col)) suppressWarnings(as.numeric(meta[[age_col]])) else NA_real_
- if (!is.na(dz_col)) {
- v <- as.character(meta[[dz_col]])
- is_ad <- grepl("\\b(ad|alz|alzheimer|case|patient|disease)\\b", v, TRUE)
- is_ctrl <- grepl("\\b(ctrl|control|cn|healthy|normal)\\b", v, TRUE)
- meta$disease <- ifelse(is_ad, 1L, ifelse(is_ctrl, 0L, NA_integer_))
- } else meta$disease <- if (context=="ad") NA_integer_ else 0L
- meta$sex <- if (!is.na(sex_col)) as.character(meta[[sex_col]]) else NA_character_
- meta$batch <- if (!is.na(bat_col)) as.character(meta[[bat_col]]) else NA_character_
- meta$region <- if (!is.na(reg_col)) as.character(meta[[reg_col]]) else NA_character_
- meta$context <- context
- meta
- }
- merge_external_info <- function(meta, csv_path, dataset_label=""){
- if (!file.exists(csv_path)) return(meta)
- ext <- read_samples_table(csv_path)
- nm <- tolower(names(ext))
- pick <- function(...) { cands <- c(...); i <- which(nm %in% tolower(cands)); if (length(i)) names(ext)[i[1]] else NA }
- idc <- pick("sample_id","gsm","id","sample","geo_accession")
- if (is.na(idc)) { log_msg("[%s] No sample_id-like column in %s; skipping merge.", dataset_label, csv_path); return(meta) }
- ext <- ext %>% mutate(sample_id = as.character(.data[[idc]]))
- agec <- pick("age","age_years","Age","AgeYears")
- sexc <- pick("sex","gender")
- regc <- pick("region","brain_region","tissue","area","region_raw")
- tisc <- pick("tissue","Tissue")
- aggc <- pick("age_group","Age_group","AGE_GROUP")
- if (!is.na(agec)) ext$age <- suppressWarnings(as.numeric(ext[[agec]]))
- if (!is.na(sexc)) ext$sex <- as.character(ext[[sexc]])
- if (!is.na(regc)) ext$region <- as.character(ext[[regc]])
- if (!is.na(tisc)) ext$tissue <- as.character(ext[[tisc]])
- if (!is.na(aggc)) ext$age_group <- as.character(ext[[aggc]])
- meta2 <- meta %>%
- left_join(ext %>% select(sample_id, any_of(c("age","sex","region","tissue","age_group"))), by="sample_id")
- for (col in c("age","sex","region","tissue","age_group")) {
- new <- paste0(col, ".y"); old <- paste0(col, ".x")
- if (new %in% names(meta2)) { meta2[[col]] <- meta2[[new]] %||% meta2[[old]]; meta2[[new]] <- NULL; meta2[[old]] <- NULL }
- }
- meta2
- }
- # ------------------ Cleaning & math ------------------------------------------
- harmonize_gene_names <- function(E) {
- rn <- rownames(E)
- rn <- gsub("\\s+", "", rn)
- rn <- gsub("\\.\\d+$", "", rn)
- rownames(E) <- toupper(rn)
- E
- }
- dedup_by_maxvar <- function(E) {
- rn <- rownames(E)
- if (anyDuplicated(rn)) {
- idxs <- split(seq_along(rn), rn)
- pick <- vapply(idxs, function(ix){ vv <- apply(E[ix,,drop=FALSE], 1, stats::var, na.rm=TRUE); ix[which.max(vv)][1] }, integer(1))
- E <- E[pick,,drop=FALSE]; rownames(E) <- names(pick)
- }
- E
- }
- median_impute_rows <- function(E) {
- for (i in seq_len(nrow(E))) {
- v <- E[i,]; ok <- is.finite(v)
- if (!all(ok)) { if (any(ok)) { med <- stats::median(v[ok]); v[!ok] <- med; E[i,] <- v } else { E[i,] <- 0 } }
- }
- E
- }
- clean_expression <- function(E, name="") {
- log_msg("[%s] raw: %s genes x %s samples", name, nrow(E), ncol(E))
- E <- harmonize_gene_names(E) |> dedup_by_maxvar()
- finite_counts <- rowSums(is.finite(E))
- min_needed <- max(MIN_FINITE_MIN, ceiling(MIN_FINITE_PROP * ncol(E)))
- keep <- finite_counts >= min_needed
- if (!any(keep)) stop(sprintf("[%s] No genes pass finite filter.", name))
- E <- E[keep,,drop=FALSE] |> median_impute_rows()
- v <- apply(E, 1, stats::var)
- E <- E[v > 0,, drop=FALSE]
- log_msg("[%s] cleaned: %s genes x %s samples (min finite per gene %s)", name, nrow(E), ncol(E), min_needed)
- E
- }
- sel_top_var_consensus <- function(E1, E2, k=15000, tag="CONS") {
- v1 <- apply(E1, 1, stats::var); v2 <- apply(E2, 1, stats::var)
- r1 <- rank(-v1, ties.method="average"); r2 <- rank(-v2, ties.method="average")
- rs <- r1 + r2; k <- min(k, length(rs))
- keep <- names(sort(rs))[seq_len(k)]
- log_msg("[%s] choosing top %s / %s shared genes by consensus variance", tag, k, length(rs))
- list(E1=E1[keep,,drop=FALSE], E2=E2[keep,,drop=FALSE], genes=keep)
- }
- std_me_names <- function(x) paste0("ME", sprintf("%02d", as.integer(gsub("^ME","", as.character(x)))))
- # ===== NEW: robust covariate utilities =======================================
- sanitize_covars <- function(covs, sample_order=NULL) {
- if (is.null(covs) || ncol(covs)==0) return(NULL)
- covs <- as.data.frame(covs, stringsAsFactors = FALSE)
- if (!is.null(sample_order)) {
- covs <- covs[match(sample_order, rownames(covs)), , drop=FALSE]
- }
- for (j in names(covs)) {
- v <- covs[[j]]
- if (is.character(v) || is.logical(v)) covs[[j]] <- droplevels(factor(v))
- }
- keep <- vapply(covs, function(col) any(is.finite(col) | !is.na(col)), logical(1))
- covs <- covs[, keep, drop=FALSE]
- if (ncol(covs)==0) return(NULL)
- drop_j <- logical(ncol(covs))
- for (j in seq_along(covs)) {
- v <- covs[[j]]
- if (is.factor(v)) {
- v <- droplevels(v)
- if (nlevels(v) < 2) drop_j[j] <- TRUE else covs[[j]] <- v
- } else if (is.numeric(v)) {
- if (all(!is.finite(v)) || stats::var(v[is.finite(v)])==0) drop_j[j] <- TRUE
- }
- }
- covs <- covs[, !drop_j, drop=FALSE]
- if (ncol(covs)==0) return(NULL)
- covs
- }
- drop_collinear <- function(y, covs, thr=0.98) {
- if (is.null(covs) || ncol(covs)==0) return(NULL)
- mm <- tryCatch(model.matrix(~ . , data=cbind.data.frame(covs)), error=function(e) NULL)
- if (is.null(mm)) return(NULL)
- mm <- mm[, colnames(mm)!="(Intercept)", drop=FALSE]
- if (ncol(mm) <= 1) return(as.data.frame(covs))
- C <- suppressWarnings(cor(mm, use="pairwise.complete.obs"))
- diag(C) <- 0
- to_drop <- c()
- while (TRUE) {
- mx <- suppressWarnings(max(abs(C), na.rm=TRUE))
- if (!is.finite(mx) || mx < thr) break
- ij <- which(abs(C) == mx, arr.ind=TRUE)[1,]
- jdrop <- colnames(C)[ij[2]]
- to_drop <- c(to_drop, jdrop)
- keep <- setdiff(colnames(C), to_drop)
- if (length(keep) < 2) break
- C <- C[keep, keep, drop=FALSE]
- }
- if (length(to_drop)) {
- keep <- setdiff(colnames(mm), to_drop)
- return(as.data.frame(covs)) # keep sanitized original; mm used only for checks
- }
- as.data.frame(covs)
- }
- # ===== Associations ===========================================================
- assoc_linear <- function(y, x, covars=NULL, min_n=4) {
- df <- data.frame(y=y, x=x)
- if (!is.null(covars)) df <- cbind(df, covars)
- df <- df[complete.cases(df), ]
- if (nrow(df) < min_n || sd(df$x, na.rm=TRUE) == 0) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
- fit <- tryCatch(lm(y ~ x + ., df), error=function(e) NULL)
- if (is.null(fit)) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
- s <- summary(fit)$coefficients
- if (!"x" %in% rownames(s)) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
- c(beta=unname(s["x","Estimate"]), se=unname(s["x","Std. Error"]), p=unname(s["x","Pr(>|t|)"]), n=nrow(df))
- }
- assoc_binary <- function(y, x, covars=NULL, min_n=6) {
- df <- data.frame(y=y, x=x)
- if (!is.null(covars)) df <- cbind(df, covars)
- df <- df[complete.cases(df), ]
- ux <- unique(df$x); ux <- ux[is.finite(ux)]
- if (length(ux) < 2 || nrow(df) < min_n) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
- fit <- tryCatch(lm(y ~ x + ., df), error=function(e) NULL)
- if (is.null(fit)) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
- s <- summary(fit)$coefficients
- if (!"x" %in% rownames(s)) return(c(beta=NA, se=NA, p=NA, n=nrow(df)))
- c(beta=unname(s["x","Estimate"]), se=unname(s["x","Std. Error"]), p=unname(s["x","Pr(>|t|)"]), n=unname(nrow(df)))
- }
- fisher_combine_p <- function(pvals){ pvals <- psafe(pvals); 1 - pchisq(-2*sum(log(pvals)), df=2*length(pvals)) }
- # ------------------ Load datasets --------------------------------------------
- age_ds <- load_expr_meta(AGE_BRAIN_EXPR_RDS); age_ds$meta <- coerce_meta(age_ds$meta, "healthy")
- ad_ds <- load_expr_meta(AD_BRAIN_EXPR_RDS); ad_ds$meta <- coerce_meta(ad_ds$meta, "ad")
- # Merge external info
- # Healthy aging annotations from GSE48350_samples_ALL_tissues_Young_vs_Old.csv (brain)
- age_ds$meta <- merge_external_info(age_ds$meta, HEALTHY_SAMPLES_CSV, "GSE48350_healthy")
- # AD annotations from samples_ALL_tissues_ageGT59.csv (filter to AD rows only)
- ad_ds$meta <- merge_external_info(ad_ds$meta, AD_SAMPLES_CSV, "AD>59")
- # AD ids from CSV — take only group == "AD" if 'group' column exists; else assume all rows are AD
- ad_csv_raw <- read_samples_table(AD_SAMPLES_CSV)
- stopifnot("sample_id" %in% names(ad_csv_raw))
- grp_col <- names(ad_csv_raw)[tolower(names(ad_csv_raw))=="group"] %||% NA
- ad_csv <- if (is.na(grp_col)) {
- log_msg("Note: 'group' not found in AD CSV; assuming all rows are AD.")
- ad_csv_raw
- } else {
- dplyr::filter(ad_csv_raw, grepl("^\\s*AD\\s*$", .data[[grp_col]], ignore.case = TRUE))
- }
- stopifnot(nrow(ad_csv)>0)
- ad_ids <- intersect(colnames(ad_ds$expr), as.character(ad_csv$sample_id))
- stopifnot(length(ad_ids)>0)
- # ------------------ Healthy-only for CONSENSUS -------------------------------
- # Healthy aging cohort from GSE48350 CSV (all brain healthy samples; young + old)
- expr_age_healthy <- age_ds$expr[, intersect(colnames(age_ds$expr),
- age_ds$meta$sample_id[(age_ds$meta$disease %||% 0) == 0]), drop=FALSE]
- # Controls from AD dataset (explicitly exclude AD ids)
- expr_ctrl_healthy <- ad_ds$expr[, intersect(colnames(ad_ds$expr),
- ad_ds$meta$sample_id[(ad_ds$meta$disease %||% 0) == 0 &
- !(ad_ds$meta$sample_id %in% ad_ids)]), drop=FALSE]
- EA0 <- clean_expression(expr_age_healthy, "GSE48350_healthy")
- EC0 <- clean_expression(expr_ctrl_healthy, "GSE48350_controls")
- # Shared gene universe and top-K consensus
- genes_shared <- intersect(rownames(EA0), rownames(EC0))
- EA_shared <- EA0[genes_shared,,drop=FALSE]
- EC_shared <- EC0[genes_shared,,drop=FALSE]
- cons <- sel_top_var_consensus(EA_shared, EC_shared, k=CONSENSUS_TOPK_GENES, tag="CONS")
- EA <- cons$E1; EC <- cons$E2; genes_cons <- cons$genes
- # WGCNA consensus on healthy brains
- DatA <- as.data.frame(t(EA)); DatC <- as.data.frame(t(EC))
- 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 }
- pA <- pick_power(DatA); pC <- pick_power(DatC)
- cons_power <- floor(median(c(pA,pC), na.rm=TRUE)); if (!is.finite(cons_power)) cons_power <- 6
- log_msg("Consensus soft-threshold power: %s (A=%s, C=%s) with %s genes", cons_power, pA, pC, length(genes_cons))
- multiExpr <- list(HealthyA= list(data=DatA), HealthyC= list(data=DatC))
- net_cons <- tryCatch(
- blockwiseConsensusModules(
- multiExpr,
- power=cons_power, networkType="signed", TOMType="signed",
- minModuleSize=MIN_MODULE_SIZE, reassignThreshold=0,
- mergeCutHeight=0.25, numericLabels=TRUE, pamRespectsDendro=FALSE, verbose=2
- ),
- error=function(e){
- log_msg("Consensus failed: %s. Falling back to single-dataset (HealthyA).", conditionMessage(e))
- single <- blockwiseModules(DatA, power=cons_power, networkType="signed", TOMType="signed",
- minModuleSize=MIN_MODULE_SIZE, reassignThreshold=0,
- mergeCutHeight=0.25, numericLabels=TRUE, pamRespectsDendro=FALSE, verbose=2)
- list(colors = single$colors, dendrograms = single$dendrograms, blockGenes = single$blockGenes)
- }
- )
- cons_colors <- net_cons$colors; names(cons_colors) <- colnames(DatA)
- module_df <- tibble(
- gene = names(cons_colors),
- module_label = as.integer(cons_colors),
- module = std_me_names(as.integer(cons_colors))
- )
- write_csv(module_df, file.path(outdir, "wgcna", "Consensus_modules_genes.csv"))
- # ------------------ Eigengenes helper ----------------------------------------
- compute_MEs <- function(EgxS, colors_vec, prefix="") {
- if (is.null(EgxS) || ncol(EgxS) < 2) { log_msg("%s compute_MEs: not enough samples (%s).", prefix, ncol(EgxS)); return(NULL) }
- genes <- intersect(rownames(EgxS), names(colors_vec))
- cols <- colors_vec[genes]; cols <- cols[!is.na(cols) & cols != 0]
- genes <- names(cols)
- if (length(genes) < 3) { log_msg("%s compute_MEs: <3 non-grey genes.", prefix); return(NULL) }
- X <- as.data.frame(t(EgxS[genes, , drop=FALSE]))
- MEs <- tryCatch(orderMEs(moduleEigengenes(X, colors=cols, excludeGrey=TRUE)$eigengenes),
- error=function(e){ log_msg("%s compute_MEs: %s", prefix, conditionMessage(e)); NULL })
- if (!is.null(MEs)) { rownames(MEs) <- rownames(X); colnames(MEs) <- std_me_names(colnames(MEs)) }
- MEs
- }
- # ------------------ Cohorts (age metadata, continuous) -----------------------
- age_meta1 <- age_ds$meta %>%
- mutate(disease = 0L) %>%
- mutate(age = suppressWarnings(as.numeric(age))) %>% filter(is.finite(age))
- age_meta2 <- ad_ds$meta %>%
- mutate(disease = ifelse(sample_id %in% ad_ids, 1L, disease)) %>%
- mutate(disease = ifelse(is.na(disease), 0L, disease)) %>% filter(disease==0) %>%
- mutate(age = suppressWarnings(as.numeric(age))) %>% filter(is.finite(age))
- E_age1 <- EA[, intersect(colnames(EA), age_meta1$sample_id), drop=FALSE]
- E_age2 <- EC[, intersect(colnames(EC), age_meta2$sample_id), drop=FALSE]
- # 3) AD vs Control (>59) in GSE48350
- ctrl_59_meta <- ad_ds$meta %>%
- mutate(disease = ifelse(sample_id %in% ad_ids, 1L, disease),
- disease = ifelse(is.na(disease), 0L, disease),
- age = suppressWarnings(as.numeric(age))) %>%
- filter(disease==0, is.finite(age), age > 59)
- ad_59_ids <- intersect(colnames(ad_ds$expr), ad_ids)
- region_pick <- function(df){
- 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))
- }
- ad_meta <- tibble(sample_id = ad_59_ids, disease=1L) %>%
- left_join(ad_csv %>% transmute(sample_id=as.character(sample_id),
- age = suppressWarnings(as.numeric(age)),
- sex = as.character(sex),
- region = region_pick(ad_csv),
- tissue = as.character(tissue)), by="sample_id")
- ctrl_meta <- ctrl_59_meta %>% select(sample_id, age, sex, region, tissue, disease)
- ad_ctrl_meta <- bind_rows(ad_meta %>% mutate(context="ad"),
- ctrl_meta %>% mutate(context="control")) %>%
- mutate(age = suppressWarnings(as.numeric(age)))
- AD_full0 <- ad_ds$expr %>% harmonize_gene_names() %>% { .[intersect(rownames(.), genes_cons), , drop=FALSE] }
- E_ad_ctrl59 <- AD_full0[, intersect(colnames(AD_full0), ad_ctrl_meta$sample_id), drop=FALSE] |> median_impute_rows()
- log_msg("[AD>59] genes=%s samples=%s (AD=%s, CTRL=%s)",
- nrow(E_ad_ctrl59), ncol(E_ad_ctrl59),
- sum(ad_ctrl_meta$disease==1, na.rm=TRUE),
- sum(ad_ctrl_meta$disease==0, na.rm=TRUE))
- # ------------------ Module-trait heatmaps (eigengene view) -------------------
- mod_trait_heatmap <- function(MEs, meta, mode=c("age","ad"), prefix=""){
- if (is.null(MEs) || ncol(MEs)==0) { log_msg("%s heatmap: no eigengenes; skipping.", prefix); return(invisible(NULL)) }
- mode <- match.arg(mode)
- traits <- if (mode=="age") data.frame(age = suppressWarnings(as.numeric(meta$age)))
- else data.frame(disease = suppressWarnings(as.numeric(meta$disease)))
- rownames(traits) <- meta$sample_id
- keep <- intersect(rownames(MEs), rownames(traits))
- if (length(keep) < 3) { log_msg("%s heatmap: <3 overlapping samples. Skipping.", prefix); return(invisible(NULL)) }
- MEs <- MEs[keep,,drop=FALSE]; traits <- traits[keep,,drop=FALSE]
- safe_cor_p <- function(x, y){
- ok <- is.finite(x) & is.finite(y); n <- sum(ok); if (n < 3) return(c(cor=NA_real_, p=NA_real_))
- x <- x[ok]; y <- y[ok]; if (sd(x)==0 || sd(y)==0) return(c(cor=NA_real_, p=NA_real_))
- r <- suppressWarnings(cor(x, y, method="pearson")); if (!is.finite(r)) return(c(cor=NA_real_, p=NA_real_))
- tstat <- r * sqrt((n-2)/(1 - r^2)); p <- 2 * stats::pt(-abs(tstat), df=n-2); c(cor=r, p=p)
- }
- C <- matrix(NA_real_, nrow=ncol(MEs), ncol=ncol(traits), dimnames=list(colnames(MEs), colnames(traits))); P <- C
- 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] }
- if (all(!is.finite(C))) { log_msg("%s heatmap: all correlations NA. Skipping.", prefix); return(invisible(NULL)) }
- lab <- paste0(sprintf("%.2f", C), "\n(", ifelse(is.finite(P), sprintf("%.1e", P), "NA"), ")")
- df <- as.data.frame(as.table(C)); names(df) <- c("ME","Trait","Cor"); df$P <- as.vector(P); df$lab <- as.vector(lab)
- p <- ggplot(df, aes(Trait, ME, fill=Cor, label=lab)) +
- geom_tile() + geom_text(size=3) +
- scale_fill_gradient2(low="#2166AC", mid="white", high="#B2182B", midpoint=0, na.value="grey85") +
- labs(title=paste0(prefix, " module–trait relationships (", mode, ")"), x=NULL, y=NULL) +
- theme_minimal(base_size=12)
- 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)
- }
- # ------------------ Module associations (eigengene) --------------------------
- MEs_age1 <- compute_MEs(E_age1, cons_colors, prefix="GSE48350_AgingCont")
- MEs_age2 <- compute_MEs(E_age2, cons_colors, prefix="GSE48350Ctrl_AgingCont")
- MEs_ad59 <- compute_MEs(E_ad_ctrl59, cons_colors, prefix="GSE48350_AD>59")
- mod_trait_heatmap(MEs_age1, age_meta1, mode="age", prefix="GSE48350_AgingCont")
- mod_trait_heatmap(MEs_age2, age_meta2, mode="age", prefix="GSE48350Ctrl_AgingCont")
- mod_trait_heatmap(MEs_ad59, ad_ctrl_meta, mode="ad", prefix="GSE48350_AD")
- # ======== KEY FIX: robust covariate building for association tests ===========
- build_covars <- function(meta, include=c("sex","batch","region","tissue","age")) {
- use_cols <- intersect(include, names(meta))
- if (!length(use_cols)) return(NULL)
- covs <- meta[, use_cols, drop=FALSE]
- rownames(covs) <- meta$sample_id
- sanitize_covars(covs)
- }
- test_binary_trait <- function(MEs, meta, trait, include_covars=c("sex","batch","region","tissue","age")){
- if (is.null(MEs) || ncol(MEs)==0) return(tibble(module=character(), beta=numeric(), p=numeric(), FDR=numeric()))
- stopifnot(trait %in% names(meta))
- keep <- intersect(rownames(MEs), meta$sample_id)
- if (length(keep) < 6) return(tibble(module=character(), beta=numeric(), p=numeric(), FDR=numeric()))
- MEs <- MEs[keep,,drop=FALSE]
- mm <- meta[match(keep, meta$sample_id), , drop=FALSE]
- covs_raw <- build_covars(mm, include=include_covars)
- covs <- sanitize_covars(covs_raw, sample_order=rownames(MEs))
- if (!is.null(covs)) {
- covs <- drop_collinear(as.numeric(mm[[trait]]), covs, thr=0.98)
- }
- out <- bind_rows(lapply(colnames(MEs), function(m){
- y <- as.numeric(MEs[,m])
- a <- assoc_binary(y, as.numeric(mm[[trait]]), covs, min_n=6)
- tibble(module=m, beta=as.numeric(a["beta"]), p=as.numeric(a["p"]))
- }))
- out$p <- psafe(out$p); out$FDR <- p.adjust(out$p, "BH"); out
- }
- 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"))
- 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"))
- res_ad_mod <- test_binary_trait(MEs_ad59, ad_ctrl_meta, "disease", include_covars=c("sex","batch","region","tissue","age"))
- res_age_mod1$module <- std_me_names(res_age_mod1$module)
- res_age_mod2$module <- std_me_names(res_age_mod2$module)
- res_ad_mod$module <- std_me_names(res_ad_mod$module)
- combine_age_modules <- function(a1, a2){
- if (nrow(a1)>0 && nrow(a2)>0) {
- a1 %>% rename(beta1=beta, p1=p, FDR1=FDR) %>%
- full_join(a2 %>% rename(beta2=beta, p2=p, FDR2=FDR), by="module") %>%
- mutate(beta = rowMeans(cbind(beta1, beta2), na.rm=TRUE),
- p = fisher_combine_p(na.omit(c(psafe(p1), psafe(p2)))),
- FDR = p.adjust(psafe(p), "BH")) %>%
- select(module, beta, p, FDR, beta1, beta2, p1, p2, FDR1, FDR2)
- } else {
- a <- if (nrow(a1)>0) a1 else a2
- a %>% rename(beta=beta, p=p, FDR=FDR)
- }
- }
- age_combined_mod <- combine_age_modules(res_age_mod1, res_age_mod2)
- ap_direction <- function(a, b) {
- res <- rep(NA_character_, length(a))
- res[a > 0 & b > 0] <- "AgeUp-ADDown (AP_Resilience)"
- res[a < 0 & b < 0] <- "AgeDown-ADUp (AP_Vulnerability)"
- res[is.na(res)] <- "Other"; res
- }
- call_ap_modules <- function(df_age, df_ad) {
- df <- full_join(
- df_age %>% select(module, beta_age=beta, p_age=p, FDR_age=FDR),
- df_ad %>% select(module, beta_ad=beta, p_ad=p, FDR_ad=FDR),
- by="module"
- ) %>%
- mutate(p_age = psafe(p_age), p_ad = psafe(p_ad),
- direction = ap_direction(beta_age, -beta_ad),
- AP_score = (sign(beta_age) * -sign(beta_ad)) * ( -log10(p_age) + -log10(p_ad) ),
- age_sig = FDR_age < REGION_P_FDR,
- ad_sig = FDR_ad < REGION_P_FDR)
- df
- }
- AP_modules <- call_ap_modules(age_combined_mod, res_ad_mod)
- sizes <- module_df %>% count(module, name="module_size")
- AP_modules <- AP_modules %>%
- left_join(sizes, by="module") %>%
- mutate(AP_class = case_when(
- direction == "AgeUp-ADDown (AP_Resilience)" ~ "AP_Resilience",
- direction == "AgeDown-ADUp (AP_Vulnerability)" ~ "AP_Vulnerability",
- TRUE ~ "Other")) %>%
- arrange(desc(AP_score))
- write_csv(AP_modules, file.path(outdir, "AP_modules.csv"))
- # ------------------ Hubs (kME) -----------------------------------------------
- hub_scores <- function(module_df, EgxS) {
- split(module_df$gene, module_df$module) %>%
- imap_dfr(function(genes, m) {
- g <- intersect(genes, rownames(EgxS))
- if (length(g) < 3 || ncol(EgxS) < 2) return(tibble(module=m, gene=NA_character_, kME=NA_real_))
- datExpr <- t(EgxS[g, , drop=FALSE])
- ME <- WGCNA::moduleEigengenes(datExpr, rep(1, ncol(datExpr)))$eigengenes[,1]
- kME <- suppressWarnings(cor(datExpr, ME, use="pairwise.complete.obs"))
- tibble(module=m, gene=colnames(datExpr), kME=as.numeric(kME)) %>% arrange(desc(kME)) %>% head(TOP_HUBS_PER_MODULE)
- })
- }
- age_hubs <- hub_scores(module_df, EA)
- ctrl_hubs <- hub_scores(module_df, EC)
- write_csv(age_hubs, file.path(outdir, "AP_module_hubs_GSE48350_healthy.csv"))
- write_csv(ctrl_hubs, file.path(outdir, "AP_module_hubs_GSE48350_controls.csv"))
- # -------------------- export summary -----------------------------------------
- write_csv(AP_modules, file.path(outdir, "AP_modules_summary_from_genes.csv"))
- cat("Quadrant plot and module summary saved in:", outdir, "\n")
- # ============================================================================#
- # ================= AP gene-level scoring (AGE = CONTINUOUS) =================#
- # ============================================================================#
- log_msg("Scoring genes for AP importance (age=continuous per cohort, meta-analyzed)...")
- # Covariates
- cov_age1 <- build_covars(age_meta1, include=c("sex","batch","region","tissue"))
- cov_age2 <- build_covars(age_meta2, include=c("sex","batch","region","tissue"))
- cov_ad <- build_covars(ad_ctrl_meta, include=c("sex","batch","region","tissue","age"))
- 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)
- # Align matrices & traits
- align_cols <- function(E, ids) E[, intersect(colnames(E), ids), drop=FALSE]
- Eg_age1 <- align_cols(E_age1, age_meta1$sample_id)
- Eg_age2 <- align_cols(E_age2, age_meta2$sample_id)
- Eg_ad <- align_cols(E_ad_ctrl59, ad_ctrl_meta$sample_id)
- x_age1 <- setNames(scale(age_meta1$age)[,1], age_meta1$sample_id) # scaled
- x_age2 <- setNames(scale(age_meta2$age)[,1], age_meta2$sample_id)
- x_ad <- setNames(ad_ctrl_meta$disease, ad_ctrl_meta$sample_id)
- # Association matrices
- do_assoc_matrix_cont <- function(EgxS, x, covars, min_n=4) {
- if (is.null(EgxS) || ncol(EgxS) < min_n) {
- log_msg("Assoc matrix (continuous): too few samples (%s).", ncol(EgxS));
- return(tibble(gene=character(), beta=numeric(), se=numeric(), p=numeric()))
- }
- if (!is.null(covars)) {
- covars <- sanitize_covars(covars, sample_order=colnames(EgxS))
- }
- genes <- rownames(EgxS)
- purrr::map_dfr(genes, function(g){
- y <- EgxS[g, ]
- a <- assoc_linear(y, x[colnames(EgxS)], covars, min_n=min_n)
- tibble(gene=g, beta=as.numeric(a["beta"]), se=as.numeric(a["se"]), p=psafe(a["p"]))
- })
- }
- do_assoc_matrix_bin <- function(EgxS, x, covars, min_n=6) {
- if (is.null(EgxS) || ncol(EgxS) < min_n) {
- log_msg("Assoc matrix (binary): too few samples (%s).", ncol(EgxS));
- return(tibble(gene=character(), beta=numeric(), se=numeric(), p=numeric()))
- }
- if (!is.null(covars)) {
- covars <- sanitize_covars(covars, sample_order=colnames(EgxS))
- }
- genes <- rownames(EgxS)
- purrr::map_dfr(genes, function(g){
- y <- EgxS[g, ]
- a <- assoc_binary(y, x[colnames(EgxS)], covars, min_n=min_n)
- tibble(gene=g, beta=as.numeric(a["beta"]), se=as.numeric(a["se"]), p=psafe(a["p"]))
- })
- }
- ga1 <- do_assoc_matrix_cont(Eg_age1, x_age1, cov_age1, min_n=4) %>% rename(beta_age1=beta, se_age1=se, p_age1=p)
- ga2 <- do_assoc_matrix_cont(Eg_age2, x_age2, cov_age2, min_n=4) %>% rename(beta_age2=beta, se_age2=se, p_age2=p)
- gad <- do_assoc_matrix_bin (Eg_ad, x_ad, cov_ad, min_n=6) %>% rename(beta_ad=beta, se_ad=se, p_ad=p)
- # Combine aging cohorts (inverse-variance for beta, Fisher for p)
- combine_age_genes <- function(ga1, ga2){
- full_join(ga1, ga2, by="gene") %>%
- mutate(
- beta_age = case_when(
- is.finite(beta_age1) & is.finite(beta_age2) & is.finite(se_age1) & is.finite(se_age2) ~ {
- w1 <- 1/(se_age1^2); w2 <- 1/(se_age2^2); (beta_age1*w1 + beta_age2*w2)/(w1+w2)
- },
- is.finite(beta_age1) ~ beta_age1,
- is.finite(beta_age2) ~ beta_age2,
- TRUE ~ NA_real_
- ),
- p_age = {
- pvec <- c(psafe(p_age1), psafe(p_age2)); pvec <- pvec[is.finite(pvec)]
- if (length(pvec)==0) NA_real_ else fisher_combine_p(pvec)
- }
- ) %>% select(gene, beta_age, p_age)
- }
- age_comb <- combine_age_genes(ga1, ga2)
- # Build gene table
- gene_tbl <- tibble(gene=genes_cons) %>%
- left_join(age_comb, by="gene") %>%
- left_join(gad %>% select(gene, beta_ad, p_ad), by="gene")
- # FDR (p.adjust keeps NA if p is NA)
- gene_tbl$p_age <- as.numeric(gene_tbl$p_age)
- gene_tbl$p_ad <- as.numeric(gene_tbl$p_ad)
- gene_tbl$FDR_age <- p.adjust(gene_tbl$p_age, "BH")
- gene_tbl$FDR_ad <- p.adjust(gene_tbl$p_ad, "BH")
- # Attach module + kME from healthy matrices
- all_kME <- function(E, module_df) {
- split(module_df$gene, module_df$module) %>%
- imap_dfr(function(gset, m){
- g <- intersect(gset, rownames(E))
- if (length(g) < 3 || ncol(E) < 2) return(tibble(gene=character(), module=m, kME=numeric()))
- datExpr <- t(E[g, , drop=FALSE]); ME <- WGCNA::moduleEigengenes(datExpr, rep(1, ncol(datExpr)))$eigengenes[,1]
- k <- suppressWarnings(cor(datExpr, ME, use="pairwise.complete.obs"))
- tibble(gene=colnames(datExpr), module=m, kME=as.numeric(k))
- })
- }
- kME_A <- all_kME(EA, module_df)
- kME_C <- all_kME(EC, module_df)
- kME_tbl <- full_join(kME_A %>% rename(kME_A=kME), kME_C %>% rename(kME_C=kME), by=c("gene","module")) %>%
- mutate(kME_mean = rowMeans(cbind(kME_A, kME_C), na.rm=TRUE))
- gene_tbl <- gene_tbl %>%
- left_join(module_df %>% select(gene, module), by="gene") %>%
- left_join(kME_tbl %>% select(gene, kME_A, kME_C, kME_mean), by="gene")
- # ------------------ AP gene metrics (normalized) -----------------------------
- p_or_one <- function(p) ifelse(is.na(p), 1, psafe(p))
- AP_antagonism <- sign(gene_tbl$beta_age) * -sign(gene_tbl$beta_ad)
- AP_antagonism[is.na(AP_antagonism)] <- 0
- AP_sig_sum <- (-log10(p_or_one(gene_tbl$p_age))) + (-log10(p_or_one(gene_tbl$p_ad)))
- effect_sum <- abs(gene_tbl$beta_age) + abs(gene_tbl$beta_ad)
- kme_w <- if (isTRUE(AP_SCORE_USE_KME)) pmax(gene_tbl$kME_mean, 0) else 1
- AP_score_raw <- AP_antagonism * effect_sum * AP_sig_sum * kme_w
- norm_minmax01 <- function(x){
- xf <- x[is.finite(x)]
- if (!length(xf) || length(unique(xf)) == 1) return(rep(0.5, length(x)))
- rng <- range(xf)
- (x - rng[1]) / (rng[2] - rng[1])
- }
- robust_z <- function(x){
- m <- stats::median(x[is.finite(x)], na.rm=TRUE)
- s <- stats::mad(x[is.finite(x)], constant=1.4826, na.rm=TRUE)
- if (!is.finite(s) || s==0) return(rep(0, length(x)))
- (x - m) / s
- }
- percentile_0_100 <- function(x){
- r <- rank(x, na.last="keep", ties.method="average")
- 100 * (r - 1) / (sum(is.finite(x)) - 1)
- }
- AP_score_norm01 <- norm_minmax01(AP_score_raw)
- AP_score_z <- robust_z(AP_score_raw)
- AP_score_percentile <- percentile_0_100(AP_score_raw)
- # Per-gene AP Z (for module aggregation; sign-aware)
- z_from_beta_p <- function(beta, p) {
- pp <- p_or_one(p)
- zz <- sign(beta) * qnorm(1 - pp/2)
- zz[!is.finite(zz)] <- 0
- zz
- }
- Z_age <- z_from_beta_p(gene_tbl$beta_age, gene_tbl$p_age)
- Z_ad <- z_from_beta_p(-gene_tbl$beta_ad, gene_tbl$p_ad) # minus sign encodes AP (AD down = resilience)
- Z_AP_gene <- (Z_age + Z_ad) / sqrt(2) # Stouffer combine (equal weights)
- # Store gene outputs
- gene_tbl$AP_antagonism <- AP_antagonism
- gene_tbl$AP_sig_sum <- AP_sig_sum
- gene_tbl$AP_score_gene_raw <- AP_score_raw
- gene_tbl$AP_score_gene_norm01 <- AP_score_norm01
- gene_tbl$AP_score_gene_z <- AP_score_z
- gene_tbl$AP_score_gene_percentile <- AP_score_percentile
- gene_tbl$Z_age <- Z_age
- gene_tbl$Z_ad <- Z_ad
- gene_tbl$Z_AP_gene <- Z_AP_gene
- gene_tbl$AP_score_gene <- AP_score_norm01 # alias used by downstream code
- ap_class_gene <- function(b_age, b_ad) {
- aa <- sign(b_age) * -sign(b_ad)
- ifelse(aa > 0 & sign(b_age) > 0, "AP_Resilience",
- ifelse(aa > 0 & sign(b_age) < 0, "AP_Vulnerability", "Other"))
- }
- gene_tbl$AP_class_gene <- ap_class_gene(gene_tbl$beta_age, gene_tbl$beta_ad)
- AP_genes_ranked <- gene_tbl %>%
- arrange(desc(AP_score_gene_norm01)) %>%
- select(gene, module, kME_A, kME_C, kME_mean,
- beta_age, p_age, FDR_age,
- beta_ad, p_ad, FDR_ad,
- AP_antagonism, AP_sig_sum, AP_class_gene,
- AP_score_gene_raw, AP_score_gene_norm01, AP_score_gene_z, AP_score_gene_percentile,
- Z_age, Z_ad, Z_AP_gene,
- AP_score_gene)
- readr::write_csv(AP_genes_ranked, file.path(outdir, "wgcna", "AP_genes_ranked.csv"))
- # ------------------ Gene-aggregated AP per module ----------------------------
- log_msg("Aggregating AP evidence across genes within modules (Stouffer Z)...")
- w_gene <- if (isTRUE(AP_MODULE_USE_KME_WEIGHTS)) pmax(gene_tbl$kME_mean, 0) else rep(1, nrow(gene_tbl))
- w_gene[!is.finite(w_gene)] <- 0
- agg_stouffer <- function(z, w){
- ok <- is.finite(z) & is.finite(w) & w > 0
- if (!any(ok)) return(NA_real_)
- sum(w[ok] * z[ok]) / sqrt(sum((w[ok])^2))
- }
- AP_modules_geneAgg <- gene_tbl %>%
- group_by(module) %>%
- summarise(
- n_genes = n(),
- n_antagonism = sum(AP_antagonism > 0, na.rm=TRUE),
- frac_antagonism= n_antagonism / n_genes,
- mean_AP_norm01 = mean(AP_score_gene_norm01, na.rm=TRUE),
- top10_AP_norm01= {
- k <- ceiling(0.10 * n_genes)
- if (k < 1) k <- 1
- mean(head(sort(AP_score_gene_norm01, decreasing=TRUE), k), na.rm=TRUE)
- },
- Z_from_genes = agg_stouffer(Z_AP_gene, w_gene[match(cur_data_all()$gene, gene_tbl$gene)]),
- p_from_genes = 2*pnorm(-abs(Z_from_genes))
- ) %>%
- ungroup() %>%
- mutate(FDR_from_genes = p.adjust(p_from_genes, "BH")) %>%
- arrange(p_from_genes)
- readr::write_csv(AP_modules_geneAgg, file.path(outdir, "wgcna", "AP_modules_geneAggregated.csv"))
- AP_modules_combined <- AP_modules %>%
- select(module, beta_age, p_age, FDR_age, beta_ad, p_ad, FDR_ad, AP_score, AP_class, module_size) %>%
- rename(EG_beta_age=beta_age, EG_p_age=p_age, EG_FDR_age=FDR_age,
- 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) %>%
- full_join(AP_modules_geneAgg, by="module")
- readr::write_csv(AP_modules_combined, file.path(outdir, "wgcna", "AP_modules_combined.csv"))
- # ---------- Ego networks for top genes ---------------------------------------
- .sim_cache <- new.env(parent=emptyenv())
- get_similarity_for_module <- function(mod, wobj) {
- key <- paste0(mod, "_", wobj$name)
- if (!is.null(.sim_cache[[key]])) return(.sim_cache[[key]])
- genes_m <- (wobj$module_df %>% filter(module==mod))$gene
- genes_m <- intersect(genes_m, rownames(wobj$expr))
- if (length(genes_m) < 5) return(NULL)
- datExpr <- t(wobj$expr[genes_m, , drop=FALSE])
- S <- NULL; ok <- TRUE
- tryCatch({ TOM <- WGCNA::TOMsimilarityFromExpr(datExpr, power=wobj$power, networkType=wobj$networkType); colnames(TOM) <- rownames(TOM) <- colnames(datExpr); S <<- TOM }, error=function(e){ ok <<- FALSE })
- if (!ok || is.null(S)) { Adj <- WGCNA::adjacency(datExpr, power=wobj$power, type=wobj$networkType); colnames(Adj) <- rownames(Adj) <- colnames(datExpr); S <- Adj }
- .sim_cache[[key]] <- S; S
- }
- export_gene_ego <- function(gene, mod, wobj, topk=15) {
- S <- get_similarity_for_module(mod, wobj)
- if (is.null(S) || !(gene %in% colnames(S))) return(invisible(NULL))
- v <- S[, gene]; v <- v[names(v) != gene]; v <- sort(v, decreasing=TRUE)
- nbrs <- head(names(v[v > 0]), min(topk, sum(v > 0)))
- if (!length(nbrs)) return(invisible(NULL))
- nodes <- unique(c(gene, nbrs))
- sub <- S[nodes, nodes, drop=FALSE]
- edges <- as.data.frame(as.table(sub), stringsAsFactors=FALSE)
- names(edges) <- c("from","to","weight")
- edges <- edges %>% filter(from < to, weight > 0)
- base <- file.path(outdir, "wgcna", "networks", paste0(wobj$name, "_", mod, "_ego_", make.names(gene)))
- write_csv(edges, paste0(base, "_edges.csv"))
- readr::write_csv(tibble(gene=nodes), paste0(base, "_nodes.csv"))
- if (ok_igraph && ok_ggraph && nrow(edges) > 0) {
- g <- igraph::graph_from_data_frame(edges, directed=FALSE, vertices=tibble(name=nodes))
- p <- ggraph::ggraph(g, layout="fr") + ggraph::geom_edge_link(alpha=0.3) +
- ggraph::geom_node_point(size=3, alpha=0.9) +
- ggraph::geom_node_text(aes(label=name), repel=TRUE, size=3) +
- ggplot2::labs(title=paste0("Ego network: ", gene, " (", mod, ")")) +
- ggplot2::theme_void(base_size=12)
- safe_ggsave(paste0(base, "_plot"), p, w=6.5, h=5.5, dpi=PNG_DPI)
- }
- }
- topR <- AP_genes_ranked %>% filter(AP_class_gene=="AP_Resilience", module!="ME00") %>% head(200)
- topV <- AP_genes_ranked %>% filter(AP_class_gene=="AP_Vulnerability", module!="ME00") %>% head(200)
- if (nrow(topR)==0) topR <- AP_genes_ranked %>% filter(module!="ME00") %>% arrange(desc(AP_sig_sum)) %>% head(200)
- if (nrow(topV)==0) topV <- AP_genes_ranked %>% filter(module!="ME00") %>% arrange(desc(AP_sig_sum)) %>% head(200)
- topR_pick <- topR %>% arrange(desc(AP_score_gene_norm01)) %>% head(TOP_EGO_PER_CLASS)
- topV_pick <- topV %>% arrange(desc(AP_score_gene_norm01)) %>% head(TOP_EGO_PER_CLASS)
- if (nrow(topR_pick)+nrow(topV_pick) == 0) {
- log_msg("No top AP genes to export ego networks for.")
- } else {
- wobj_export <- list(name="ConsensusOn_GSE48350", module_df=module_df, expr=EC, power=cons_power, networkType="signed")
- for (row in seq_len(nrow(topR_pick))) export_gene_ego(topR_pick$gene[row], topR_pick$module[row], wobj_export)
- for (row in seq_len(nrow(topV_pick))) export_gene_ego(topV_pick$gene[row], topV_pick$module[row], wobj_export)
- log_msg("Exported ego networks for top AP genes (per class).")
- }
- # ---- Save combined objects for reproducibility ----
- saveRDS(list(
- modules = module_df,
- AP_modules = AP_modules,
- AP_modules_geneAgg = AP_modules_geneAgg,
- AP_modules_combined = AP_modules_combined,
- AP_genes = AP_genes_ranked,
- hubs_age = age_hubs,
- hubs_ctrl = ctrl_hubs,
- power = cons_power,
- colors = cons_colors,
- genes_cons = genes_cons,
- AP_SCORE_USE_KME = AP_SCORE_USE_KME,
- AP_MODULE_USE_KME_WEIGHTS = AP_MODULE_USE_KME_WEIGHTS
- ), file = file.path(outdir, "wgcna", "AP_wgcna_objects.rds"))
- # ------------------ Quadrant plot (eigengene view) ---------------------------
- suppressPackageStartupMessages({ library(ggrepel); library(scales); library(readr); library(dplyr); library(ggplot2) })
- # Load the combined module table produced above
- mods <- readr::read_csv(file.path(outdir, "wgcna", "AP_modules_combined.csv"), show_col_types = FALSE)
- # If EG_AP_class already exists, use it; otherwise infer from EG betas
- infer_class <- function(b_age, b_ad) {
- if (is.finite(b_age) && is.finite(b_ad)) {
- if (b_age > 0 && b_ad < 0) "AP_Resilience"
- else if (b_age < 0 && b_ad > 0) "AP_Vulnerability"
- else "Other"
- } else "Other"
- }
- AP_COLORS <- c("AP_Resilience"="#009E73", "AP_Vulnerability"="#D55E00", "Other"="grey70")
- AP_modules_plot <- mods %>%
- mutate(
- AP_class = if (!is.null(EG_AP_class)) EG_AP_class else mapply(infer_class, EG_beta_age, EG_beta_ad),
- x = EG_beta_age,
- y = -EG_beta_ad,
- size_raw = pmax(0,
- -log10(pmax(EG_p_age, .Machine$double.xmin)) +
- -log10(pmax(EG_p_ad, .Machine$double.xmin))
- ),
- size_raw = ifelse(is.finite(size_raw), size_raw, 0),
- size_s = scales::rescale(
- pmin(size_raw, stats::quantile(size_raw[size_raw>0], 0.99, na.rm=TRUE)),
- to = c(2.5, 9),
- from = range(size_raw[size_raw>0], na.rm=TRUE)
- )
- )
- plt_quad <- ggplot(AP_modules_plot, aes(x = x, y = y)) +
- geom_hline(yintercept = 0, linetype = 2, linewidth = 0.3) +
- geom_vline(xintercept = 0, linetype = 2, linewidth = 0.3) +
- geom_point(aes(color = AP_class, size = size_s), alpha = 0.9) +
- ggrepel::geom_text_repel(aes(label = module),
- min.segment.length = 0, seed = 42,
- box.padding = 0.25, point.padding = 0.2,
- size = 3.2, color = "grey20", max.overlaps = Inf) +
- scale_color_manual(values = AP_COLORS, name = "AP Class", drop = FALSE) +
- scale_size_identity(guide = "legend", name = "-log10(p_age)+-log10(p_ad)") +
- labs(
- x = "Module effect (Healthy Aging, β_age; eigengene)",
- y = "Module effect in AD (−β_ad; eigengene)",
- title = "AP Module Quadrant Plot (Aging vs AD)"
- ) +
- coord_equal(expand = TRUE) +
- theme_minimal(base_size = 12) +
- theme(legend.position = "right")
- dir.create(file.path(outdir, "wgcna"), showWarnings = FALSE, recursive = TRUE)
- safe_ggsave(file.path(outdir, "wgcna", "fig_modules_quadrant_AP_modules_from_EG"), plt_quad, w = 7.5, h = 6.5, dpi = PNG_DPI)
- # ==================== High-AP modules: plots + gene composition ==============
- suppressPackageStartupMessages({ library(dplyr); library(readr); library(ggplot2); library(ggrepel); library(scales); })
- mods <- read_csv(file.path(outdir, "wgcna", "AP_modules_combined.csv"), show_col_types = FALSE)
- genes <- read_csv(file.path(outdir, "wgcna", "AP_genes_ranked.csv"), show_col_types = FALSE)
- # --- Selection knobs (override via env) --------------------------------------
- AP_HIGHSCORE_MIN <- as.numeric(Sys.getenv("AP_HIGHSCORE_MIN", unset = NA)) # e.g. 4
- AP_TOP_N <- as.integer(Sys.getenv("AP_TOP_N", unset = 6)) # fallback if none pass threshold
- # Helper: pick high-AP modules by eigengene-level score (antagonism-weighted)
- pick_high_ap <- function(df, min_score = NA, top_n = 6){
- d <- df %>% mutate(EG_AP_abs = abs(EG_AP_score))
- if (is.finite(min_score)) {
- keep <- d %>% filter(EG_AP_abs >= min_score)
- if (nrow(keep) > 0) return(keep)
- }
- d %>% slice_max(order_by = EG_AP_abs, n = top_n, with_ties = FALSE)
- }
- mods_sel <- pick_high_ap(mods, AP_HIGHSCORE_MIN, AP_TOP_N)
- if (nrow(mods_sel) == 0) {
- warning("No modules selected for plotting; check thresholds.")
- } else {
- # -------------- Plot 1: Quadrant for selected modules (eigengene stats) ---
- infer_class <- function(b_age, b_ad) {
- if (is.finite(b_age) && is.finite(b_ad)) {
- if (b_age > 0 && b_ad < 0) "AP_Resilience"
- else if (b_age < 0 && b_ad > 0) "AP_Vulnerability"
- else "Other"
- } else "Other"
- }
- AP_COLORS <- c("AP_Resilience" = "#009E73",
- "AP_Vulnerability" = "#D55E00",
- "Other" = "grey70")
- plot_df <- mods_sel %>%
- mutate(
- AP_class = if ("EG_AP_class" %in% names(.)) EG_AP_class else mapply(infer_class, EG_beta_age, EG_beta_ad),
- x = EG_beta_age,
- y = -EG_beta_ad,
- size_raw = pmax(0,
- -log10(pmax(EG_p_age, .Machine$double.xmin)) +
- -log10(pmax(EG_p_ad, .Machine$double.xmin))
- ),
- size_raw = ifelse(is.finite(size_raw), size_raw, 0),
- size_s = scales::rescale(
- pmin(size_raw, quantile(size_raw[size_raw>0], 0.99, na.rm=TRUE)),
- to = c(2.5, 9),
- from = range(size_raw[size_raw>0], na.rm=TRUE)
- )
- )
- plt_quad_hi <- ggplot(plot_df, aes(x = x, y = y)) +
- geom_hline(yintercept = 0, linetype = 2, linewidth = 0.3) +
- geom_vline(xintercept = 0, linetype = 2, linewidth = 0.3) +
- geom_point(aes(color = AP_class, size = size_s), alpha = 0.9) +
- ggrepel::geom_text_repel(aes(label = module),
- seed = 42, box.padding = 0.25, point.padding = 0.2,
- size = 3.2, color = "grey20", min.segment.length = 0) +
- scale_color_manual(values = AP_COLORS, name = "AP Class", drop = FALSE) +
- scale_size_identity(guide = "legend", name = "-log10(p_age)+-log10(p_ad)") +
- labs(
- title = "High-AP Modules (eigengene view)",
- x = "β_age (Healthy aging, eigengene)",
- y = "−β_ad (AD vs Control, eigengene)",
- subtitle = sprintf("Selected by |AP score|%s",
- if (is.finite(AP_HIGHSCORE_MIN)) paste0(" ≥ ", AP_HIGHSCORE_MIN) else
- paste0(" — top ", AP_TOP_N))
- ) +
- coord_equal(expand = TRUE) +
- theme_minimal(base_size = 12) +
- theme(legend.position = "right")
- safe_ggsave(file.path(outdir, "wgcna", "fig_quadrant_highAP_modules"), plt_quad_hi, w = 7.5, h = 6.5, dpi = PNG_DPI)
- # --------- Composition: #genes per module by AP_class_gene (gene-level) ----
- comp_long <- genes %>%
- semi_join(mods_sel %>% select(module), by = "module") %>%
- mutate(AP_class_gene = factor(AP_class_gene, levels = c("AP_Resilience","AP_Vulnerability","Other"))) %>%
- count(module, AP_class_gene, name = "n_genes") %>%
- group_by(module) %>%
- mutate(total_genes = sum(n_genes), frac = n_genes / total_genes) %>%
- ungroup()
- # Save a tidy composition table (answers your “are you determining the numbers?” → yes)
- write_csv(comp_long, file.path(outdir, "wgcna", "highAP_modules_gene_composition.csv"))
- # -------------- Plot 2: Stacked bars by gene AP class (counts & fraction) --
- plt_counts <- ggplot(comp_long, aes(x = module, y = n_genes, fill = AP_class_gene)) +
- geom_col(width = 0.8, color = "white") +
- scale_fill_manual(values = c("AP_Resilience"="#009E73","AP_Vulnerability"="#D55E00","Other"="grey70"),
- name = "Gene AP class") +
- labs(title = "Gene composition of high-AP modules",
- subtitle = "Counts by AP_Resilience / AP_Vulnerability / Other",
- x = "Module", y = "# genes") +
- theme_minimal(base_size = 12) +
- theme(legend.position = "right")
- safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_modules_gene_counts"), plt_counts, w = 8, h = 5, dpi = PNG_DPI)
- plt_frac <- ggplot(comp_long, aes(x = module, y = frac, fill = AP_class_gene)) +
- geom_col(width = 0.8, color = "white") +
- scale_y_continuous(labels = percent_format()) +
- scale_fill_manual(values = c("AP_Resilience"="#009E73","AP_Vulnerability"="#D55E00","Other"="grey70"),
- name = "Gene AP class") +
- labs(title = "Gene composition of high-AP modules",
- subtitle = "Fraction within each module",
- x = "Module", y = "Fraction") +
- theme_minimal(base_size = 12) +
- theme(legend.position = "right")
- safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_modules_gene_fractions"), plt_frac, w = 8, h = 5, dpi = PNG_DPI)
- # ================== SINGLE FIGURE: Lollipop (top) + Donuts (bottom) ==================
- suppressPackageStartupMessages({
- library(dplyr); library(readr); library(ggplot2); library(scales)
- })
- has_patchwork <- requireNamespace("patchwork", quietly = TRUE)
- mods <- readr::read_csv(file.path(outdir, "wgcna", "AP_modules_combined.csv"), show_col_types = FALSE)
- genes <- readr::read_csv(file.path(outdir, "wgcna", "AP_genes_ranked.csv"), show_col_types = FALSE)
- # -------- selection knobs (change via env if you like) --------
- AP_HIGHSCORE_MIN <- as.numeric(Sys.getenv("AP_HIGHSCORE_MIN", unset = NA)) # e.g., 4
- AP_TOP_N <- as.integer(Sys.getenv("AP_TOP_N", unset = 6)) # top-N if no cutoff
- pick_high_ap <- function(df, min_score = NA, top_n = 6){
- d <- df %>% mutate(EG_AP_abs = abs(EG_AP_score))
- if (is.finite(min_score)) {
- keep <- d %>% filter(EG_AP_abs >= min_score)
- if (nrow(keep) > 0) return(keep)
- }
- d %>% slice_max(order_by = EG_AP_abs, n = top_n, with_ties = FALSE)
- }
- mods_sel <- pick_high_ap(mods, AP_HIGHSCORE_MIN, AP_TOP_N) %>%
- arrange(desc(abs(EG_AP_score))) %>%
- mutate(module = factor(module, levels = unique(module)))
- if (nrow(mods_sel) == 0) {
- warning("No modules selected — lower AP_HIGHSCORE_MIN or increase AP_TOP_N.");
- } else {
- AP_COLORS <- c("AP_Resilience"="#009E73","AP_Vulnerability"="#D55E00","Other"="grey70")
- # -------------------- TOP: Lollipop rank by |AP score| ---------------------
- p_top <- ggplot(mods_sel, aes(y = module, x = abs(EG_AP_score))) +
- geom_segment(aes(yend = module, x = 0, xend = abs(EG_AP_score)), linewidth = 1, alpha = 0.45) +
- geom_point(aes(color = EG_AP_class,
- size = -log10(pmax(EG_p_age, .Machine$double.xmin)) +
- -log10(pmax(EG_p_ad, .Machine$double.xmin))),
- alpha = 0.95) +
- scale_color_manual(values = AP_COLORS, drop = FALSE, name = "AP class") +
- scale_size_continuous(range = c(3, 9), name = expression(-log[10](p[age])+-log[10](p[AD]))) +
- labs(title = "High-AP modules", subtitle = "Ranked by |AP score| (eigengene)",
- x = "|AP score|", y = NULL) +
- theme_minimal(base_size = 12) +
- theme(legend.position = "right", panel.grid.major.y = element_blank())
- # --------------- BOTTOM: Donut row of gene-class composition ---------------
- comp <- genes %>%
- semi_join(mods_sel %>% select(module), by = "module") %>%
- mutate(AP_class_gene = factor(AP_class_gene, levels = c("AP_Resilience","AP_Vulnerability","Other")),
- module = factor(module, levels = levels(mods_sel$module))) %>%
- count(module, AP_class_gene, name = "n") %>%
- group_by(module) %>% mutate(frac = n/sum(n)) %>% ungroup()
- p_bottom <- ggplot(comp, aes(x = 2, y = frac, fill = AP_class_gene)) +
- geom_col(width = 0.6, color = "white") +
- coord_polar(theta = "y") +
- facet_wrap(~ module, nrow = 1) +
- scale_fill_manual(values = AP_COLORS, name = "Gene AP class") +
- xlim(0.5, 2.6) +
- labs(title = NULL, subtitle = NULL) +
- theme_void(base_size = 12) +
- theme(legend.position = "right",
- strip.text = element_text(face = "bold"))
- # ---------------------- Stack (donut at the bottom) ------------------------
- dir.create(file.path(outdir, "wgcna"), recursive = TRUE, showWarnings = FALSE)
- if (has_patchwork) {
- fig <- p_top / p_bottom + patchwork::plot_layout(heights = c(2, 1), guides = "collect")
- safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_lollipop_plus_donuts"), fig, w = 11, h = 7.5, dpi = PNG_DPI)
- } else {
- # Save separately if patchwork isn’t installed
- safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_lollipop"), p_top, w = 11, h = 5.0, dpi = PNG_DPI)
- safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_donuts"), p_bottom, w = 11, h = 3.0, dpi = PNG_DPI)
- }
- # Also write the composition table (counts + fractions) for the figure
- readr::write_csv(comp, file.path(outdir, "wgcna", "highAP_modules_gene_composition_for_donuts.csv"))
- }
- # ---------------- Top genes per module (10 highest AP_score_gene) ----------
- TOP_GENES_PER_MODULE <- as.integer(Sys.getenv("TOP_GENES_PER_MODULE", unset = "10"))
- top_genes <- genes %>%
- semi_join(mods_sel %>% dplyr::select(module), by = "module") %>%
- dplyr::group_by(module) %>%
- dplyr::slice_max(order_by = AP_score_gene, n = TOP_GENES_PER_MODULE, with_ties = FALSE) %>%
- dplyr::ungroup() %>%
- # build a per-module ordering key so each facet sorts independently
- dplyr::group_by(module) %>%
- dplyr::arrange(AP_score_gene, .by_group = TRUE) %>%
- dplyr::mutate(key = paste(module, gene, sep = "::")) %>%
- dplyr::ungroup()
- # lock factor levels using the per-module order
- key_levels <- top_genes %>%
- dplyr::group_by(module) %>%
- dplyr::arrange(AP_score_gene, .by_group = TRUE) %>%
- dplyr::pull(key)
- top_genes$key <- factor(top_genes$key, levels = unique(key_levels))
- p_topgenes <- ggplot(top_genes,
- aes(x = AP_score_gene, y = key, color = AP_class_gene)) +
- geom_segment(aes(x = 0, xend = AP_score_gene, y = key, yend = key),
- alpha = 0.45, linewidth = 0.9) +
- geom_point(size = 2.6, alpha = 0.95) +
- scale_color_manual(values = AP_COLORS,
- name = "Gene AP class",
- breaks = c("AP_Resilience","AP_Vulnerability","Other"),
- drop = FALSE) +
- scale_y_discrete(labels = function(x) sub(".*::", "", x)) +
- facet_wrap(~ module, scales = "free_y") +
- labs(
- title = sprintf("Top %d genes by AP score (per module)", TOP_GENES_PER_MODULE),
- x = "AP_score_gene (normalized 0–1)", y = NULL
- ) +
- coord_cartesian(clip = "off") +
- theme_minimal(base_size = 12) +
- theme(
- legend.position = "right",
- strip.text = element_text(face = "bold"),
- panel.grid.major.y = element_blank()
- )
- safe_ggsave(file.path(outdir, "wgcna", "fig_highAP_top_genes_per_module"),
- p_topgenes, w = 11, h = 6.5, dpi = PNG_DPI)
- # export the exact list that appears in the plot
- readr::write_csv(top_genes %>%
- dplyr::transmute(module, gene,
- AP_score_gene,
- AP_class_gene,
- beta_age, p_age, FDR_age,
- beta_ad, p_ad, FDR_ad,
- kME_mean),
- file.path(outdir, "wgcna", "top_genes_per_module_for_figure.csv"))
- # Also print a quick text summary to the log
- log_msg("High-AP modules selected: %s", paste(sort(unique(mods_sel$module)), collapse=", "))
- log_msg("Composition table written to: %s",
- file.path(outdir, "wgcna", "highAP_modules_gene_composition.csv"))
- # ======================= ALL MODULES: where are the strong genes? =======================
- suppressPackageStartupMessages({ library(dplyr); library(readr); library(ggplot2); library(ggrepel); library(scales) })
- # knobs (override via env)
- AP_GENE_MIN_NORM <- as.numeric(Sys.getenv("AP_GENE_MIN_NORM", unset = "0.70")) # threshold on AP_score_gene_norm01
- TOP_GENES_PER_MOD <- as.integer(Sys.getenv("TOP_GENES_PER_MOD", unset = "3")) # labels per module
- # Ensure factor order: rank modules globally by |EG_AP_score| when available
- mods_ranked <- mods %>%
- mutate(EG_AP_abs = abs(EG_AP_score)) %>%
- arrange(desc(EG_AP_abs)) %>%
- mutate(module = factor(module, levels = unique(module)))
- genes2 <- genes %>%
- mutate(AP_class_gene = factor(AP_class_gene, levels = c("AP_Resilience","AP_Vulnerability","Other"))) %>%
- left_join(mods_ranked %>% select(module, EG_AP_abs), by = "module") %>%
- mutate(module = factor(module, levels = levels(mods_ranked$module)))
- # ---------- (1) Heatmap: counts of high-AP genes per module × gene AP class ----------
- hi_counts <- genes2 %>%
- filter(is.finite(AP_score_gene_norm01)) %>%
- mutate(is_high = AP_score_gene_norm01 >= AP_GENE_MIN_NORM) %>%
- group_by(module, AP_class_gene) %>%
- summarise(n_high = sum(is_high, na.rm = TRUE), .groups = "drop")
- # Fill missing combos with zero for a clean heatmap
- all_mods <- levels(genes2$module)
- all_class <- levels(genes2$AP_class_gene)
- hi_counts <- tidyr::complete(hi_counts, module = all_mods, AP_class_gene = all_class, fill = list(n_high = 0))
- p_heat <- ggplot(hi_counts, aes(x = AP_class_gene, y = module, fill = n_high)) +
- geom_tile(color = "white", linewidth = 0.3) +
- scale_fill_gradient(low = "grey95", high = "black", name = "# high-AP genes") +
- scale_x_discrete(position = "top") +
- labs(
- title = sprintf("High-AP genes across ALL modules (threshold: ≥ %.2f)", AP_GENE_MIN_NORM),
- x = "Gene AP class", y = "Module (ranked by |EG AP|)"
- ) +
- theme_minimal(base_size = 12) +
- theme(panel.grid = element_blank(), axis.text.x = element_text(face = "bold"))
- 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)
- # ---------- (2) Small multiples: top K genes per module (labels) ---------------
- topK_per_module <- genes2 %>%
- group_by(module) %>%
- arrange(desc(AP_score_gene_norm01), .by_group = TRUE) %>%
- slice_head(n = TOP_GENES_PER_MOD) %>%
- ungroup() %>%
- mutate(label = paste0(gene, " (", scales::number(AP_score_gene_norm01, accuracy = 0.01), ")"))
- # If some modules are tiny, ensure at least one row
- topK_per_module <- topK_per_module %>% filter(!is.na(module))
- p_smallmult <- ggplot(topK_per_module,
- aes(x = AP_score_gene_norm01, y = reorder(label, AP_score_gene_norm01))) +
- geom_col(aes(fill = AP_class_gene), width = 0.8, color = "white") +
- geom_vline(xintercept = AP_GENE_MIN_NORM, linetype = 2, linewidth = 0.3) +
- facet_wrap(~ module, ncol = 3, scales = "free_y") +
- scale_fill_manual(values = AP_COLORS, name = "Gene AP class") +
- scale_x_continuous(limits = c(0, 1), labels = label_number(accuracy = 0.1)) +
- labs(
- title = sprintf("Top %d genes per module by AP score (normalized 0–1)", TOP_GENES_PER_MOD),
- subtitle = "ALL modules; dotted line = high-AP threshold",
- x = "AP_score_gene (norm.)", y = NULL
- ) +
- theme_minimal(base_size = 12) +
- theme(legend.position = "right",
- strip.text = element_text(face = "bold"),
- panel.grid.major.y = element_blank())
- safe_ggsave(file.path(outdir, "wgcna", "fig_allModules_topK_genes"), p_smallmult, w = 11, h = 10, dpi = PNG_DPI)
- # Export tidy tables used in these figures
- readr::write_csv(hi_counts, file.path(outdir, "wgcna", "allModules_highAP_geneClass_counts.csv"))
- readr::write_csv(topK_per_module, file.path(outdir, "wgcna", "allModules_topK_genes.csv"))
- # Log a quick heads-up
- log_msg("All-modules figures saved: high-AP heatmap + top-%d genes per module. Threshold=%.2f",
- TOP_GENES_PER_MOD, AP_GENE_MIN_NORM)
- }
- log_msg("Done. Wrote:\n - %s\n - %s\n - %s\n - %s\n - %s\n - %s",
- file.path(outdir, "AP_modules.csv"),
- file.path(outdir, "wgcna", "AP_modules_geneAggregated.csv"),
- file.path(outdir, "wgcna", "AP_modules_combined.csv"),
- file.path(outdir, "wgcna"),
- file.path(outdir, "wgcna", "networks"),
- file.path(outdir, "wgcna", "AP_genes_ranked.csv"))
10_modules_AP.R at commit 377f6ae, no license · at the source
Overview
- Department of Bioinformatics, Julius-Maximilians-Universität Würzburg, Würzburg, Germany
- Department of Bioengineering, Marmara University, Istanbul, Turkey
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/
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
377f6aed20f1984d011e84b99e5ed5cd2db0c811, 30 March 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
15 files
- 00_config.R, R, 77 lines
- 01_prepare_universe.R, R, 186 lines, 1 match
- 02_consensus_meta.R, R, 382 lines, 2 matches
- 03_pathway_antagonism.R, R, 64 lines, 1 match
- 04_ap_candidates.R, R, 864 lines, 2 matches
- 05_tf_activity.R, R, 345 lines, 3 matches
- 06_drug_reversal_and_gwa
s.R , R, 38 lines - 07_optional_gsva_deconv.
R , R, 247 lines, 2 matches - 08_concordance_and_robus
tness.R , R, 332 lines - 09_go_kegg_enrichment.R, R, 196 lines, 1 match
- 10_modules_AP.R, R, 1,242 lines, 4 matches
- Run_all.R, R, 19 lines
- utils.R, R, 124 lines, 1 match
- withDevelopment_section.
R , R, 1,582 lines, 1 match - README.md, Text, 84 lines
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
- bioconductor.org/
packages/ , at bioconductor.org; found in the referencesmsigdb - geo:GSE113957, at NCBI GEO; found in the text, “Introduction”
Data Availability
https://
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://
BibTeX
@article{salihoglu2026in
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/
url = {https://
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/
VL - 35
IS - 1
SP - 0134
SN - 2001-0370
PB - AAAS Science Partner Journal Program
DO - 10.34133/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.34133/
"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":
"volume": "35",
"issue": "1",
"page": "0134",
"DOI": "10.34133/
"PMID": "42267139",
"PMCID": "PMC13243799",
"ISSN": "2001-0370",
"publisher": "AAAS Science Partner Journal Program",
"URL": "https://
"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.1038/s41593-026-02367-0 [code]
- A reproducible three-dimensional model of human brain tissue to investigate physiological and disease-associated microglia phenotypes.Journal: Nature neuroscienceIn common: WGCNA, SingleCellExperiment, igraph, 5 other tools, Alzheimer's / dementia, cellular / molecular, 3 references
- [2] doi:10.1038/s41380-026-03629-w [code]
- Maternal fasting during early gestation induces epigenetic alterations and schizophrenia-related phenotypes.Journal: Molecular psychiatryIn common: WGCNA, igraph, clusterProfiler, 4 other tools, genetics / omics, cellular / molecular, 4 references
- [3] doi:10.1016/j.xcrm.2026.102766 [code]
- A longitudinal single-cell and spatial multiomic atlas of pediatric high-grade glioma.Journal: Cell reports. MedicineIn common: WGCNA, SingleCellExperiment, igraph, 5 other tools, genetics / omics, cellular / molecular, 1 reference
- [4] 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 journalIn common: clusterProfiler, pheatmap, ggplot2, 1 other tool, Alzheimer's / dementia, genetics / omics, cellular / molecular, 6 references
- [5] doi:10.1038/s41593-026-02384-z [code]
- cGAS-mediated type I IFN signaling contributes to disease progression in drug-refractory epilepsy.Journal: Nature neuroscienceIn common: WGCNA, SingleCellExperiment, igraph, 5 other tools, cellular / molecular, 1 reference
- [6] doi:10.1038/s44318-026-00806-z [code]
- Interspecific diversity in the neuronal composition of the mammalian cortex arises from heterochrony in neurogenesis.Journal: The EMBO journalIn common: WGCNA, SingleCellExperiment, igraph, 5 other tools, 1 reference
- [7] 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 AssociationIn common: Alzheimer's / dementia, genetics / omics, cellular / molecular, 10 references
- [8] doi:10.1038/s41467-026-72598-z [code]
- Functional impact of genetic background on variable expressivity in neurodevelopmental disorders.Journal: Nature communicationsIn common: WGCNA, clusterProfiler, pheatmap, 3 other tools, 4 references
- [9] doi:10.1038/s41398-026-04200-5 [code]
- Postmortem brain single-nucleus and bulk gene expression analyses identify shared and distinct abnormalities in bipolar disorder and major depressive disorder.Journal: Translational psychiatryIn common: WGCNA, SingleCellExperiment, igraph, 4 other tools, genetics / omics, cellular / molecular, 1 reference
- [10] doi:10.1038/s41467-026-73305-8 [code]
- Comparative analysis of the cellular landscape in mammalian striatum.Journal: Nature communicationsIn common: WGCNA, SingleCellExperiment, clusterProfiler, 4 other tools, genetics / omics, cellular / molecular, 1 reference
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.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 14 scripts, and 18 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:424b3fea8c1d38ef…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
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.
