-
Notifications
You must be signed in to change notification settings - Fork 0
/
S01-CoReMo-TSC-Analysis.Rmd
2146 lines (1961 loc) · 72.7 KB
/
S01-CoReMo-TSC-Analysis.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Systematic transcriptional investigation of epilepsy associated structural abnormalities: towards the identification of novel treatment targets"
subtitle: "Coregulated gene modules identification in TSC"
author: "Liesbeth François"
date: "`r format(Sys.time(), '%B %d %Y')`"
output:
html_document:
self_contained: yes
fig_height: 6
fig_width: 8
keep_md: yes
number_sections: yes
theme: cerulean
toc: yes
toc_float: yes
editor_options:
chunk_output_type: console
---
```{r setup, echo=F, eval = T, include=F}
rm(list=ls())
gc()
library(knitr)
library(kableExtra)
opts_chunk$set(
include=FALSE,
warning=FALSE, echo=FALSE, message=FALSE,
concordance=TRUE
)
library(beeswarm)
library(BiocParallel)
library(DT)
library(edgeR)
library(ggplot2)
library(here)
library(limma)
library(MASS)
library(openxlsx)
library(plotly)
library(RColorBrewer)
library(readxl)
library(scales)
library(tibble)
library(tximport)
library(CRAFT)
library(reshape2)
library(WGCNA)
library(ggrepel)
library(UpSetR)
library(cluster)
library(gplots)
library(pheatmap)
library(CoReMo)
library(lme4)
library(ggpubr)
library(rlist)
library(dplyr)
library(BED)
library(dendextend)
library(fgsea)
library(stringr)
library(factoextra)
library(heatmaply)
library(TKCat)
#
myPal = function(n=10){
#returns n colors
seq = rev(seq(0,255,by=255/(n)))
palRGB = cbind(seq,seq,255)
rgb(palRGB,maxColorValue=255)
}
bigFormat <- function(n){
format(n, big.mark=" ")
}
```
# Correction for technical covariates
Before applying any analyses, the impact of technical covariates and presence of outliers is assessed using PCA in two steps: 1. on the TSC samples only and 2. on TSC samples together with the control samples. Using PCA no covariates could be identified; however, after a first application of module identification, sequencing group was identified as a technical covariates. A batch correction for sequencing group was put in place to correct for this on the three different cohorts together.
## TSC samples
```{r , echo=F, eval = T, include=F}
load(here("Data/04_QC/Preprocessing.rda"))
sampleInfo <- sampleInfo %>%
filter(PA_Diagnosis %in% c("TSC")) %>%
mutate(log10_seizure_freq = log10(Seizure_Frequency_months))
table(sampleInfo$PA_Diagnosis, sampleInfo$Area_of_Resection)
all_samples <- sampleInfo
d <- vg$E[,sampleInfo$GS_RNASEQ_ID]
dim(d)
```
The PCA shows the impact of library preparation batch. In addition, 2 control samples will be removed from downstream analyses as they are part of a separate library preparation batch not present in the HS samples.
```{r, include = TRUE}
pca <- prcomp(t(d), center=TRUE, scale.=TRUE)
pcImp <- pca$sdev^2/sum(pca$sdev^2)
## Library prep batches
pcLib <- p.adjust(apply(
pca$x, 2,
function(pc){
head(pc)
toTest <- data.frame(
val=pc,
groups=as.factor(sampleInfo$Library_Prep_batch[match(rownames(pca$x),sampleInfo$GS_RNASEQ_ID)])
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
## Library prep batches
pcSeiz <- p.adjust(apply(
pca$x, 2,
function(pc){
head(pc)
toTest <- data.frame(
val=pc,
groups=sampleInfo$log10_seizure_freq[match(rownames(pca$x),sampleInfo$GS_RNASEQ_ID)]
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
## Sequencing groups
pcsgid <- p.adjust(apply(
pca$x, 2,
function(pc){
head(pc)
toTest <- data.frame(
val=pc,
groups=as.factor(sampleInfo$SGID[match(rownames(pca$x),sampleInfo$GS_RNASEQ_ID)])
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
## Tissue
pcArea <- p.adjust(apply(
pca$x, 2,
function(pc){
head(pc)
toTest <- data.frame(
val=pc,
groups=as.factor(sampleInfo$Area_of_Resection[match(rownames(pca$x),sampleInfo$GS_RNASEQ_ID)])
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
toShow<-data.frame(cbind(pcLib,pcsgid, pcArea, pcSeiz))
```
No impact of any covariate could be assessed (table below). Even the diagnosis was not a significant covariate to differentiate the two tumor types.
```{r, include = TRUE}
datatable(
toShow,
filter = "top",
options=list(pageLength=6)
) %>%
formatSignif(2, digits=3) %>%
formatSignif(1:ncol(toShow), digits=2) %>%
formatStyle(
1:ncol(toShow),
backgroundColor=styleInterval(
c(10^(-6), 0.05), colorRampPalette(c("darkred", "white"))(3)
),
color=styleInterval(
10^(-6), c("white", "black")
)
)
```
**PC1 versus PC2**
```{r, include = TRUE, fig.height=5}
toPlot <- sampleInfo %>%
bind_cols(as_tibble(pca$x[sampleInfo$GS_RNASEQ_ID,1:20]))
p <- ggplot(toPlot) +
geom_point(aes(x = PC1, y = PC4, col = Area_of_Resection), size = 2) +
theme_bw()
p
```
## TSC and control samples
```{r , echo=F, eval = T, include=F}
load(here("Data/04_QC/Preprocessing.rda"))
sampleInfo <- sampleInfo %>%
filter(PA_Diagnosis %in% c("TSC", "Control") &
!Area_of_Resection %in% c("Hippocampus")) %>%
mutate(log10_seizure_freq = log10(Seizure_Frequency_months)) %>%
filter(Age_At_Time_of_Operation <= 30)
all_samples <- sampleInfo
table(sampleInfo$PA_Diagnosis, sampleInfo$Area_of_Resection)
all_samples <- sampleInfo
d <- vg$E[,sampleInfo$GS_RNASEQ_ID]
dim(d)
```
```{r}
ggplot(all_samples, aes(x = PA_Diagnosis, y = Age_At_Time_of_Operation)) +
geom_boxplot()
```
```{r}
if(file.exists(here("Data/04_QC/TSC_expression_matrix_batch_corrected.rda"))){
load(here("Data/04_QC/TSC_expression_matrix_batch_corrected.rda"))
}else{
combn <- factor(sampleInfo$PA_Diagnosis)
design <- model.matrix(~0+combn)
colnames(design) <- levels(combn)
head(design)
bc_vg <- removeBatchEffect(d,
batch = sampleInfo$SGID,
design = design)
save("bc_vg", file = here("Data/04_QC/TSC_expression_matrix_batch_corrected.rda"))
}
```
```{r, include = TRUE}
d <- bc_vg
pca <- prcomp(t(d), center=TRUE, scale.=TRUE)
pcImp <- pca$sdev^2/sum(pca$sdev^2)
## Library prep batches
pcLib <- p.adjust(apply(
pca$x, 2,
function(pc){
head(pc)
toTest <- data.frame(
val=pc,
groups=as.factor(sampleInfo$Library_Prep_batch[match(rownames(pca$x),sampleInfo$GS_RNASEQ_ID)])
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
## Library prep batches
pcSeiz <- p.adjust(apply(
pca$x, 2,
function(pc){
head(pc)
toTest <- data.frame(
val=pc,
groups=sampleInfo$log10_seizure_freq[match(rownames(pca$x),sampleInfo$GS_RNASEQ_ID)]
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
## Sequencing groups
pcsgid <- p.adjust(apply(
pca$x, 2,
function(pc){
head(pc)
toTest <- data.frame(
val=pc,
groups=as.factor(sampleInfo$SGID[match(rownames(pca$x),sampleInfo$GS_RNASEQ_ID)])
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
## Tissue
pcArea <- p.adjust(apply(
pca$x, 2,
function(pc){
head(pc)
toTest <- data.frame(
val=pc,
groups=as.factor(sampleInfo$Area_of_Resection[match(rownames(pca$x),sampleInfo$GS_RNASEQ_ID)])
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
## Condition
pcDiag <- p.adjust(apply(
pca$x, 2,
function(pc){
head(pc)
toTest <- data.frame(
val=pc,
groups=as.factor(sampleInfo$PA_Diagnosis[match(rownames(pca$x),sampleInfo$GS_RNASEQ_ID)])
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
toShow<-data.frame(cbind(pcLib,pcsgid, pcDiag,pcArea, pcSeiz))
```
Only diagnosis is now a significant variable distuighing control samples from tumor samples although this differentiation is not strong as can be seen on the plots below.
```{r, include = TRUE}
datatable(
toShow,
filter = "top",
options=list(pageLength=6)
) %>%
formatSignif(2, digits=3) %>%
formatSignif(1:ncol(toShow), digits=2) %>%
formatStyle(
1:ncol(toShow),
backgroundColor=styleInterval(
c(10^(-6), 0.05), colorRampPalette(c("darkred", "white"))(3)
),
color=styleInterval(
10^(-6), c("white", "black")
)
)
```
**PC1 versus PC2**
The plot below shows the first two principal components with diagnosis and area of resection.
```{r, include = TRUE, fig.height=5}
toPlot <- sampleInfo %>%
bind_cols(as_tibble(pca$x[sampleInfo$GS_RNASEQ_ID,1:20]))
p <- ggplot(toPlot) +
geom_point(aes(x = PC1, y = PC2, col = PA_Diagnosis), size = 2) +
theme_bw()
p
```
# Gene mutations
No outliers or technical covariates could be identified. The table below shows the structure of the dataset consisting of `r sampleInfo %>% filter(PA_Diagnosis == "TSC") %>% nrow` TSC samples and `r sampleInfo %>% filter(PA_Diagnosis == "Control") %>% nrow` control samples.
```{r, include = TRUE}
kable(table(sampleInfo$PA_Diagnosis, sampleInfo$Gene))
```
# Module identification
This reports deals with the identification of modules of gene coregulation in tuberous sclerosis complex (TSC) and assessment of the conservation of the identified regulations in other contexts. The coregulation modules are build across the different tissue that show similarity in gene expression and have sufficient amount of samples to avoid interference of tissue-specific regulations. For TSC there are 20 samples that will be used to identified gene modules of coregulation. Library preparation batch was identified to impact gene expression for TSC samples. Therefore, a batch correction was performed using limma R package to avoid that library preparation batch might drive the module identification.
A detailed explanation of the identification of gene co-expression modules can be found in [Srivastava et al. 2018](https://www.nature.com/articles/s41467-018-06008-4) or the Epinet project. Briefly, the different steps consist of:
<ol>
<li> Differential expression analysis on gene level between tumor cohorts and healthy patients </li>
<li> Gene filtering based on variance in expression </li>
<li> Scale-free fit index </li>
<li> Unsupervised hierarchical clustering and defining the optimal number of clusters </li>
<li> Module robustness assessment </li>
<li> Module overview and association to phenotype </li>
<li> Functionally annotation of the modules </li>
<li> Identification of "healthy" regulations by comparison with coregulation modules constructed in healthy tissue </li>
<li> Assessment of conservation in other pathologies and contexts to understand the functions of the module in the broader context of epilepsy and identify potential specific regulations </li>
<li> Differential co-expression of modules compared to control samples </li>
<li> Causal reasoning for prediction of upstream regulators </li>
</ol>
## Differential expression analysis on gene level between tumor cohorts and healthy patients
Due to the unbalance between tumor samples (`r sampleInfo %>% filter(PA_Diagnosis != "Control") %>% nrow()` samples) and control samples (`r sampleInfo %>% filter(PA_Diagnosis == "Control") %>% nrow()` samples), there may be more genes significantly differentially expressed between the two groups ([Yang et al. 2006](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1780111/)).
```{r deg, cache=FALSE,echo=FALSE}
resFile <- here("Data/06_Modules/TSC/Module-Data","DEG.rda")
if(file.exists(resFile)){
load(resFile)
}else{
## design, timepoint as fixed effect
dd <- bc_vg[,pull(sampleInfo, GS_RNASEQ_ID)]
s <- all_samples %>%
as_tibble()
combn <- factor(gsub(" ", "" , s$PA_Diagnosis))
##
design <- model.matrix( ~ 0 + combn)
colnames(design) <- c(levels(combn))
dim(design)
## lm
fit <- lmFit(object = dd,
design = design)
##
contrast.matrix <- makeContrasts(TSC-Control, levels = design)
fit2 <- contrasts.fit(fit, contrast.matrix)
fit2 <- eBayes(fit2)
deg <- topTable(fit = fit2, coef = 1, number = Inf)
rm(combn, design, fit, contrast.matrix, fit2)
save(deg, file=resFile)
}
```
Top 1000 genes
```{r, include = TRUE}
gd <- getBeIdDescription(rownames(deg),
be = "Gene",
source = "Ens_gene",
organism = "human")
toShow <- deg %>%
mutate(Gene = gd$symbol[match(rownames(deg), gd$id)])
datatable(toShow %>%
select(Gene, AveExpr, logFC, FDR = adj.P.Val) %>%
arrange(FDR) %>%
slice(1:1000),
rownames = FALSE,
filter = "top",
extensions = 'Buttons',
options = list(
dom = "Blfrtip",
buttons = c('csv'),
order = list(list(3, "asc")),
autoWidth = TRUE)) %>%
formatSignif(c("AveExpr","logFC", "FDR"), 2)
```
## Gene filtering depending on variance
```{r mad,echo=FALSE}
sampleInfo <- sampleInfo %>% filter(PA_Diagnosis %in% c("TSC"))
d <- bc_vg[,sampleInfo$GS_RNASEQ_ID]
sdThr <- 0.25
MAD <- apply(d,1,function(x) mad(x))
```
For the identification of co-expression modules only genes showing high variance across the samples are kept for clustering analysis. Standard deviation has been
estimated using the median absolute deviation (MAD) in order to avoid outlier
triggered bias. Before MAD filtering there were `r bigFormat(nrow(d))` genes in the dataset.
The figure below shows the distribution of gene expression MAD
across all samples.
```{r mad_plot, include=TRUE,echo=FALSE, fig.height=5}
hist(
MAD, breaks=100,
col="grey",
xlab="MAD",
main="MAD of gene expression"
)
abline(v=sdThr, col="red", lty=2, lwd=2)
```
```{r}
KeptProbes <- names(MAD)[which(MAD >= sdThr)]
length(KeptProbes)
d <- bc_vg[KeptProbes, sampleInfo$GS_RNASEQ_ID]
save(KeptProbes,
file = here("Data","06_Modules/TSC/Module-Data", "List-KeptProbes.rda"))
```
It has been arbitrarily decided to keep only the
`r bigFormat(length(KeptProbes))` genes showing a MAD greater or equal
to `r sdThr`.
```{r cormat, cache=FALSE,echo=FALSE,include=FALSE}
## Create Spearman correlation matrix for all genes dislaying variance (MAD > 0.25)
corMeth <- "spearman"
sampGroup <- "TSC"
sampleInfo <- sampleInfo %>% filter(PA_Diagnosis %in% c("TSC"))
dim(d)
corFile <- here("Data","06_Modules/TSC/Module-Data",
paste0(corMeth,"-KeptProbes-",sampGroup,".rda"))
##
if(!file.exists(here("Data","06_Modules","TSC/Module-Data/Modules-TSC"))){
if(!file.exists(corFile)){
message(paste("Applying ", corMeth, " on ", sampGroup, "..."))
message(Sys.time())
message(corMeth, " correlation in ", sampGroup)
corMat <- cor(t(d), method=corMeth)
save(corMat,file=corFile)
gc()
message("... Done")
message(Sys.time())
}else{
load(corFile)
}
}
```
## Scale-free fit index
<blockquote>
Constructing a weighted gene network entails the choice of the
soft thresholding power β to which co-expression
similarity is raised to calculate adjacency
([Zhang and Horvath 2005](https://www.ncbi.nlm.nih.gov/pubmed/16646834)).
[Zhang and Horvath (2005)](https://www.ncbi.nlm.nih.gov/pubmed/16646834)
have proposed to choose the soft thresholding
power based on the criterion of approximate scale-free topology.
<footer><cite>
[Tutorial for the WGCNA package for R](https://labs.genetics.ucla.edu/horvath/htdocs/CoexpressionNetwork/Rpackages/WGCNA/Tutorials/Consensus-NetworkConstruction-man.pdf)
</cite></footer>
</blockquote>
The figure below shows the the scale-free fit index and the mean connectivity as a function of the soft-thresholding power.
```{r scalefree,include=FALSE,echo=FALSE}
## Scale-free fit index
defaultSoftPower <- 6
## Choose a set of soft-thresholding powers
powers <- 1:20
## Call the network topology analysis function
r2cut <- 0.85
sFile <- here("Data", "06_Modules", "TSC/Module-Data/ScaleFreeIndex_TSC.rda")
if(file.exists(sFile)){
load(sFile)
}else{
sft <- WGCNA::pickSoftThreshold(t(d),
powerVector = powers,
RsquaredCut = r2cut,
verbose = 0,
corOptions = list(method=corMeth)
)
save(sft, file = sFile)
}
```
```{r scalefree_plot,include=TRUE,echo=FALSE, fig.height=6}
opar <- par(no.readonly=T)
par(mfrow = c(1,2));
cex1 = 0.9;
## Scale-free topology fit index as a function of the soft-thresholding power
plot(
sft$fitIndices[,1],
-sign(sft$fitIndices[,3])*sft$fitIndices[,2],
xlab="Soft Threshold (power)",
ylab="Scale Free Topology Model Fit, signed R²",
type="n",
main = "Scale independence"
)
text(
sft$fitIndices[,1],
-sign(sft$fitIndices[,3])*sft$fitIndices[,2],
labels=powers, cex=cex1, col="red"
)
abline(h=r2cut,col="red", lty=2)
abline(
h=-sign(sft$fitIndices[,3])*sft$fitIndices[,2][which(sft$fitIndices[,1]==defaultSoftPower)],
col="blue", lty=2
)
## Mean connectivity as a function of the soft-thresholding power
plot(
sft$fitIndices[,1],
sft$fitIndices[,5],
xlab="Soft Threshold (power)",
ylab="Mean Connectivity", type="n",
main = paste("Mean connectivity")
)
text(
sft$fitIndices[,1],
sft$fitIndices[,5],
labels=powers,
cex=cex1,
col="red"
)
par(opar)
```
## Unsupervised hierarchical clustering and defining the optimal number of clusters
```{r clust,include=FALSE,echo=FALSE}
clMeth <- "ward.D"
softPower <- defaultSoftPower
minClusSize <- 1
##
subcorDir <- here("Data", "06_Modules", "ClustModules")
dir.create(subcorDir,showWarnings = FALSE)
corFile <- here("Data", "06_Modules", "TSC", "ClustModules",
"Clustering_TSC.rda")
##
if(file.exists(corFile)){
load(corFile)
}else{
distMat <- 1-abs(corMat)^softPower
distMat <- as.dist(distMat)
tree <- stats::hclust(d=distMat, method=clMeth)
rm(distMat)
gc()
}
```
Clustering using the `r clMeth` clustering method is performed on the correlation matrix.
```{r treecut,echo=FALSE}
if(!file.exists(corFile)){
cutOpt <- treeCutQual(
tree,
corMat,
k.min = 1,
k.max = 200 ,
minsize = minClusSize ,
d = d,
corMeth = corMeth #, mc.cores=3
)
kinfl <- CoReMo::getInflPoint(cutOpt[,c("k", "R2 weighted median")])
rm(cutOpt)
gc()
}
```
The optimal number of clusters was identified using a static cut comparing different levels of K clusters. The chosen number of clusters is selected when the increase of weighted average
of R<sup>2</sup> reaches a plateau ($d(dy/dx)/dx \approx 0$). No minimum cluster size for the downstream analyses has been set.
```{r treecut_plot, include=TRUE,echo=FALSE, fig.height=5}
CoReMo::plotInfl(kinfl)
ksel <- attr(kinfl, "xlim")
```
```{r clustqual, echo=FALSE}
if(!file.exists(corFile)){
clusters <- CoReMo::msCutree(tree,
k = ksel,
minsize = minClusSize,
d = d,
corMeth = corMeth)
qc <- CoReMo::clQual(clusters,
corMat = corMat)
junkModule <- rownames(qc)[which(qc[,"r2med"] < 0.05)]
inJunk <- names(clusters)[which(clusters == junkModule)]
notInJunk <- setdiff(names(clusters), inJunk)
save(
tree, kinfl, clusters, qc, junkModule, inJunk, notInJunk,
file = corFile
)
}
```
Genes have finally been divided into `r nrow(qc)` modules (including one junk module).
## Module robustness
The leave-one-out bootstrapping procedure is used to assess the impact of samples on the stability and robustness of gene coregulation modules. For each permutation, the correlation matrix is calculated and the modules are constructed and their membership recorded. To apply this procedure, the number of clusters has already been defined beforehand using the full dataset and standard CoReMo procedure. This procedure only aims to identify more robust module memberships by LOO bootstrapping. Finally, a similarity matrix is build based on cluster membership across the different permutations to identify junk modules based on an arbitrary threshold. After identification of junk module members, these are removed from the analyses and the remaining genes are clustered by using the similarity matrix as input. These are the robust modules derived from LOO bootstrapping procedure.
```{r module_settings}
wgcna.clMeth <- "ward.D"
wgcna.corMeth <- "spearman"
wgcna.softPower <- 6
wgcna.minClusSize <- 1
wgcna.k <- 16
```
```{r, eval = FALSE}
# source(here("Analysis/E01-Module-Robustness-Bootstrapping.R"))
```
```{r ls_permutate_modules}
load(here("Data/06_Modules/TSC/Module-Data/LOO_TSC_Cluster.rda"))
load(here("Data/06_Modules/TSC/Module-Data/Bootstrapping_Similarity_TSC.rda"))
```
After application of the leave-one-one procedure, `r length(unique(junk.genes))` genes are categorized as junk genes in at least one bootstrap. `r table(junk.genes) %>% {.[. == 65]} %>% length` genes are always assigned to the junk genes. If gene is assigned to the junk module more than 50% of the permutations, this gene will be considered as junk, leaving `r length(junk.genes.out)` genes within the junk module that are and are removed from the analysis. Finally, the modules are constructed by clustering the remaining gene using the similarity matrix constructed during bootstrapping. This matrix captures the number of times gene are co-clustered during the leave-one-out procedure resulting in more robust modules. This leaves `r nrow(LOO.clusters) - length(junk.genes.out)` assigned to `r wgcna.k` coexpression modules.
```{r, include = TRUE, fig.height=4}
junk.genes.thres <- (length(unique(mod.decision$Bootstrap)) - 1)/2
toShow <- as.vector(table(junk.genes))
hist(toShow[toShow < max(toShow)], main = "Distribution of junk membership")
abline(v = junk.genes.thres)
text(x=junk.genes.thres+6, y=1000, "50% threshold")
```
```{r ls_consensuscluster}
# Consensus Cluster
dist.matrix <- as.dist(1 - (similarity.mat/(ncol(LOO.clusters)-1)))
# # Simple Ordering
clus.memb <- dist.matrix %>%
stats::hclust(., method = "ward.D") %>%
cutree(., k=(wgcna.k-1)) %>% sort
hm.order <- names(clus.memb)
sim.mat.out <- similarity.mat %>%
.[match(hm.order, rownames(.)),] %>%
.[,match(hm.order, colnames(.))]
## Compare to original clusters
BS_clusters <- LOO.clusters %>%
dplyr::select(ensgene, BS_0) %>%
left_join(stack(clus.memb) %>%
mutate_if(is.factor, as.character) %>%
rename(BSF = values,
ensgene = ind),
by = "ensgene")
```
```{r}
# Internal Module Correlation vs Average Similarity
if(file.exists(here("Data/06_Modules/TSC/Module-Data/TSC_CorrMembership.rda"))){
load(here("Data/06_Modules/TSC/Module-Data/TSC_CorrMembership.rda"))
}else{
data.modcor <- data.frame()
for(j in 1:max(clus.memb)) {
subset.genes <- clus.memb %>% .[. == j] %>% names
cormat.subset <- corMat %>%
.[subset.genes, subset.genes] %>%
.[upper.tri(.)] %>% abs %>%
{. ^ 2} %>% mean
cormat.sim <- similarity.mat %>%
.[subset.genes,subset.genes] %>%
.[upper.tri(.)] %>% median
module.size <- length(subset.genes)
data.modcor <- rbind(data.modcor, c(j, cormat.subset, module.size, cormat.sim))
}
data.modcor <- data.modcor %>%
as.data.frame %>%
`colnames<-`(c("Module", "Median R2",
"Module Size",
"Median Similarity"))
data.clusters <- clus.memb
data.cormat <- corMat[names(data.clusters),names(data.clusters)]
save(data.clusters, data.cormat, data.modcor,
file = here("Data/06_Modules/TSC/Module-Data/TSC_CorrMembership.rda"))
}
```
```{r, include = FALSE}
datatable(data.modcor,
rownames = FALSE) %>%
formatSignif(2, digits = 2)
```
The plot below shows the module's median R² and its median similarity within each module, namely the median of the number of times genes within the modules are co-clustered during the leave-one-out bootstrapping procedure. The size represents the number of genes within the module.
```{r, include = TRUE, fig.height=5}
modcor.gg <- data.modcor %>%
ggplot(., aes(`Module Size`, `Median R2`, label = `Module`)) +
geom_vline(xintercept = 0, linetype = "dashed", alpha = 0.5) +
geom_hline(yintercept = 0, linetype = "dashed", alpha = 0.5) +
geom_point(aes(size = `Median Similarity`)) +
geom_label_repel() +
theme_bw() +
labs(title = "Module Size Against Module Internal Median R2")
ggplotly(modcor.gg)
```
```{r size_plot,include = FALSE}
plot(
data.modcor$`Module Size`, data.modcor$`Median R2`,
# log = "x",
xlab = "size", ylab = "R²",
main = paste("Module quality in", sampGroup),
type = "n"
)
text(
data.modcor$`Module Size`, data.modcor$`Median R2`,
rownames(data.modcor),
cex=0.5
)
```
Data of the modules is available in the **Data/06_Modules/TSC** folder.
```{r size_tb,include=FALSE,echo=FALSE, eval = FALSE}
toShow <- as.data.frame(table(data.clusters))
datatable(
toShow,
rownames=FALSE,
colnames=c("Module","Number of genes"),
elementId=paste0("ModuleNamesShow-", round((10^6)*runif(1)))
)
```
## Module overview and association to phenotype
After construction of the modules, potential sub-modules are identified when positively correlated and anti-correlated genes are present in the module. The sub-modules are identified by the suffix "o" and "u" based on mean logFC between HS and the control samples.
```{r mod_anno, cache=FALSE,eval = TRUE, echo=FALSE}
corFile <- here("Data","06_Modules","TSC/Module-Data/Modules-TSC.rda")
if(file.exists(corFile)){
load(corFile)
}else{
modules <- list()
modules.Ensembl <- list()
modules.entrez <- list()
for(mid in unique(data.clusters)){
m <- names(data.clusters[which(data.clusters == mid)])
mid <- paste(sampGroup, mid, sep = ".")
resFile2 <- here("Data/06_Modules/TSC/ClustModules", paste0(mid, ".rda"))
if(file.exists(resFile2)){
load(resFile2)
}else{
mCorMat <- data.cormat[m, m]
attr(mCorMat, "geneMed") <- apply(mCorMat^2, 2, median) # squared values
save(mCorMat, file=resFile2)
}
lfc <- deg[m, "logFC"]
names(lfc) <- m
modules.Ensembl[[mid]] <- getSubModules(mCorMat, lfc)
modules[[mid]] <- mCorMat
}
## Convert to Entrez gene IDs
modules.entrez <- lapply(
modules.Ensembl,
convBeIdLists,
from = "Gene", from.source = "Ens_gene", from.org = "human",
to = "Gene", to.source = "EntrezGene", to.org = "human",
restricted=TRUE
)
moduleList <- BED::BEIDList(rlist::list.flatten(modules.Ensembl))
save(modules, modules.Ensembl, modules.entrez, moduleList, file = corFile)
}
rm(corMat, mgtex, mCorMat, dn, degf, dn, gtex, clust.memb,
cormat.sim, cormat.subset)
gc()
```
The association of the module with any of the recorded phenotypes is tested using linear regression for each module's eigenGene and the different phenotypes. As duration and age are not independent of each other, the association for duration is corrected for age.
The table below shows the overview of the modules, the number of genes, average R², and FDR of the association with different phenotypes.
```{r batchAss}
## Eigen genes
mvec <- stack(lapply(modules.Ensembl, unlist))
mvecVal <- as.character(mvec$ind)
names(mvecVal) <- mvec$values
mvec <- mvecVal
rm(mvecVal)
length(mvec)
##
eigenGenes <- getEigenValues(mvec, d)
egg <- t(eigenGenes)
tb <- sampleInfo[match(rownames(egg), sampleInfo$GS_RNASEQ_ID),] %>%
as_tibble()
egg <- cbind(tb, egg) %>%
mutate(
Gender = as.factor(Gender)
)
## Checking pup/batch/gender effects on module construction
modulesTable <- list()
size <- sapply(modules.Ensembl, function(x){length(unlist(x))} )
r2 <- sapply(modules, function(x){median(as.dist(x^2))})
o.size <- sapply(modules.Ensembl, function(x){length(x$o)})
u.size <- sapply(modules.Ensembl, function(x){length(x$u)})
##
seizfreqAss <- p.adjust(apply(
egg[,grep("TSC[.]",colnames(egg))], 2,
function(pc){
toTest <- data.frame(
val=pc,
groups=egg$log10_seizure_freq
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
##
genderAss <- p.adjust(apply(
egg[,grep("TSC[.]",colnames(egg))], 2,
function(pc){
toTest <- data.frame(
val=pc,
groups=as.factor(egg$Gender)
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
##
ageAss <- p.adjust(apply(
egg[,grep("TSC[.]",colnames(egg))], 2,
function(pc){
toTest <- data.frame(
val=pc,
groups=egg$Age_At_Time_of_Operation
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
##
durAss <- p.adjust(apply(
egg[,grep("TSC[.]",colnames(egg))], 2,
function(pc){
toTest <- data.frame(
val=pc,
groups=egg[, c("Duration_years", "Age_At_Time_of_Operation")]
)
drop1(lm(data=toTest,
formula=val~groups.Duration_years+groups.Age_At_Time_of_Operation),
test="F")[2,"Pr(>F)"]
}
), method="BH")
##
SGIDAss <- p.adjust(apply(
egg[,grep("TSC[.]",colnames(egg))], 2,
function(pc){
toTest <- data.frame(
val=pc,
groups=as.factor(egg$SGID)
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
##
libAss <- p.adjust(apply(
egg[,grep("TSC[.]",colnames(egg))], 2,
function(pc){
toTest <- data.frame(
val=pc,
groups=as.factor(egg$Library_Prep_batch)
)
summary(aov(formula=val~groups, data=toTest))[[1]]$`Pr(>F)`[1]
}
), method="BH")
modulesTable <- tibble(Module = names(modules.Ensembl),
`Module size` = size,
R2 = r2,
`O Size` = o.size,
`U Size` = u.size,
# `Tumor type` = diagAss[names(modules.Ensembl)],
`Seizure frequency` = seizfreqAss[names(modules.Ensembl)],
Age = ageAss[names(modules.Ensembl)],
Gender = genderAss[names(modules.Ensembl)],
`Duration (years)` = durAss[names(modules.Ensembl)],
`Sequencing group` = SGIDAss[names(modules.Ensembl)],
`Library batch` = libAss[names(modules.Ensembl)])
save(modulesTable,
file = here("Data", "06_Modules/TSC/Module-Data/PhenotypeAssociation.rda"))
```
```{r, include = TRUE}
shown <- datatable(modulesTable) %>%
formatSignif(c(3,6:11), digits = 2) %>%
formatStyle(
c(6:11),
backgroundColor = styleInterval(c(0.05), c('#afe575', 'transparent'))) %>%
formatStyle(
"O Size",
background = styleColorBar(modulesTable$"O Size", "#F08080"),
backgroundSize = '100% 90%',
backgroundRepeat = 'no-repeat',
backgroundPosition = 'center') %>%
formatStyle(
"U Size",
background = styleColorBar(modulesTable$"U Size", "#F08080"),
backgroundSize = '100% 90%',
backgroundRepeat = 'no-repeat',
backgroundPosition = 'center')
absMax <- max(abs(range(modulesTable$R2, na.rm=TRUE)))
breaks <- seq(-absMax, absMax, length.out=20)
cols <- colorRampPalette(c("blue", "white", "red"))(21)
shown <- formatStyle(
shown, "R2",
backgroundColor = styleInterval(breaks, cols)
)
shown
```
# Functional annotation {.tabset}
In this section, each module is functionally annotated by calculating the overlap of the genes inside with different biological databases. To establish whether the overlap between a module’s genes and genes in a biological pathway is significant a hypergeometric test is used.
```{r}
toTest <- rlist::list.flatten(modules.Ensembl)
eg <- rownames(d)
bescope = list(be = "Gene", source = "Ens_gene", organism = "human")
```
## MetaBase pathway maps
```{r}
# faFile <- here("Data", "06_Modules", "TSC/Module-Data/FunctionalAnnotation-TSC.rda")
if(!file.exists(faFile)){
nbeidsLim <- c(10, 500)
fl <- do.call(focusOnScope, c(
list(
x=getBekBeids(
externalKnowledge="MetaBase_pathway",
nbeids=nbeidsLim
),
force=TRUE
),
bescope
))
tmp <- unlist(lapply(fl, length))
fl <- fl[which(tmp>=min(nbeidsLim) & tmp <= max(nbeidsLim))]
names(fl) <- metadata(fl)$externalID
res <- TBTools::qrlEnrich(
query=toTest, reference=fl,
omega=eg,
mc.cores=30
)
colnames(res) <- c(
"uuid", "query", "ruuid", "reference",
"intersection", "p-value", "FDR"
)
res <- do.call(rbind, by(
res,
res$uuid,
function(d){
d$rank <- rank(-log10(d$"p-value"))
d$relRank <- d$rank/max(d$rank, na.rm=TRUE)
return(d)
}
))
rownames(res) <- NULL
resMB <- res %>%
mutate(type = "MetaBase_pathway") %>%
inner_join(metadata(fl) %>% select("externalID", name),
by = c("ruuid" = "externalID")) %>%
mutate(Pathway = paste0(sprintf('<a href="https://portal.genego.com/cgi/imagemap.cgi?id=%s" target="_blank">%s</a>',
ruuid,
name)))
}