# SolvesEverything RNA Atlas — save KEGG pathways as a .gmt file on your own computer.
# Downloads the current KEGG pathway gene lists from the KEGG REST API (KEGGREST) and maps Entrez IDs to
# gene symbols / Ensembl IDs with org.Hs.eg.db, org.Mm.eg.db or org.Rn.eg.db. Load the .gmt in RNA Atlas → Pathways →
# "upload custom GMT". KEGG data © Kanehisa Laboratories: free for academic use; other uses need a licence
# (https://www.kegg.jp/kegg/legal.html). Do not redistribute the file. Cite Kanehisa et al., Nucleic Acids Res.
#
# Install once:  install.packages("BiocManager"); BiocManager::install(c("KEGGREST", "AnnotationDbi", "org.Hs.eg.db", "org.Mm.eg.db", "org.Rn.eg.db"))

organism   <- "hsa"       # "hsa" = human, "mmu" = mouse, "rno" = rat
identifier <- "SYMBOL"    # "SYMBOL", "ENSEMBL" or "ENTREZID" — use the identifiers in your results table
out_file   <- sprintf("KEGG_%s_%s_%s.gmt", organism, identifier, format(Sys.Date(), "%Y-%m-%d"))

stopifnot(organism %in% c("hsa", "mmu", "rno"), identifier %in% c("SYMBOL", "ENSEMBL", "ENTREZID"))
link   <- KEGGREST::keggLink("pathway", organism)           # gene → pathway, e.g. hsa:7157 → path:hsa04115
titles <- KEGGREST::keggList("pathway", organism)           # pathway → title
entrez <- sub("^[a-z]+:", "", names(link)); pid <- sub("^path:", "", unname(link))
keep <- grepl(paste0("^", organism, "[0-9]{5}$"), pid); entrez <- entrez[keep]; pid <- pid[keep]
if (identifier == "ENTREZID") gene <- entrez else {
  db <- c(hsa = "org.Hs.eg.db", mmu = "org.Mm.eg.db", rno = "org.Rn.eg.db")[[organism]]
  map <- suppressMessages(AnnotationDbi::mapIds(getExportedValue(db, db), keys = unique(entrez), keytype = "ENTREZID", column = identifier, multiVals = "first"))
  gene <- unname(map[entrez])
}
ok <- !is.na(gene) & nzchar(gene)
sets <- lapply(split(gene[ok], pid[ok]), function(g) sort(unique(g)))
label <- setNames(sub(" - [^-]+ \\([^)]*\\)$", "", unname(titles)), sub("^path:", "", names(titles)))
release <- tryCatch(regmatches(paste(KEGGREST::keggInfo("pathway"), collapse = "\n"), regexpr("Release [^\n]+", paste(KEGGREST::keggInfo("pathway"), collapse = "\n"))), error = function(e) "")
lines <- vapply(names(sets), function(id) paste(c(paste0(ifelse(is.na(label[id]), id, label[id]), " (", id, ")"),
                                                 paste("KEGG", id, release, "retrieved", Sys.Date()), sets[[id]]), collapse = "\t"), "")
writeLines(lines, out_file)
message(sprintf("Saved %d KEGG pathways to %s (%d of %d KEGG genes could not be mapped to %s).", length(sets), out_file, length(unique(entrez[!ok])), length(unique(entrez)), identifier))
