library(readr)
library(tidyverse)
library(dplyr)
library(data.table)
library(jsonlite)
library(org.Hs.eg.db)
library(AnnotationDbi)
library(writexl)
di<-"L:/MO/" # set directory path
setwd(di)  # set current directory 

all_studies <- fromJSON("https://www.cbioportal.org/api/studies") # JSON (JavaScript Object Notation) is a lightweight, human-readable, programming-language-independent data format
COAD_studies <- all_studies |>
  filter(cancerTypeId %in% c("coad")) # this is exact match for partial match use something like filter(grepl("coad|read|crc", cancerTypeId))

studies <- c("coad_tcga_gdc")
options(timeout = 1800)
for (study in studies) {
  url <- paste0("https://datahub.assets.cbioportal.org/",study,".tar.gz")
  archive <- paste0(study, ".tar.gz")
  download.file(url,destfile = archive,mode = "wb",method = "libcurl")
  untar(archive)
}

COAD_TPM <- read_tsv(paste0(di,"coad_tcga_gdc/data_mrna_seq_tpm.txt"))

# keep only unique Gene IDs with highest mean expression across all columns
COAD_TPM_unique <- COAD_TPM |>
  mutate(mean_TPM = rowMeans(across(starts_with("TCGA-")),na.rm = TRUE)) |>
  group_by(Entrez_Gene_Id) |>
  slice_max(order_by = mean_TPM, n = 1, with_ties = FALSE) |>
  ungroup() |>
  dplyr::select(-mean_TPM)
COAD_TPM_MAT <- column_to_rownames(COAD_TPM_unique, var = "Entrez_Gene_Id")

# keep only primary tumor samples and transform to TCGA Patient ID (barcode)
COAD_TPM_MAT_PRIM <- COAD_TPM_MAT |>
  dplyr::select(matches("^.{12}-01")) |>
  (\(x) x[, !duplicated(substr(colnames(x), 1, 12))])() |>
  rename_with(~ substr(.x, 1, 12))

# keep only primary tumor samples and transform to TCGA Patient ID (barcode)
gene_symbols <- mapIds(
  org.Hs.eg.db,
  keys = rownames(COAD_TPM_MAT_PRIM),
  column = "SYMBOL",
  keytype = "ENTREZID",
  multiVals = "first"
)

# tidyverse (tibble, dplyr) unique gene symbols as row.names
COAD_TPM_SYMBOL <- COAD_TPM_MAT_PRIM |>
  rownames_to_column("ENTREZID") |>
  mutate(SYMBOL = unname(gene_symbols[ENTREZID])) |>
  filter(!is.na(SYMBOL), !duplicated(SYMBOL)) |>
  dplyr::select(-ENTREZID) |>
  column_to_rownames("SYMBOL")

# base R unique gene symbols as row.names
keep <- !is.na(gene_symbols) & !duplicated(gene_symbols)
COAD_TPM_SYMBOL2 <- COAD_TPM_MAT_PRIM[keep, ]
rownames(COAD_TPM_SYMBOL2) <- gene_symbols[keep]

# transform TPM to log2 TPM+1
COAD_LOG2TPM1 <- COAD_TPM_SYMBOL |>
  mutate(across(everything(), \(x) log2(x + 1)))

# Clinical information
COAD_CLIN <- read_tsv(paste0(di,"coad_tcga_gdc/data_clinical_patient.txt"))

# Match TCGA PATID (BARCODE) of clinical information with LOG2TPM1 of RNAseq from primary tumor
common_ids <- intersect(colnames(COAD_TPM_SYMBOL),COAD_CLIN$"#Patient Identifier")
COAD_TPM_MATCHED <- COAD_TPM_SYMBOL |>
  dplyr::select(all_of(common_ids))
COAD_CLIN_MATCHED <- COAD_CLIN |>
  dplyr::slice(match(common_ids, `#Patient Identifier`))
# verify if identical
identical(
  colnames(COAD_TPM_MATCHED),
  COAD_CLIN_MATCHED$`#Patient Identifier`
)
write_tsv(COAD_CLIN_MATCHED, "COAD_CLIN_MATCHED.tsv")
COAD_CLIN_DF <- COAD_CLIN_MATCHED |>
  tibble::column_to_rownames("#Patient Identifier")

