#########################################################################
### ### ###             Using_R_to_explore_HPA                ### ### ### 
#########################################################################
# Dr. Javier De Las Rivas (IBMCC, CSIC/USAL, Salamanca): jrivas@usal.es
#########################################################################
### HPAanalyze et al.
#########################################################################
# Query and explore HPA proteomic database
# https://www.proteinatlas.org/

getwd()
setwd("/Users/javierd19/Desktop/R_Workshop_COST2021/")


if (!requireNamespace("BiocManager", quietly = TRUE))
  install.packages("BiocManager")

BiocManager::install("BiocStyle")

BiocManager::install(c("HPAanalyze", "tibble", "dplyr", "ggplot2"))
BiocManager::install("hpar")

library(BiocStyle)
library(HPAanalyze)
library(tibble)
library(dplyr)
library(ggplot2)


# https://www.bioconductor.org/packages/release/bioc/html/HPAanalyze.html


### (Section 3.1) 
# Download and explore HPA data with hpaDownload()

# this gives you the latest everything of HPA, which is nice to keep but not really necessary
# BUT it is too big and if you do not have all the correct libraries it may give an ERROR
# downloadedData <- hpaDownload(downloadList='all')
# summary(downloadedData)


# download RNA data from HPA
downloadedDtRNA <- hpaDownload(downloadList='rna', version='v18')
# ... URL 'https://www.proteinatlas.org/download/rna_tissue_consensus.tsv.zip'
# Content type 'application/zip' length 6081979 bytes (5.8 MB)
# ... URL 'https://www.proteinatlas.org/download/rna_celline.tsv.zip'
# Content type 'application/zip' length 10651643 bytes (10.2 MB)
#
tibble::glimpse(downloadedDtRNA$rna_tissue, give.attr=FALSE)
# Rows: 1,180,464
# Columns: 4
# $ ensembl <chr> "ENSG00000000003", "ENSG00000000003", "ENSG00000000003", "ENSG00000000003", "ENSG00000000003", "ENSG00000000003", "ENSG00000000003", "ENSG0…
# $ gene    <chr> "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6",…
# $ tissue  <chr> "adipose tissue", "adrenal gland", "amygdala", "appendix", "B-cells", "basal ganglia", "bone marrow", "breast", "cerebellum", "cerebral cor…
# $ nx      <chr> "27.0", "9.8", "7.0", "4.4", "0.3", "6.6", "0.1", "33.0", "2.9", "4.9", "15.9", "17.8", "12.6", "0.2", "6.4", "9.7", "11.1", "10.4", "27.1"…
#
unique(downloadedDtRNA$rna_tissue$tissue)
length(unique(downloadedDtRNA$rna_tissue$tissue))
#
tibble::glimpse(downloadedDtRNA$rna_cell_line, give.attr=FALSE)
# Rows: 1,357,230
# Columns: 6
# $ ensembl   <chr> "ENSG00000000003", "ENSG00000000003", "ENSG00000000003", "ENSG00000000003", "ENSG00000000003", "ENSG00000000003", "ENSG00000000003", "ENS…
# $ gene      <chr> "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6", "TSPAN6…
# $ cell_line <chr> "A-431", "A549", "AF22", "AN3-CA", "ASC diff", "ASC TERT1", "BEWO", "BJ", "BJ hTERT+", "BJ hTERT+ SV40 Large T+", "BJ hTERT+ SV40 Large T…
# $ tpm       <chr> "27.8", "37.6", "108.1", "51.8", "32.3", "17.7", "42.7", "14.9", "22.3", "31.8", "77.5", "77.4", "47.4", "0.0", "68.2", "14.1", "25.0", "…
# $ ptpm      <chr> "33.9", "45.5", "134.5", "64.4", "37.4", "20.8", "53.5", "18.4", "26.5", "38.4", "94.4", "94.8", "58.9", "0.0", "83.8", "16.8", "30.9", "…
# $ nx        <chr> "7.9", "10.6", "28.7", "14.5", "12.6", "6.8", "11.6", "4.5", "7.1", "9.0", "21.1", "23.8", "13.9", "0.0", "19.1", "4.6", "6.2", "6.5", "0…
unique(downloadedDtRNA$rna_cell_line$cell_line)
length(unique(downloadedDtRNA$rna_cell_line$cell_line))



# About CELL-LINES in HPA see https://www.proteinatlas.org/humanproteome/cell/cell+line
# A549 cells = adenocarcinomic human alveolar basal epithelial cells, model for the study of LUNG CANCER.
# MCF7 cells = adherent epithelial luminal cells similar to invasive breast ductal carcinoma, ER and PR positive, model for the study of BREAST CANCER.
#
class(downloadedDtRNA$rna_cell_line)
# [1] "tbl_df"     "tbl"        "data.frame"
head(downloadedDtRNA$rna_cell_line[,c(1,2,5)])
# # A tibble: 6 x 3
#   ensembl         gene   ptpm 
#   <chr>           <chr>  <chr>
# 1 ENSG00000000003 TSPAN6 33.9 
# 2 ENSG00000000003 TSPAN6 45.5 
# 3 ENSG00000000003 TSPAN6 134.5
# 4 ENSG00000000003 TSPAN6 64.4 
# 5 ENSG00000000003 TSPAN6 37.4 
# 6 ENSG00000000003 TSPAN6 20.8 
gEtb <- downloadedDtRNA$rna_cell_line
unique(gEtb$cell_line)
#
gEtb %>% 
  filter(cell_line %in% "A549") %>% 
  select(ensembl, gene, ptpm)
#
gEtbA549 <- gEtb %>% type.convert() %>% 
                  filter(cell_line %in% "A549") %>%  
                        select(ensembl, gene, ptpm) %>% as.data.frame()
gEtbMCF7 <- gEtb %>% type.convert() %>% 
                  filter(cell_line %in% "MCF7") %>%  
                        select(ensembl, gene, ptpm) %>% as.data.frame()
#
View(gEtbA549)
head(gEtbA549)
head(gEtbMCF7)
summary(gEtbA549$ptpm)
# Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#  0.0     0.0     4.8    50.8    26.4 13974.4 
summary(gEtbMCF7$ptpm)
# Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#  0.0     0.0     3.3    50.8    22.7 14595.6 
sum(gEtbA549$ptpm)
# [1] 999225.5
sum(gEtbMCF7$ptpm)
# [1] 999240.3
plot(density((log2(gEtbA549[,3]+1))), col="blue", ylim=c(0,0.45))
lines(density((log2(gEtbMCF7[,3]+1))), col="purple")
#
boxplot(log2(gEtbA549[,3]+1),log2(gEtbMCF7[,3]+1), nocth=TRUE, col=c("blue","purple"), ylim=c() )
#
gEA549m1 <- gEtbA549[(log2(gEtbA549[,3]+1)>=1),3]
gEMCF7m1 <- gEtbMCF7[(log2(gEtbMCF7[,3]+1)>=1),3]
#
boxplot(log2(gEA549m1),log2(gEMCF7m1), nocth=TRUE, col=c("blue","purple"), ylim=c() )
#
plot(density(log2(gEA549m1)), col="blue", ylim=c(0,0.25) )
lines(density(log2(gEMCF7m1)), col="purple")


### (Section 3.2) 
# List available parameter for subsetting with hpaListParam()
str(hpaListParam(downloadedDtRNA))
# List of 2
# $ normal_tissue_rna: chr [1:61] "adipose tissue" "adrenal gland" "amygdala" "appendix" ...
# $ cell_line_rna    : chr [1:69] "A-431" "A549" "AF22" "AN3-CA" ...
sapply(downloadedDtRNA, nrow)
# rna_tissue rna_cell_line 
#    1180464       1357230 


# download HISTOLOGY data from HPA
downloadedDtHIST <- hpaDownload(downloadList='histology', version='example')
summary(downloadedDtHIST)
sapply(downloadedDtHIST, nrow)
# normal_tissue            pathology   subcellular_location 
#       1118517               393400                  12813 
str(hpaListParam(downloadedDtHIST))
# List of 4
# $ normal_tissue       : chr [1:63] "adipose tissue" "adrenal gland" "appendix" "bone marrow" ...
# $ normal_cell         : chr [1:120] "adipocytes" "glandular cells" "lymphoid tissue" "hematopoietic cells" ...
# $ cancer              : chr [1:20] "breast cancer" "carcinoid" "cervical cancer" "colorectal cancer" ...
# $ subcellular_location: chr [1:34] "Cell Junctions" "Cytosol" "Nucleoli fibrillar center" "Mitochondria" ...
#
#
# download SUBCELLULAR LOCATION data
downloadedDtHIST$subcellular_location
# select only the proteins that are located in the PLASMA MEMBRANE
downloadedDtHIST$subcellular_location[downloadedDtHIST$subcellular_location$main_location=="Plasma membrane",]
gPlMb <- downloadedDtHIST$subcellular_location[downloadedDtHIST$subcellular_location$main_location=="Plasma membrane",c(1,2,3,4,5,14)]  %>% 
            as.data.frame()
View(gPlMb)
# see all the NORMAL TISSUES included in HPA = 62 + N/A
downloadedDtHIST$normal_tissue
unique(downloadedDtHIST$normal_tissue$tissue)
#  [1] "adipose tissue"    "adrenal gland"     "appendix"          "bone marrow"       "breast"            "bronchus"          "caudate"          
#  [8] "cerebellum"        "cerebral cortex"   "cervix, uterine"   "colon"             "duodenum"          "endometrium 1"     "endometrium 2"    
# [15] "epididymis"        "esophagus"         "fallopian tube"    "gallbladder"       "heart muscle"      "hippocampus"       "kidney"           
# [22] "liver"             "lung"              "lymph node"        "nasopharynx"       "oral mucosa"       "ovary"             "pancreas"         
# [29] "parathyroid gland" "placenta"          "prostate"          "rectum"            "salivary gland"    "seminal vesicle"   "skeletal muscle"  
# [36] "skin 1"            "skin 2"            "small intestine"   "smooth muscle"     "soft tissue 1"     "soft tissue 2"     "spleen"           
# [43] "stomach 1"         "stomach 2"         "testis"            "thyroid gland"     "tonsil"            "urinary bladder"   "vagina"           
# [50] "N/A"               "hypothalamus"      "hair"              "retina"            "lactating breast"  "skin"              "thymus"           
# [57] "cartilage"         "eye"               "pituitary gland"   "dorsal raphe"      "choroid plexus"    "substantia nigra"  "sole of foot" 
#
# select the LUNG and BREAST
gLUNG <- downloadedDtHIST$normal_tissue[downloadedDtHIST$normal_tissue$tissue=="lung" & downloadedDtHIST$normal_tissue$cell_type=="alveolar cells",] %>% 
            as.data.frame()
View(gLUNG)              
#
#
# download PATHOLOGY data
downloadedDtHIST$pathology
table(downloadedDtHIST$pathology$cancer)
# select only the proteins that are located in the PLASMA MEMBRANE
downloadedDtHIST$pathology[downloadedDtHIST$pathology$cancer=="colorectal cancer",]
gCRC <- downloadedDtHIST$pathology[downloadedDtHIST$pathology$cancer=="colorectal cancer",c(1:11)]  %>% 
            as.data.frame() %>% arrange(prognostic_unfavorable)
View(gCRC)
# see in HPA this page:
# https://www.proteinatlas.org/humanproteome/pathology/colorectal+cancer


### (Section 3.3) 
# Subset data with hpaSubset()
geneList <- c('TP53', 'EGFR', 'CD44', 'PTEN', 'IDH1', 'IDH2', 'CYCS')
tissueList <- c('breast', 'cerebellum', 'skin 1')
cancerList <- c('breast cancer', 'glioma', 'melanoma')
cellLineList <- c('A-431', 'A549', 'AF22', 'AN3-CA')
#
subsetData <- hpaSubset(data=downloadedDtHIST,
                        targetGene=geneList,
                        targetTissue=tissueList,
                        targetCancer=cancerList,
                        targetCellLine=cellLineList)
sapply(subsetData, nrow)
# normal_tissue            pathology   subcellular_location 
#            86                   21                      7 
subsetData$pathology
subsetData$pathology$cancer=="breast cancer"


### (Section 3.4) 
# Export data with hpaExport()
getwd()
setwd("/Users/javierd19/Desktop/R_Workshop_COST2021")
hpaExport(subsetData, fileName='subset', fileType='xlsx')


### (Section 4.1) 
# General Visualization = Unbrella function hpaVis()
hpaVis(targetGene = c("GCH1", "PTS", "SPR", "DHFR", "APP"),
       targetTissue = c("cerebellum", "cerebral cortex", "hippocampus"),
       targetCancer = c("glioma"))


### (Section 4.2,4.3,4.4) 
#
# Visualize tissue data with hpaVisTissue()
geneList <- c('TP53', 'EGFR', 'CD44', 'PTEN', 'IDH1', 'IDH2', 'CYCS', 'ESR1', 'PGR')
tissueList <- c('breast', 'cerebral cortex', 'skin 1')
#
hpaVisTissue(downloadedDtHIST,
             targetGene=geneList,
             targetTissue=tissueList)
#
# Visualize expression in cancer with hpaVisPatho()
geneList <- c('TP53', 'EGFR', 'CD44', 'PTEN', 'IDH1', 'IDH2', 'CYCS', 'ESR1', 'PGR')
cancerList <- c('breast cancer', 'glioma', 'lymphoma', 'prostate cancer')
# colorGray <- c('slategray1', 'slategray2', 'slategray3', 'slategray4')
colorGray <- c('azure', 'cyan2', 'cyan3', 'cyan4')
#
hpaVisPatho(downloadedDtHIST,
            targetGene=geneList,
            targetCancer=cancerList,
            color=colorGray)
#
# Visualize subcellular location data with hpaVisSubcell()
geneList <- c('TP53', 'EGFR', 'CD44', 'PTEN', 'IDH1', 'IDH2', 'CYCS', 'ESR1')
#
hpaVisSubcell(downloadedDtHIST,
              targetGene=geneList,
              customTheme=TRUE) +
  ggplot2::theme_minimal() +
  ggplot2::ylab('Subcellular locations') +
  ggplot2::xlab('Protein') +
  ggplot2::theme(axis.text.x=element_text(angle=45, hjust=1))  +
  ggplot2::theme(legend.position="none") +
  ggplot2::coord_equal()



ls()
sessionInfo()

###  END  ###
#########################################################################












