-
Notifications
You must be signed in to change notification settings - Fork 0
/
MethyatlonAnalysis.Rmd
executable file
·5444 lines (4268 loc) · 180 KB
/
MethyatlonAnalysis.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: "Canary BRCA1/2 Methylation"
author: "Ian Beddows"
date: '`r format(Sys.Date(), "%B %d, %Y")`'
params:
rmd: ""
output:
html_document:
dev: png
code_folding: hide
self_contained: yes
toc: true
toc_depth: 2
toc_float:
collapsed: false
smooth_scroll: true
number_sections: true
df_print: paged
css: styles.css
---
Tested in R version `r getRversion()`.
```{r setup,echo=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
message = FALSE,
warning = FALSE,
cache = TRUE,
cache.lazy = FALSE
)
```
```{r loadlibs}
# BiocManager::install(site_repository = 'biobenkj/biscuiteer',update=TRUE) - not working
# remotes::install_github(repo = 'biobenkj/biscuiteer') # dev version - is working
suppressPackageStartupMessages({
library(yaml)
library(xtable)
library(kableExtra)
library(tidyverse)
library(reshape2)
library(matrixStats)
library(ggplot2)
library(ggrepel)
library(biscuiteer)
library(patchwork)
library(ggrepel)
library(bsseq)
library(ComplexHeatmap)
library(DMRcate)
library(Gviz)
library(rstatix)
library(bbplot)
})
```
```{r source_methFunctions.R,cache=FALSE}
source("~/Desktop/biscuiteer_adjacent_R_functions/methFunctions.R")
# source bisplotti
source("~/Desktop/bisplotti/R/epistate.R")
HeatmapFromBed <- function(myChr,myRanges,nameArg,clip=0,cluster_rows=TRUE){
bs_list <- generate_or_load_bsseq_list(
path='../Biscuit_Snakemake_Workflow/analysis/pileup/',
vcf_header_path = '../Biscuit_Snakemake_Workflow/analysis/pileup/',
name=nameArg,
sampNames=meta$SVC,
readBiscuitMergedFlag=TRUE,
whichFlag = GRanges(
seqnames=myChr,
ranges=myRanges,
strand='*'
)
)
names(bs_list) <- meta$SVC
# unique(unlist(lapply(bs_list,FUN=function(x){return(rownames(x))})))
tictoc::tic("Unionize")
myBS <- bs_list[[1]]
# combineList <- edit(bsseq::combineList)
# add
# `checkDimnames = FALSE` to the se call at the very end!
# (see https://github.com/hansenlab/bsseq/pull/113/commits/d4a2305f1fe5d9e65312f9a4575ff942fd0c21eb)
for (i in seq(2,length(bs_list))){
cat(i,names(bs_list)[i],nrow(bs_list[[i]]),"\n")
myBS <- combineList(list(bs_list[[i]],myBS))
}
tictoc::toc()
betaMatrix.tidy <- do.call('rbind',
lapply(
seq_along(bs_list), FUN = function(
x,n,i
){
# print(paste(x[i],n[i],i))
cbind(
data.frame(rowRanges(x[[i]])),
beta = as.numeric(round(x[[i]]@assays@data$M / x[[i]]@assays@data$Cov, 2)),
depth = as.numeric(x[[i]]@assays@data$Cov),
sample = rep(n[[i]],nrow(x[[i]]))
)
},
x=bs_list,
n=names(bs_list)
)
)
betaMatrix.tidy$pos <- paste0(betaMatrix.tidy$seqnames,':',betaMatrix.tidy$start)
## GET THE BETA MATRIX
betaMatrix <- betaMatrix.tidy %>%
dplyr::select(one_of(c('sample','beta','pos'))) %>%
tidyr::pivot_wider(values_from = beta,names_from = sample)
dim(betaMatrix)
betaMatrix <- dplyr::arrange(betaMatrix,pos)
.rownames <- betaMatrix$pos
betaMatrix <- dplyr::select(betaMatrix,-pos)
dim(betaMatrix)
# rownames(betaMatrix) <- .rownames
# if(clip>0){betaMatrix <- head(betaMatrix,clip)}
### arrange the order
meta.tmp <- dplyr::arrange(meta,`ReproductiveStatus`,DaysSinceLMP)
meta.tmp$groupBRCA = factor(meta.tmp$groupBRCA,levels=c('NON-BRCA','BRCA1','BRCA2'))
betaMatrix <- betaMatrix[,meta.tmp$sample]
rownames(betaMatrix) <- .rownames
stopifnot(all(colnames(betaMatrix)==meta.tmp$sample))
betaMatrix <- t(betaMatrix)
stopifnot(all(rownames(betaMatrix)==meta.tmp$sample))
### REMAKE THE ANNOTATION SINCE THE ORDER IS CHANGED
haRowMasterFUNCTION <- rowAnnotation(
`Stroma` = meta.tmp$MIR200cAvgBeta,
`Reproductive Status` = meta.tmp$ReproductiveStatus,
`Age` = meta.tmp$`Age at time of surgery`,
`BRCA Germline` = meta.tmp$groupBRCA,
# `LMP explanation` = meta.tmp$LMP_explanation,
`Race` = meta.tmp$Race,
col = list(
`Stroma` = circlize::colorRamp2(
breaks = seq(from = 0, to = 1, length = 20),
colors = colorRampPalette(c("white", "black"))(20)
),
Pilot = c(
'A' = pal[1],
'B' = pal[2]
),
`Reproductive Status` = c(
'Pre' = '#28BBECFF',
'Post' = '#FB8022FF'
),
`BRCA Germline` = c(
'BRCA1' = '#40498e',
'BRCA2' = '#38aaac',
'NON-BRCA' = 'black'
),
Race = c(
'Asian' = pal2[1],
'Black' = pal2[2],
'East Indian' = pal2[3],
'Hispanic Latino/White' = pal2[4],
'White' = pal2[5],
'Other' = 'grey44'
),
`Age` = circlize::colorRamp2(
breaks = seq(from = 20, to = 72, length = 20),
colors = colorRampPalette(c("gray75", "gray10"))(20)
),
DaysSinceLMP = circlize::colorRamp2(
breaks = seq(from = 6, to = 368, length = 50),
colors = colorRampPalette(c("white", "blue"))(50)
),
`LMP explanation` = c(
'F2M on Testosterone' = 'orange',
'Perimennopausal' = 'lightblue2',
'Post' = 'red',
'Pregnancy' = 'pink'
)
)
)
# new_order <- match(ordered,rownames(betaMatrix))
# betaMatrix2 <- betaMatrix[new_order,]
myHM <- ComplexHeatmap::Heatmap(
betaMatrix,
show_column_names = FALSE,
col=viridis::cividis(20),
cluster_rows = cluster_rows,
cluster_columns = FALSE,
heatmap_legend_param = list(title='Beta'),
row_title_gp = gpar(fontsize = 9),
row_names_gp = gpar(fontsize = 7),
column_names_rot = 90,
column_names_gp = gpar(
fontsize = 8#,
# col = myPosColors
),
column_title = nameArg,
column_title_gp = gpar(fontsize = 22),
# right_annotation = haRowMIR200,
right_annotation = haRowMasterFUNCTION,
# top_annotation = haCol_MIR141,
heatmap_width = unit(9, "in"),
heatmap_height = unit(7, "in"),
# row_split = paste0(meta$groupBRCA),
# row_split = paste0(meta.tmp$Race),
# row_split = paste0(meta$ReproductiveStatus,'\n',meta$groupBRCA),
row_title_rot = 0
)
print(
myHM
)
return(
betaMatrix
)
}
```
```{r config}
config <- yaml::yaml.load_file("../Biscuit_Snakemake_Workflow/config/config.yaml")
config.multiscale = "../Biscuit_Snakemake_Workflow/multiscale_methylation_plot_pipeline//bin/config.yaml"
# config$ref$fasta
```
# METADATA
From Pilot C data
removed 3345 (BRCA2) due to low coverage
removed 3354 (WT) due to being an outlier in retention rates
Note that these are removed in the useMethData column of the metadata. They were also resequenced but no avail.
```{r load_meta}
brca.lvls <- c('NON-BRCA','BRCA1','BRCA2')
snk.meta.file="../Biscuit_Snakemake_Workflow/config/samples_Aug2023.tsv" # samples_Aug2023 has 111 samples with Pilots A (N=7, only for showing in multiqc that they were not converted), B, C, & D
# master.meta.file="../MasterCanaryClinData_20230823.xlsx"
master.meta.file="../MasterCanaryClinData_20230913.xlsx"
sheet = 'data'
snk.meta <- read.delim(snk.meta.file)
cat('Found',nrow(snk.meta),'samples in SNAKEMAKE meta file',snk.meta.file,'\n')
cat('Loading Master Meta Data:',master.meta.file,"\n")
cat('\tSheet:',sheet,"\n")
master.meta <- dplyr::filter(readxl::read_excel(path=master.meta.file,sheet=sheet),sequencedRNA==TRUE | useMethData==TRUE)
dim(master.meta)
table(master.meta$groupBRCA)
table(master.meta$Pilot)
table(master.meta$useMethData,master.meta$Pilot)
# do some math for # samples
# meta2 <- dplyr::filter(meta,useMethData==TRUE | sequencedRNA==TRUE)
# dim(meta2)
# table(master.meta$sequencedRNA,master.meta$useMethData)
# These are from 53 individual samples. 26 cases have both Methylation and RNA, 7 have only methylation, and 20 have only RNA.
# drop levels that were not sequenced
meta <- readxl::read_excel(path=master.meta.file,sheet=sheet)
meta$PredictedAges <- round(as.numeric(meta$PredictedAges),1)
meta <- dplyr::filter(meta,useMethData==TRUE | is.na(useMethData))
cat('Found',nrow(meta),"samples with useMethData==TRUE or blank\n")
cat('all samples are in SNAKEMAKE meta file:',all(meta$SVC %in% snk.meta$sample),'\n')
# Make some factors
raceLvls = c('Asian','Black','Hispanic Latino/White','East Indian','White','Other')
# Fix race issue
meta$Race <- ifelse(meta$Race=='white','White',meta$Race)
meta$Race <- ifelse(meta$Race=='black','Black',meta$Race)
setequal(raceLvls,unique(meta$Race)) # check that values are ok
meta$Race <- factor(meta$Race,levels=raceLvls)
unique(meta$ReproductiveStatus)
meta$ReproductiveStatus = factor(meta$ReproductiveStatus,levels=c('Pre','Post'))
# Get the age of the patients in years
# meta$age_in_years <- ifelse(
# meta$Pilot%in%c('B'),
# as.numeric( round(( as.Date(meta$`Date of Surgery`) - as.Date(meta$DoB) ) / 365 , 0) ),
# as.numeric(meta$`Age at time of surgery`)
# )
# summary(meta$age_in_years)
# Not working with pilot C
# meta$FlowcellNumber <- unlist(lapply(meta$fq1,function(x){
# stringr::str_count(x,",") + 1
# }))
# cat('Flowcells count distribution by sample\n')
# table(meta$FlowcellNumber)
# saveRDS(meta,'meta.Rds') # do this later after adding MIR200c
meta$sample <- meta$SVC
meta$groupBRCA = factor(meta$groupBRCA,
levels=c('NON-BRCA','BRCA1','BRCA2'))
## Note Aug 2023, this code is no longer needed because the meta was formalized with these values in it. Retaking the meta from box now.
# also change the Date of Surgery and LMP to dates
# meta$`Date of Surgery` <- as.Date(meta$`Date of Surgery`)
# change NAs
# meta$LMP <- as.Date(dplyr::na_if(meta$LMP,"NA"))
# meta$`LMP (days)` = ifelse(meta$ReproductiveStatus=='Post',NA,(meta$`Date of Surgery` - meta$LMP))
# check that all TRUE in table(meta$useMethData) exist as mergecg.bed.gz
table(
file.exists(
paste0('../Biscuit_Snakemake_Workflow/analysis/pileup/',dplyr::filter(meta,useMethData==TRUE)$SVC,'_mergecg.bed.gz')
)
)
# Make pregnancy annotation variable
meta$Pregnancy <- ifelse(is.na(meta$LMP_explanation),'Normal',meta$LMP_explanation)
meta$Pregnancy <- ifelse(meta$Pregnancy=='Pregnancy','Pregnant','Normal')
# table(meta$Pregnancy)
meta$DaysSinceLMP_use <- abs(meta$DaysSinceLMP)
meta$DaysSinceLMP_use <- ifelse(meta$DaysSinceLMP_use>50,NA,meta$DaysSinceLMP_use)
meta.rna <- dplyr::filter(master.meta,is.na(useRNAData) & sequencedRNA==TRUE)
dim(meta.rna)
```
# Sample Demographics
old one
```{r sample.demographics.plots,fig.height=5,fig.width=5}
meta$groupBRCA=factor(meta$groupBRCA,levels=c('NON-BRCA','BRCA1','BRCA2'))
master.meta$groupBRCA=factor(master.meta$groupBRCA,levels=c('NON-BRCA','BRCA1','BRCA2'))
meta.wgbs <- dplyr::filter(meta,useMethData==TRUE)
pal <- viridis::viridis(n=7)
meta.rna$ReproductiveStatus <- factor(meta.rna$ReproductiveStatus,levels=levels(meta.wgbs$ReproductiveStatus))
a <- ggplot(meta.rna,aes(x=groupBRCA)) +
geom_bar(aes(y=..count.., fill=`ReproductiveStatus`)) +
# geom_bar(aes(y=..count..),fill='grey32') +
# coord_flip() +
scale_fill_manual(values = c('#28BBECFF','#FB8022FF')) +
# facet_wrap(~groupBRCA) +
xlab('') +
bbc_style() +
labs(title="",
subtitle = paste0('KAPA RNA Hyperprep Kit (N=',nrow(meta.rna),')'),) +
theme(axis.text.x = element_text(angle=45,hjust=1))
b <- ggplot(meta.wgbs,aes(x=groupBRCA)) +
geom_bar(aes(y=..count.., fill=`ReproductiveStatus`)) +
# geom_bar(aes(y=..count..),fill='grey32') +
# coord_flip() +
scale_fill_manual(values = c('#28BBECFF','#FB8022FF')) +
# facet_wrap(~groupBRCA) +
xlab('') +
bbc_style() +
labs(title="",
subtitle = paste0('Swift Accel-NGS Methyl-Seq (N=',nrow(meta.wgbs),')'),) +
theme(axis.text.x = element_text(angle=45,hjust=1))
library(patchwork)
layout <- '
A
B
'
pdf(file='sample_demographics_RNA.pdf',height = 6,width = 6); a + ylim(c(0,60)); dev.off()
pdf(file='sample_demographics_Meth.pdf',height = 6,width = 6); b + ylim(c(0,60));dev.off()
# boxplot of groupBRCA ~ age
library(rstatix)
meta %>%
pairwise_wilcox_test(`Age at time of surgery` ~ groupBRCA)
.meta <- meta
.meta$PilotColor <- ifelse(.meta$Pilot=='B','grey12','grey72')
pdf(file='sample_demographics_groupBRCA_age.pdf',height = 6,width = 6)
ggplot(.meta,aes(x=groupBRCA,y=`Age at time of surgery`)) +
# geom_boxplot() +
geom_jitter(size = 5, alpha = 1, width = 0.1,aes(color=Pilot)) +
# geom_jitter(size = 5, alpha = 1, width = 0.1,color=.meta$RaceColor) +
geom_violin(aes(x=groupBRCA,y=`Age at time of surgery`),fill=NA,draw_quantiles = c(0.25, 0.5, 0.75)) +
bbc_style() +
ylab('Age') +
ylim(c(30,80)) +
ylab('Age at the time of FT collection') +
ggtitle('') +
theme(axis.text.x = element_text(angle=45,hjust=1),
legend.position='bottom')
dev.off()
pdf(file='sample_demographics_groupBRCA_race2.pdf',height = 5,width = 5)
ggplot(meta,aes(x=groupBRCA,fill=Race)) +
geom_bar(stat='count') +
# scale_fill_manual(values = c('grey32','grey52','grey82')) +
scale_fill_brewer(palette = 'Accent') +
bbc_style() +
xlab('') +
ylim(c(0,60)) +
ggtitle('') +
theme(axis.text.x = element_text(angle=45,hjust=1),legend.position = 'top')
dev.off()
# table(meta.wgbs$Pilot,meta.wgbs$groupBRCA)
# table(meta.rna$Pilot,meta.rna$groupBRCA)
.meta$LMP_explanation2 <- ifelse(is.na(.meta$LMP_explanation),as.character(.meta$ReproductiveStatus),.meta$LMP_explanation)
pdf(file='sample_demographics_groupBRCA_pregnancy.pdf',height = 5,width = 5)
ggplot(.meta,aes(x=groupBRCA,fill=LMP_explanation2)) +
geom_bar(stat='count') +
# scale_fill_manual(values = c('grey32','grey52','grey82')) +
scale_fill_brewer(palette = 'Set1') +
bbc_style() +
xlab('') +
ylim(c(0,60)) +
ggtitle('') +
theme(axis.text.x = element_text(angle=45,hjust=1),legend.position = 'top')
dev.off()
```
new one using Table S1
```{r sample.demographics.plots,fig.height=5,fig.width=5}
require(bbplot)
require(tidyverse)
m0 <- readxl::read_excel('~/Dropbox/Ian,\ Svetlana,\ Hui/canary/Tables1-3.xlsx',sheet='Table S1 Clinical Data')
dim(m0)
m0$groupBRCA=factor(m0$groupBRCA,levels=c('NON-BRCA','BRCA1','BRCA2'))
m0$ReproductiveStatus <- factor(m0$ReproductiveStatus,levels=c('Pre','Post'))
# Filter that an assay was done:
m1 <- dplyr::filter(m0,useMethylation==TRUE | useProteomics==TRUE | useRNA_2==TRUE)
dim(m1)
table(m1$useMethylation,m1$useProteomics,m1$useRNA_2)
table(m1$groupBRCA)
ggplot(m1,aes(x=groupBRCA)) +
geom_bar(aes(y=..count.., fill=`ReproductiveStatus`)) +
# geom_bar(aes(y=..count..),fill='grey32') +
# coord_flip() +
scale_fill_manual(values = c('#28BBECFF','#FB8022FF')) +
# facet_wrap(~groupBRCA) +
xlab('') +
bbc_style() +
labs(title="",
subtitle = paste0('N=',nrow(m1))) +
theme(axis.text.x = element_text(angle=45,hjust=1))
# same thing with race
m1$Race <- factor(m1$Race,levels=c('Asian','Black','East Indian','Hispanic Latino/White','White','Other'))
library(ggpattern)
ggplot(data = df, aes(x = Class, fill = StudyTime, pattern = Nerd)) +
geom_bar_pattern(position = position_dodge(preserve = "single"),
color = "black",
pattern_fill = "black",
pattern_angle = 45,
pattern_density = 0.1,
pattern_spacing = 0.025,
pattern_key_scale_factor = 0.6) +
scale_fill_manual(values = colorRampPalette(c("#0066CC","#FFFFFF","#FF8C00"))(4)) +
scale_pattern_manual(values = c(Nerd = "stripe", NotNerd = "none")) +
labs(x = "Class", y = "Number of Students", pattern = "Nerd?") +
guides(pattern = guide_legend(override.aes = list(fill = "white")),
fill = guide_legend(override.aes = list(pattern = "none")))
pX <- ggplot(m1,aes(x=groupBRCA,fill=Race,pattern=Postpartum)) +
ggpattern::geom_bar_pattern(
color = "black",
pattern_fill = "black",
pattern_angle = 45,
pattern_density = 0.1,
pattern_spacing = 0.025,
pattern_key_scale_factor = 0.6) +
# geom_bar(aes(y=..count..),fill='grey32') +
# coord_flip() +
scale_fill_manual(values = c("#30123BFF","#28BBECFF","#A2FC3CFF","#FB8022FF","#7A0403FF","grey44")) +
scale_pattern_manual(values = c('TRUE' = "stripe", 'FALSE' = "none")) +
# Race = c(
# 'Asian' = "#30123BFF",
# 'Black' = "#28BBECFF",
# 'East Indian' = "#A2FC3CFF",
# 'Hispanic Latino/White' = "#FB8022FF",
# 'White' = "#7A0403FF"
# )
xlab('') +
bbc_style() +
labs(title="",
subtitle = paste0('N=',nrow(m1))) +
theme(axis.text.x = element_text(angle=45,hjust=1)) +
guides(pattern = guide_legend(override.aes = list(fill = "white")),
fill = guide_legend(override.aes = list(pattern = "none")))
pX
pdf(file='sample_demographics_Race.pdf',height = 6,width = 6);pX; dev.off()
```
# Heatmap anno row master
```{r ComplexHeatmapAnnotations}
heatmapColorPal <- colorRampPalette(c('blue','yellow'))(20)
pal = c(
viridis::viridis(n=4),
viridis::rocket(n=5)[2:4],
viridis::turbo(n=5)[c(2,4)]
)
# pal2 = viridis::mako(n=5)
pal2 = viridis::turbo(n=5)
metaOO <- dplyr::arrange(meta,`Age at time of surgery`)
haRowMaster <- rowAnnotation(
Batch = metaOO$Pilot,
`Reproductive Status` = metaOO$ReproductiveStatus,
`Race` = metaOO$Race,
`Age` = metaOO$`Age at time of surgery`,
`Pregnancy` = metaOO$Pregnancy,
`Days since LMP` = metaOO$DaysSinceLMP_use,
`BRCA status` = metaOO$groupBRCA,
col = list(
`Block Age (Years)` = circlize::colorRamp2(
breaks = seq(from = 0, to = 11, length = 20),
colors = colorRampPalette(c("yellow", "blue"))(20)
),
`Days since LMP` = circlize::colorRamp2(
breaks = seq(from = 0, to = 50, length = 20),
colors = colorRampPalette(c("gray100", "gray10"))(20)
),
`Age` = circlize::colorRamp2(
breaks = seq(from = 20, to = 72, length = 20),
colors = colorRampPalette(c("gray75", "gray10"))(20)
),
`Pregnancy` = c(
'Pregnant' = 'pink',
'Normal' = 'gray22'
),
Batch = c(
'A' = pal[1],
'B' = pal[2],
'C' = pal[3],
'D' = pal[4]
),
`Reproductive Status` = c(
'Pre' = pal[8],
'Post' = pal[9]
),
`BRCA status` = c(
'BRCA1' = '#40498e',
'BRCA2' = '#38aaac',
'NON-BRCA' = 'black'
),
Race = c(
'Asian' = pal2[1],
'Black' = pal2[2],
'East Indian' = pal2[3],
'Hispanic Latino/White' = pal2[4],
'White' = pal2[5],
'Other' = 'gray48'
)
)
)
```
# MultiQC plots remade
```{r boxplot.biscuit-mapping-overview-plot,fig.height=5,fig.width=7}
# get the raw reads
# rawReads <- NULL
# namesReads <- NULL
# for(s in meta$SVC){
# fi <- paste0('../Biscuit_Snakemake_Workflow/analysis/rawReads/',s,'.txt')
# if(file.exists(fi)){
# x <- read.delim(fi,header=FALSE,check.names = FALSE)
# rawReads <- c(rawReads,x$V1)
# namesReads <- c(namesReads,s)
# }
# }
# rawReads <- rawReads / 2
#
# tmp <- data.frame(
# SVC=namesReads,
# rawReadsMethylation=rawReads
# ) %>% dplyr::left_join(meta)
data <- read.delim('samtools-flagstat-dp.tsv',sep="\t")
# if(! 'Optimally.Aligned.Reads' %in% colnames(meta)){
tmp <- dplyr::left_join(meta,data,by=c('SVC'='Sample'))
dim(tmp)
tmp$groupBRCA = factor(tmp$groupBRCA,levels=levels(meta$groupBRCA))
a <- ggplot(tmp,aes(x=groupBRCA,y=Mapped,group=groupBRCA,color=ReproductiveStatus)) +
geom_violin(fill=NA,draw_quantiles = c(0.25, 0.5, 0.75)) +
geom_jitter(size = 2, alpha = 1, width = 0.1) + theme_bw() +
scale_color_manual(values=c("#28BBECFF","#FB8022FF")) +
theme(legend.position='none') +
# theme(axis.text = element_text(size=34),
# axis.title = element_text(size=36)) +
ylab('Million Reads Mapped') + xlab('') + ylim(c(0,1000))
a
pdf(file='MillionsReadMapped_dotplot.pdf',height = 3,width = 3); a; dev.off()
# shows no correlation
ggplot(tmp,aes(x=`Age at time of surgery`,y=Mapped,group=groupBRCA)) + geom_point() + theme_bw() + scale_color_viridis_c() #+ theme(legend.position='none')
# make a matched figure for total counts of RNA data
# add in the raw counts
raw_counts <- readRDS('raw_counts_N104.Rds')
x <- data.frame(colSums(raw_counts[,3:ncol(raw_counts)],na.rm=TRUE))
x$SVC <- rownames(x)
colnames(x)[1] <- 'total_reads_RNA'
tmp <- dplyr::left_join(meta,x)
b <- ggplot(tmp,aes(x=groupBRCA,y=total_reads_RNA,group=groupBRCA,color=Race)) +
geom_violin(fill=NA,draw_quantiles = c(0.25, 0.5, 0.75)) +
geom_jitter(size = 2, alpha = 1, width = 0.1) + theme_bw() +
# scale_color_manual(values=c("#28BBECFF","#FB8022FF")) +
theme(legend.position='none') +
# theme(axis.text = element_text(size=34),
# axis.title = element_text(size=36)) +
ylab('Gene Counts') + xlab('') + ylim(c(0,3e7))
b
pdf(file='GeneCounts_dotplot.pdf',height = 3,width = 3); b; dev.off()
```
## Biscuit Retention Barplot
Looked at the isize distribution in multiQC with no differences amongst samples
```{r boxplot.biscuit_retention,fig.height=5,fig.width=9}
data <- read.delim('biscuit_retention.tsv',sep="\t")
data <- dplyr::left_join(meta,data,by=c('SVC'='Category'))
d <- dplyr::select(data,matches('Retention'),one_of(c('groupBRCA','SVC')))
d2 <- pivot_longer(d,cols=matches('Retention'),names_to = 'Base',values_to = 'Retention')
ggplot(d2,aes(x=SVC,y=Retention,fill=Base)) + geom_bar(stat='identity',position = 'dodge') + bbplot::bbc_style() + scale_fill_viridis_d(option='turbo') + theme(axis.text.x = element_blank()) + ylim(c(0,100))
d3 <- dplyr::left_join(d2,meta,by='SVC')
pdf('Retention_boxplot.pdf',height = 3,width = 6)
ggplot(d3,aes(x=groupBRCA.x,y=Retention,color=Base)) +
geom_boxplot() + theme_bw() + scale_color_viridis_d(option='mako') +
theme(axis.text.x = element_text(angle=45,hjust=1)) +
xlab('')
dev.off()
d3$Base <- gsub('.Retention','',d3$Base)
pdf('Retention_boxplot2.pdf',height = 5,width = 2)
ggplot(d3,aes(x=Base,y=Retention)) +
geom_boxplot() + theme_bw() + scale_color_viridis_d(option='mako') +
theme(axis.text.x = element_text(angle=45,hjust=1)) +
xlab('')
dev.off()
# get average of different retentions
dplyr::filter(d3,Base!='CpG.Retention') %>% summarise(mean=mean(Retention))
dplyr::filter(d3,Base=='CpG.Retention') %>% summarise(mean=mean(Retention))
```
```{r boxplot.biscuit_strands,fig.height=7,fig.width=7}
data <- read.delim('biscuit_strands.tsv',sep="\t",check.names = FALSE)
data <- dplyr::filter(data,Category%in%dplyr::filter(meta2,Pilot!='A')$SVC)
# meta <- dplyr::left_join(meta,data,by=c('SVC'='Category'))
# d <- dplyr::select(meta,matches('Retention'),one_of(c('groupBRCA','SVC')))
d2 <- pivot_longer(data,cols=matches('Conversion'),names_to = 'Mapping',values_to = 'Reads')
# pdf('mappingStrand.pdf',width = 7,height = 7)
ggplot(d2,aes(x=Category,y=Reads,fill=Mapping)) + geom_bar(stat='identity',position = 'stack') + bbplot::bbc_style() + scale_fill_viridis_d(option='viridis') + theme(axis.text.y = element_blank()) + coord_flip()#+ ylim(c(0,100))
# dev.off()
```
```{r boxplot.biscuit_seq_depth,fig.height=7,fig.width=12,eval=FALSE}
# data <- read.delim('biscuit_seq_depth.tsv',sep="\t",check.names = FALSE)
# data <- dplyr::filter(data,Sample%in%dplyr::filter(meta2,Pilot!='A')$SVC)
```
# Age by patient BRCA status dotplot
```{r }
p002 <- ggplot(dplyr::filter(master.meta,Pilot!='A'),aes(x=groupBRCA,y=`Age at time of surgery`)) +
# geom_boxplot() +
geom_violin(fill=NA,draw_quantiles = c(0.25, 0.5, 0.75)) +
geom_jitter(size = 1, alpha = 1, width = 0.1) +
theme_minimal() +
xlab('Patient germline status') + ggtitle('') + ylim(c(19,80))
p002
pdf(file='Age_by_BRCAgroup.pdf',height = 3,width = 3);p002;dev.off()
rstatix::anova_test(dplyr::filter(master.meta,Pilot!='A'),formula = `Age at time of surgery` ~ groupBRCA)
rstatix::pairwise_wilcox_test(dplyr::filter(master.meta,Pilot!='A'),formula = `Age at time of surgery` ~ groupBRCA)
```
# MIR200chg
```{r load_epic_manifest_get_mir_probes,eval=TRUE}
manifest.df <- read.table('EPIC.hg38.manifest.gencode.v36.tsv',sep="\t",header=TRUE)
# manifest <- sesameData::sesameDataGet("EPIC.hg38.manifest")
# class(manifest)
# manifest.df <- data.frame(manifest)
rownames(manifest.df) <- manifest.df$probeID
mir200c.probes <- c(
'cg24702147',
'cg00366413',
'cg27534624',
'cg22413603', # this does not exist !!
'cg18959988',
'cg23067082',
'cg19794481',
'cg18185189',
'cg12161331',
'cg02624246'
)
mir200c.probes.pos <- manifest.df[mir200c.probes,1:3]
# mir200.start <- min(c(mir200c.probes.pos$end,mir200c.probes.pos$start),na.rm=TRUE)
# mir200.end <- max(c(mir200c.probes.pos$end,mir200c.probes.pos$start),na.rm=TRUE)
mir200.start <- min(c(mir200c.probes.pos$CpG_beg,mir200c.probes.pos$CpG_end),na.rm=TRUE);mir200.start
mir200.end <- max(c(mir200c.probes.pos$CpG_beg,mir200c.probes.pos$CpG_end),na.rm=TRUE);mir200.end
```
```{r readBiscuit}
bs_list <- generate_or_load_bsseq_list(
path='../Biscuit_Snakemake_Workflow/analysis/pileup/',
vcf_header_path = '../Biscuit_Snakemake_Workflow/analysis/pileup/',
name='MIR200',
sampNames=meta$SVC,
readBiscuitMergedFlag=TRUE,
whichFlag = GRanges(
seqnames='chr12',
ranges=IRanges(mir200.start, width=(mir200.end-mir200.start)),
strand='*'
)
)
names(bs_list) <- meta$SVC
# names(bs_list) <- gsub('_mergecg.bed.gz','',list.files('Biscuit_Snakemake_Workflow/analysis/pileup/',pattern = '_mergecg.bed.gz$')) # these are the same but one is easier...
# tictoc::tic("Unionize")
# myBS <- bs_list[[1]]
# table(unlist(lapply(bs_list,FUN=length)))
# for (i in (2:length(bs_list))){
# myBS <- biscuiteer::unionize(myBS,bs_list[[i]])
# }
# tictoc::toc()
# saveRDS(myBS,'MIR200_myBS.Rds')
# myBS <- readRDS('MIR200_myBS.Rds')
# myBS <- bs_list[[1]]
# for (i in (2:length(bs_list))){
# myBS <- bsseq::combine(myBS,bs_list[[i]])
# }
```
```{r getBetaMatrixFrom_BS_LIST}
betaMatrix.tidy <- do.call('rbind',
lapply(
seq_along(bs_list), FUN = function(
x,n,i
){
# print(paste(x[i],n[i],i))
cbind(
data.frame(rowRanges(x[[i]])),
beta = as.numeric(round(x[[i]]@assays@data$M / x[[i]]@assays@data$Cov, 2)),
depth = as.numeric(x[[i]]@assays@data$Cov),
sample = rep(n[[i]],nrow(x[[i]]))
)
},
x=bs_list,
n=names(bs_list)
)
)
betaMatrix.tidy$pos <- paste0(betaMatrix.tidy$seqnames,':',betaMatrix.tidy$start)
## Factor samples
betaMatrix.tidy$sample = factor(betaMatrix.tidy$sample,levels=meta$SVC)
### FILTER TO SET OF PROBES
# dim(betaMatrix.tidy)
# betaMatrix.tidy <- dplyr::filter(betaMatrix.tidy,pos %in% paste(mir200c.probes.pos$seqnames,mir200c.probes.pos$start,sep=":"))
dim(betaMatrix.tidy)
## GET THE BETA MATRIX
betaMatrix <- betaMatrix.tidy %>%
dplyr::select(one_of(c('sample','beta','pos'))) %>%
tidyr::pivot_wider(values_from = beta,names_from = sample)
dim(betaMatrix)
betaMatrix <- dplyr::arrange(betaMatrix,pos)
.rownames <- betaMatrix$pos
betaMatrix <- dplyr::select(betaMatrix,-pos)
dim(betaMatrix)
rownames(betaMatrix) <- .rownames
## GET THE DEPTH MATRIX
depthMatrix <- betaMatrix.tidy %>%
dplyr::select(one_of(c('sample','depth','pos'))) %>%
tidyr::pivot_wider(values_from = depth,names_from = sample)
dim(depthMatrix)
depthMatrix <- dplyr::arrange(depthMatrix,pos)
.rownames <- depthMatrix$pos
depthMatrix <- dplyr::select(depthMatrix,-pos)
dim(depthMatrix)
rownames(depthMatrix) <- .rownames
## filter betaMatrix if needed
# mir200.index4mat <- which(rownames(betaMatrix) %in% paste(mir200c.probes.pos$seqnames,mir200c.probes.pos$start,sep=":"))
# betaMatrix <- betaMatrix[mir200.index4mat,]
# rownames(betaMatrix) <- .rownames[mir200.index4mat]
# dim(betaMatrix)
```
## Heatmap
```{r heatmapMIR200cgh,fig.height=7.5,fig.width=9.5,dev=c('png','pdf'),eval=TRUE}
# get the depth
avgDepth <- (betaMatrix.tidy %>% dplyr::group_by(sample) %>% dplyr::summarise(avgDepth = mean(depth)))$avgDepth
avgDepthSamples <- (betaMatrix.tidy %>% dplyr::group_by(sample) %>% dplyr::summarise(avgDepth = mean(depth)))$sample
# triple check ordering!
stopifnot(all(avgDepthSamples==colnames(betaMatrix)) && all(avgDepthSamples==colnames(betaMatrix)))
pal = c(
viridis::viridis(n=3),
viridis::turbo(n=5)[c(2,4)]
)
myPosColors <- rep('black',nrow(betaMatrix))
mir200c.pos.index <- which(rownames(betaMatrix) %in% paste(mir200c.probes.pos$CpG_chrm,mir200c.probes.pos$CpG_beg+1,sep=":")); mir200c.pos.index
myPosColors[
mir200c.pos.index
] <- 'red'
### Make the annotation
# haCol <- HeatmapAnnotation(
haRow <- rowAnnotation(
# `Mean\nBeta` = anno_barplot(colMeans(betaMatrix[mir200c.pos.index,],na.rm = TRUE), width = unit(0.5, "in"),ylim=c(0,1)),
# `Mean\nDepth` = anno_barplot(avgDepth, width = unit(0.5, "in"))
# > viridis::rocket(n=9)
# [1] "#03051AFF" "#30173AFF" "#611F53FF" "#961C5BFF" "#CB1B4FFF"
# [6] "#EC4B3EFF" "#F4875EFF" "#F6BB97FF" "#FAEBDDFF"
# just the mir200 probes
`Mean\nBeta` = anno_barplot(colMeans(betaMatrix,na.rm = TRUE), width = unit(0.5, "in"),ylim=c(0,1),border=FALSE,gp = gpar(fill='gray12')),
`Mean\nDepth` = anno_barplot(avgDepth,gp = gpar(fill='gray45'), width = unit(0.5, "in"),border=FALSE)
)
# Get sample depths
avgDepth <- round((betaMatrix.tidy %>% dplyr::group_by(sample) %>% dplyr::summarise(avgDepth = mean(depth,na.rm=TRUE)))$avgDepth,2)
avgBeta <- round((betaMatrix.tidy %>% dplyr::group_by(sample) %>% dplyr::summarise(avgBeta = mean(beta,na.rm=TRUE)))$avgBeta,2)
# check that positions depth names match matrix rownames
stopifnot(all(rownames(betaMatrix)==avgDepthPosPositions))
# stopifnot(all(colnames(betaMatrix)==meta$SVC))
haRow_MIR141 <- rowAnnotation(
`Mean\nDepth` = anno_barplot(avgDepth, width = unit(0.5, "in")),
`Mean\nBeta` = anno_barplot(avgBeta, width = unit(0.5, "in"),ylim=c(0,1))
)
## Make the heatmap
# .meta <- dplyr::filter(meta,SVC%in%colnames(betaMatrix))
hm.mir200 <- ComplexHeatmap::Heatmap(
t(betaMatrix),
show_column_names = TRUE,
show_row_names = FALSE,
col=viridis::cividis(20),
cluster_rows = TRUE,
cluster_columns = FALSE,
heatmap_legend_param = list(title='Beta'),
row_title_gp = gpar(fontsize = 9),
row_names_gp = gpar(fontsize = 5),
column_names_rot = 90,
column_names_gp = gpar(
fontsize = 8#,
# col = myPosColors
),
column_title = "MIR200cgh CpG Methylation",
column_title_gp = gpar(fontsize = 22),
# right_annotation = haRowMaster,
# right_annotation = haRow_MIR141,
right_annotation = c(haRowMaster,haRow_MIR141),
heatmap_width = unit(6, "in"),
heatmap_height = unit(5, "in"),
# row_split = paste0(meta$ReproductiveStatus,'\n',meta$groupBRCA),
# row_split = paste0(meta$groupBRCA),
row_title_rot = 0
)
pdf('hm.mir200.pdf',width=10,height=7)
print(hm.mir200)
dev.off()
# colnames(betaMatrix)
# paste(rownames(betaMatrix)[1])
# plotEpiread(
# epibed.gr.tabulated.list[[1]],
# show_readnames = FALSE,
# plot_read_ave = FALSE
# ) + ggtitle('test')
```
use the chunk above this one!
```{r heatmapMIR200cgh_wDensity,fig.height=7.5,fig.width=9.5,dev=c('png','pdf'),eval=FALSE}
pal = c(
viridis::viridis(n=3),
viridis::turbo(n=5)[c(2,4)]