#########################################################################
### ### ###             Using_R_to_explore_GEO                ### ### ### 
#########################################################################
# Dr. Javier De Las Rivas (IBMCC, CSIC/USAL, Salamanca): jrivas@usal.es
#########################################################################
### GEOquery et al.
#########################################################################
# Query and explore GEO genomic database
# https://www.ncbi.nlm.nih.gov/geo/
#
# https://www.bioconductor.org/packages/release/bioc/vignettes/GEOquery/inst/doc/GEOquery.html
# 3.2 The GSE class
#
# Example GEOquery HTML:    GSE781 
# Example selected by me:   GSE106325 (9 samples Human BM-MSCs HGU133 plus2 :: 3 MSCnoc, 3 MSCcocul CRC cells1, 3 MSCcocul CRC cells2)

getwd()
setwd("/Users/javierd19/Desktop/R_Workshop_COST2021/")

library(GEOquery)


gse <- getGEO("GSE781",GSEMatrix=FALSE)
# or
gse <- getGEO(filename=system.file("extdata/GSE781_family.soft.gz",package="GEOquery"))
#
#
head(Meta(gse))
names(GSMList(gse))
GSMList(gse)[[1]]
names(GPLList(gse))


gse <- getGEO("GSE106325",GSEMatrix=FALSE)
# or 
gse <- getGEO(filename="/Users/javierd19/Desktop/R_Workshop_COST2021/GSE106325_family.soft.gz")
#
#
head(Meta(gse))
names(GSMList(gse))
# [1] "GSM2836109" "GSM2836110" "GSM2836111" "GSM2836112" "GSM2836113" "GSM2836114" "GSM2836115" "GSM2836116" "GSM2836117"
GSMList(gse)[[1]]
names(GPLList(gse))
# [1] "GPL570"



#########################################################################
# Version info: R 3.2.3, Biobase 2.30.0, GEOquery 2.40.0, limma 3.26.8
#########################################################################
#
#   Differential expression analysis with limma
library(GEOquery)
library(limma)
library(umap)
library(maptools)

### Load DATA ### load series and platform data from GEO

gset <- getGEO("GSE106325", GSEMatrix =TRUE, AnnotGPL=TRUE)
length(gset)
if (length(gset) > 1) idx <- grep("GPL570", attr(gset, "names")) else idx <- 1
gset <- gset[[idx]]
class(gset)
# [1] "ExpressionSet"
# attr(,"package")
# [1] "Biobase"


### Prepare the DATA ### make proper column names to match toptable 
fvarLabels(gset) <- make.names(fvarLabels(gset))


# group membership for all samples
gsms <- "000XXX111"
sml <- strsplit(gsms, split="")[[1]]
sml
# [1] "0" "0" "0" "X" "X" "X" "1" "1" "1"


# filter out excluded samples (marked as "X")
sel <- which(sml != "X")
sml <- sml[sel]
gset <- gset[ ,sel]
gset
# ExpressionSet (storageMode: lockedEnvironment)
# assayData: 54675 features, 6 samples 
#   element names: exprs 
# protocolData: none
# phenoData
#   sampleNames: GSM2836109 GSM2836110 ... GSM2836117 (6 total)
#   varLabels: title geo_accession ... gender:ch1 (34 total)
#   varMetadata: labelDescription
# featureData
#   featureNames: 1007_s_at 1053_at ... AFFX-TrpnX-M_at (54675 total)
#   fvarLabels: ID Gene.title ... GO.Component.ID (21 total)
#   fvarMetadata: Column Description labelDescription
# experimentData: use 'experimentData(object)'
# Annotation: GPL570 


# ExpressionSet "gset" and Expression data matrix "exprs(gset)"
class(exprs(gset))
str(exprs(gset))
dim(exprs(gset))
# [1] 54675     6
head(exprs(gset), 5)
#           GSM2836109 GSM2836110 GSM2836111 GSM2836115 GSM2836116 GSM2836117
# 1007_s_at 277.883916 295.787873 294.744154 181.975538  274.60111  280.49052
# 1053_at    42.551351  43.537344  33.606824  59.339138   47.94208   42.93027
# 117_at     15.322808  15.621831  13.347085  16.630662   15.31746   16.30624
# 121_at     73.725421  77.461191  85.927168  93.798349   73.71742   87.55844
# 1255_g_at   6.569269   5.794504   5.489103   9.611314   11.60570   11.35172
slotNames(gset)
# [1] "experimentData"  "assayData"   "phenoData"  "featureData"   "annotation"   "protocolData"   ".__classVersion__"


# log2 transformation
ex <- exprs(gset)
summary(ex[,1])
#  Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
# 1.593     6.154    17.294   136.532    67.583 12358.537 
summary(ex[,c(1,2,5,6)])
# GSM2836109          GSM2836110          GSM2836116          GSM2836117       
# Min.   :    1.593   Min.   :    1.597   Min.   :    1.610   Min.   :    1.593  
# 1st Qu.:    6.154   1st Qu.:    6.393   1st Qu.:    6.345   1st Qu.:    6.292  
# Median :   17.294   Median :   17.614   Median :   17.990   Median :   17.742  
# Mean   :  136.532   Mean   :  132.378   Mean   :  133.569   Mean   :  135.185  
# 3rd Qu.:   67.583   3rd Qu.:   63.586   3rd Qu.:   64.118   3rd Qu.:   64.344  
# Max.   :12358.537   Max.   :12330.193   Max.   :12156.383   Max.   :12600.458 
#
qx <- as.numeric(quantile(ex, c(0., 0.25, 0.5, 0.75, 0.99, 1.0), na.rm=T))
qx
# [1]     1.565857     6.320693    17.763949    64.582707  2276.898117 12854.944190
LogC <- (qx[5] > 100) || (qx[6]-qx[1] > 50  &&  qx[2] > 0)
# if TRUE this indicates that the data distribution is not in LOG scale
if (LogC) { ex[which(ex <= 0)] <- NaN
           exprs(gset) <- log2(ex) }
summary(exprs(gset)[,1])
#   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
# 0.6718  2.6216  4.1122  4.5182  6.0786 13.5932 


# assign samples to groups and set up design matrix
gs <- factor(sml)
groups <- make.names(c("MSCnoc","MSCcocCC"))
levels(gs) <- groups
groups
# [1] "MSCnoc"   "MSCcocCC"
gs
# [1] MSCnoc   MSCnoc   MSCnoc   MSCcocCC MSCcocCC MSCcocCC
# Levels: MSCnoc MSCcocCC
gset$group <- gs
design <- model.matrix(~group + 0, gset)
colnames(design) <- levels(gs)
design
#            MSCnoc MSCcocCC
# GSM2836109      1        0
# GSM2836110      1        0
# GSM2836111      1        0
# GSM2836115      0        1
# GSM2836116      0        1
# GSM2836117      0        1
# attr(,"assign")
# [1] 1 1
# attr(,"contrasts")
# attr(,"contrasts")$group
# [1] "contr.treatment"


### LIMMA for LINEAR MODEL ### linear model using LIMMA
# https://bioconductor.org/packages/release/bioc/html/limma.html
fit <- lmFit(gset, design)  # fit linear model


# set up contrasts of interest and recalculate model coefficients
cts <- paste(groups[1], groups[2], sep="-")
cts
# [1] "MSCnoc-MSCcocCC"
cont.matrix <- makeContrasts(contrasts=cts, levels=design)
fit2 <- contrasts.fit(fit, cont.matrix)


# compute statistics and table of top significant genes
fit2 <- eBayes(fit2, 0.01)
names(fit2)
#  [1] "coefficients"     "rank"             "assign"           "qr"               "df.residual"      "sigma"            "cov.coefficients" "stdev.unscaled"  
#  [9] "pivot"            "genes"            "Amean"            "method"           "design"           "contrasts"        "df.prior"         "s2.prior"        
# [17] "var.prior"        "proportion"       "s2.post"          "t"                "df.total"         "p.value"          "lods"             "F"               
# [25] "F.p.value" 
# Extract a table of the top-ranked genes from a linear model fit.
?topTable
# USAGE: topTable(fit, coef=NULL, number=10, genelist=fit$genes, adjust.method="BH", sort.by="B", resort.by=NULL, p.value=1, lfc=0, confint=FALSE)
tT <- topTable(fit2, adjust="fdr", sort.by="B", number=250)
colnames(tT)
#  [1] "ID"                    "Gene.title"            "Gene.symbol"           "Gene.ID"               "UniGene.title"         "UniGene.symbol"       
#  [7] "UniGene.ID"            "Nucleotide.Title"      "GI"                    "GenBank.Accession"     "Platform_CLONEID"      "Platform_ORF"         
# [13] "Platform_SPOTID"       "Chromosome.location"   "Chromosome.annotation" "GO.Function"           "GO.Process"            "GO.Component"         
# [19] "GO.Function.ID"        "GO.Process.ID"         "GO.Component.ID"       "logFC"                 "AveExpr"               "t"                    
# [25] "P.Value"               "adj.P.Val"             "B"     


tT <- subset(tT, select=c("ID","adj.P.Val","P.Value","t","B","logFC","Gene.symbol","Gene.title"))
write.table(tT, file=stdout(), row.names=F, sep="\t")
DEg_3MSCnoc3MSCcocCC <- write.table(tT, file=stdout(), row.names=F, sep="\t")
write.table(tT, file="DEg_3MSCnoc3MSCcocCC.txt", row.names=F, sep="\t")


getwd()
# [1] "/Users/javierd19/Desktop/R_Workshop_COST2021"
dir()




#########################################################################
### Plot DATA ###
# Visualize and quality control test results.
#
# Build histogram of p-values for all genes. Normal test
# assumption is that most genes are not differentially expressed.
tT2 <- topTable(fit2, adjust="fdr", sort.by="B", number=Inf)
hist(tT2$adj.P.Val, col = "grey", border = "white", xlab = "adj.p.value",
     ylab = "Number of genes", main = "adjusted p.value distribution")


# summarize test results as "up", "down" or "not expressed"
dT <- decideTests(fit2, adjust.method="fdr", p.value=0.05)
dT
# TestResults matrix
#          Contrasts
#           MSCnoc-MSCcocCC
# 1007_s_at               0
# 1053_at                 0
# 117_at                  0
# 121_at                  0
# 1255_g_at              -1
# 54670 more rows ...
summary(dT)
#        MSCnoc-MSCcocCC
# Down              2317
# NotSig           49119
# Up                3239
length(which(dT[,cts]!=0))
# [1] 5556


# Venn diagram of results
vennDiagram(dT, circle.col=palette())


### Create Q-Q PLOT for t-statistic
# QQ plot (or quantile-quantile plot) draws the correlation between a given sample and the normal distribution. 
# A "reference line" is also plotted. QQ plots are used to visually check the normality of the data. 
# If the distribution is truly a NORMAL the "reference line" will be at 45-degrees
t.good <- which(!is.na(fit2$F)) # filter out bad probes
#
qqt(fit2$t[t.good], fit2$df.total[t.good], main="Moderated t statistic / Q-Q plot")
qqline(fit2$t[t.good], col = "steelblue", lwd = 2, distribution = function(x) qt(x, df = fit2$df.total[1]))
# again with fixed X & Y limits; marking the X=0 and Y=0
qqt(fit2$t[t.good], fit2$df.total[t.good], main="Moderated t statistic / Q-Q plot", xlim=c(-30,30), ylim=c(-30,30))
abline(h=0 , v=0, col="red", lwd = 1)
abline(a=0 , b=1, col="green", lwd = 1) # added line at 45-degrees
qqline(fit2$t[t.good], col = "steelblue", lwd = 2, distribution = function(x) qt(x, df = fit2$df.total[1]))


### Volcano PLOT (log p-value vs log fold change)
# A volcano plot displays log fold changes on the x-axis versus a measure of statistical significance on the y-axis. 
colnames(fit2) # list contrast names
# [1] "MSCnoc-MSCcocCC"
ct <- 1        # choose contrast of interest
# str(dT)
# View(dT@.Data)
?volcanoplot
volcanoplot(fit2, coef=ct, main=colnames(fit2)[ct], pch=20,
            highlight=length(which(dT[,ct]!=0)), hl.col="green", names=rep('+', nrow(fit2)))
#
# Now add some features on the PLOT
abline(v=c(-2,2), col="red", lwd = 1)
abline(h=(-log10(0.005)), col="red", lwd = 1)
#
tTmod <- tT
tTmod$color <- ifelse((tTmod$P.Value<0.005 & tTmod$logFC>=2), "red", ifelse((tTmod$P.Value<0.005 & tTmod$logFC<=-2), "blue", "grey"))
table(tTmod$color)
points(x=tTmod$logFC[tTmod$color %in% "red"], y=-log10(tTmod$P.Value[tTmod$color %in% "red"]), col="red", pch=19)
points(x=tTmod$logFC[tTmod$color %in% "blue"], y=-log10(tTmod$P.Value[tTmod$color %in% "blue"]), col="blue", pch=19)
abline(h=(-log10(max(tTmod$P.Value))), col="darkred", lwd = 1)


### MD PLOT (log fold change vs mean log expression) ... similar to a MA plot
# highlight statistically significant (p-adj < 0.05) probes
?plotMD
plotMD(fit2, column=ct, status=dT[,ct], legend=F, pch=20, cex=1, 
       xlab="intensity AVERAGE [RANGE] : log2(A)+log2(B)/2", 
       ylab="intensity RATIO [FC] : log2(A/B)")
abline(h=0, col="green")




#########################################################################
# General expression data analysis
ex <- exprs(gset)


### Box PLOT, box-and-whisker plot
ord <- order(gs)  # order samples by group
# To look for a COLOR in RGB use "color-picker":
# https://htmlcolorcodes.com/color-picker/ 
palette(c("#1B9E77", "#7570B3", "#E7298A", "#E6AB02", "#D95F02",
          "#66A61E", "#A6761D", "#B32424", "#B324B3", "#666666"))
par(mar=c(7,4,2,1))
title <- paste ("GSE106325", "/", annotation(gset), sep ="")
boxplot(ex[,ord], boxwex=0.6, notch=TRUE, main=title, outline=FALSE, las=2, col=gs[ord])
legend("topleft", groups, fill=palette(), bty="o")
# legend("bottomright", groups, fill=palette(), bty="n")
boxplot(ex[,ord], boxwex=0.6, notch=TRUE, main=title, outline=TRUE, las=2, col=gs[ord])
legend(0.6,2.2, groups, fill=palette(), bty="n")


### Density PLOT, expression value distribution
par(mar=c(4,4,2,1))
title <- paste ("GSE106325", "/", annotation(gset), " value distribution", sep ="")
plotDensities(ex, group=gs, main=title, legend ="topright")


### UMAP PLOT: dimensionality reduction
ex <- na.omit(ex) # eliminate rows with NAs
ex <- ex[!duplicated(ex), ]  # remove duplicates
#
ump <- umap(t(ex), n_neighbors = 3, random_state = 123)
#
par(mar=c(3,3,2,6), xpd=TRUE)
plot(ump$layout, main="UMAP plot, nbrs=3", xlab="", ylab="", col=gs, pch=20, cex=1.5)
legend("topleft", inset=c(0.05,0), legend=levels(gs), pch=20,
       col=1:nlevels(gs), title="Group", pt.cex=1.5)
library("maptools")  # point labels without overlaps
pointLabel(ump$layout, labels = rownames(ump$layout), method="SANN", cex=0.6)


### PLOT residual SD vs MN : mean-variance trend, helps to see if precision weights are needed
# Sigma vs A plot for microarray linear model
# Plot residual standard deviation versus average log expression for a fitted microarray linear model.
par(mar=c(4,4,2,2))
plotSA(fit2, main="Mean variance trend, GSE106325")


### MA PLOT and fitting
par(mar=c(4,4,2,2), xpd=FALSE)
# Using the expression matrix
dim(ex)
# [1] 54668     6
head(ex)
#           GSM2836109 GSM2836110 GSM2836111 GSM2836115 GSM2836116 GSM2836117
# 1007_s_at   8.118339   8.208419   8.203319   7.507601   8.101194   8.131808
# 1053_at     5.411133   5.444181   5.070682   5.890912   5.583221   5.423923
# 117_at      3.937609   3.965492   3.738453   4.055774   3.937105   4.027352
# 121_at      6.204090   6.275402   6.425042   6.551491   6.203934   6.452174
# 1255_g_at   2.715733   2.534685   2.456570   3.264734   3.536762   3.504839
# 1294_at     5.936373   5.592073   5.613019   5.907793   5.811802   5.892673
#
# xlab="intensity AVERAGE [RANGE] : log2(A)+log2(B)/2", 
# ylab="intensity RATIO [FC] : log2(A/B)")
#
x <- rowMeans(ex[,])
A <- rowMeans(ex[,c(1,2,3)])
B <- rowMeans(ex[,c(4,5,6)])
AvB <- rowMeans(ex[,c(1,2,3)]) / rowMeans(ex[,c(4,5,6)])
y <- AvB
length(x)
length(y)
plot(x,y)
abline(h=1, col="green")
#
loessF <- loess(y~x)
plot(x,y)
lines(predict(loessF), col='red', lwd=1)



ls()
sessionInfo()

###  END  ###
#########################################################################
