-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09-ASXL1_Tcell_and_Rescue.Rmd
1618 lines (1408 loc) · 63.7 KB
/
09-ASXL1_Tcell_and_Rescue.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: "09-ASXL1_Tcell_and_Rescue"
author: "Maggie Fu"
date: '2023-05-19'
output: html_document
---
```{r setup, include=FALSE}
# Work directory
setwd("/mnt/scratch/KoborLab/Personal_Folders/mfu/Projects/ASXL1/")
# .libPaths(c("/mnt/koborlab-hpc/tools/R/library/4",
# "/usr/local/lib/R/site-library",
# "/usr/lib/R/site-library", "/usr/lib/R/library"))
# Packages
## For loading DNAm data
library(minfi)
library(data.table)
library(IlluminaHumanMethylationEPICv2manifest,lib.loc = "/mnt/scratch/KoborLab/R_Libs/4.2.2")
# BiocManager::install("jokergoo/IlluminaHumanMethylationEPICv2anno.20a1.hg38")
library(IlluminaHumanMethylationEPICv2anno.20a1.hg38)
# library(methylumi)
# library(ewastools, lib.loc = "/mnt/scratch/KoborLab/R_Libs/4.2.2") # (supports EPIC_v2)
## Preprocessing
library(wateRmelon)
## Basic data manipulation / plotting
library(dplyr)
library(ggplot2)
library(ggvenn)
## Cell type prediction
library(FlowSorted.Blood.EPIC)
library(ExperimentHub)
library(pheatmap)
library(eulerr)
## DNAm age
library(methylclock)
## Parallel processing
library(pbapply)
## Enrichment analysis
library(msigdbr)
library(clusterProfiler)
library(org.Hs.eg.db)
library(fgsea)
library(R.utils)
library(missMethyl)
## Color palette
library(cartography)
library(nord)
# Define colors for plotting
group.colors <- c("family control" = "#EBCB8BFF", "unrelated healthy control" = "#A3BE8CFF", "patient empty vector" ="#BF616AFF", "patient wild type" = "#B48EADFF")
# Internal functions
source("/mnt/scratch/KoborLab/Personal_Folders/mfu/Functions/DetPvalTestRG.R")
source("/mnt/scratch/KoborLab/Personal_Folders/mfu/Functions/locfdr_LMM.R")
source("/mnt/scratch/KoborLab/Personal_Folders/mfu/Functions/SexAgePrediction_RG.R")
source("/mnt/scratch/KoborLab/Personal_Folders/mfu/Functions/BetaPlot.R")
```
## Preprocessing
Try to keep the preprocessing steps similar to the whole blood analysis
- Sample / probe QC
- Funnorm
-
#### Reading IDATs
```{bash}
cd /mnt/cifs/maggie.fu/fs/KoborLab/raw_data/BRAINSTORM-KoborArchive2014March/RAW Data - DNA methylation/RAW data - EPIC methylation/2023/Turvey_May2023
scp -r * /mnt/scratch/KoborLab/Personal_Folders/mfu/Projects/ASXL1/raw/
cd /mnt/scratch/KoborLab/Personal_Folders/mfu/Projects/ASXL1/raw/207057130152/
mv *.idat ../
rm -r 207057130152
```
```{r}
rawDir <- "raw"
targets <- read.metharray.sheet(rawDir)
RGset <- read.metharray.exp(base = rawDir, targets = targets, extended = T, recursive = T)
pheno <- pData(RGset)
# reassign the annotation so that the minfi functions getBeta(), preprocessRaw() and others like preprocessNoob() will work
annotation(RGset)["array"] <- "IlluminaHumanMethylationEPICv2"
annotation(RGset)["annotation"] <- "20a1.hg38"
(manifest <- getManifest(RGset))
saveRDS(RGset, file = "RData/901-ASXL1_Tcell_RGset.rds")
```
### Normalization
```{r}
RGset <- readRDS("RData/901-ASXL1_Tcell_RGset.rds")
anno <- readRDS("/mnt/scratch/KoborLab/Personal_Folders/mfu/Reference/EPICv2_fdat.rds")
GRset <- preprocessFunnorm(RGset)
```
### Sample QC
```{r}
# EWAStools
ewas_meth <- read_idats(pData(RGset)$Basename)
ctrls <- control_metrics(ewas_meth)
pData(GRset)$failed <- sample_failure(ctrls)
table(pData(GRset)$failed)
# minfi
minfi_controlqc <- getQC(preprocessRaw(RGset))
controlqc <- plotQC(minfi_controlqc)
# Other checks
out1 <- DetPBisCTest(RGset)
out2 <- detectOutlier(as.matrix(getBeta(GRset))) %>% which(.) # Take too long to run
out3 <- outlyx(RGset)
out4 <- locfdr_LMM(getBeta(GRset), pData(GRset))
# No outliers! All samples' quality is good
```
### Probe QC
```{r}
detP <- minfi::detectionP(as(RGset, "RGChannelSet"))
bc <- beadcount(RGset)
RGset <- pfilter(RGset, pn = detP, bc = bc, pnthresh = 0.001)
# 0 samples having 1 % of sites with a detection p-value greater than 0.001 were removed
# Samples removed:
# 8659 sites were removed as beadcount <3 in 5 % of samples
# 3535 sites having 1 % of samples with a detection p-value greater than 0.001 were removed
GRset <- preprocessFunnorm(RGset$mn)
```
### Remove duplicated probes???
Weird duplicated probe names _TC / _BC - remove duplicated ones
```{r}
bt <- getBeta(GRset)
probes <- gsub("_.*", "", rownames(bt)) %>% unique()
bt_dup <- bt[duplicated(gsub("_.*", "", rownames(bt))), ] # remove these
dim(bt_dup)
bt_dup2 <- bt[!duplicated(gsub("_.*", "", rownames(bt))), ] # keep these
dim(bt_dup2)
GRset <- GRset[rownames(bt_dup2), ]
rownames(GRset) <- gsub("_.*", "", rownames(GRset))
dim(GRset) #923736 8
dim(anno) #infinium-methylationepic-v-1-0-b5-manifest-file 52
intersect(rownames(GRset), anno$IlmnID) %>% length() #721378 - why is the overlap so low???
overlap <- intersect(rownames(GRset), anno$IlmnID)
GRset <- GRset[overlap, ]
rownames(anno) <- anno$IlmnID
anno <- anno[overlap, ]
```
```{r}
beta <- getBeta(GRset)
meta <- pData(GRset)
# Relabel things
meta$Sample_Group <- gsub("sister|mom|Dad", "family control", meta$Sample_Group) %>%
gsub("HC.*", "unrelated healthy control", .) %>%
gsub("P_WT.*", "patient wild type", .) %>%
gsub("P_EU", "patient empty vector", .)
meta$Sample_Name <- gsub("EU", "EV", meta$Sample_Name) %>%
gsub("sister", "Sister", .) %>%
gsub("mom", "Mom", .)
meta$Sentrix_row <- gsub("C.*", "", meta$Array) %>% gsub("R", "", .) %>% as.integer()
colnames(beta) <- meta$Sample_Name
rownames(meta) <- meta$Sample_Name
save(beta, meta, anno, file = "RData/902-ASXL1_Tcell_betas_norm.RData")
```
## Data exploration - cell type, DNAm age, sex, etc
### Check sex
```{r}
BetaPlot <- function(bt, mt, var){
if(nrow(bt) > 20000){
n <- 20000
} else {
n <- nrow(bt)
}
bt.m <- reshape2::melt(bt[sample(1:nrow(bt),n),])
#remove NAs before plotting (otherwise get many non-inifnite warnings)
plt <- bt.m[which(!(is.na(bt.m$value))),]
# Add meta
colnames(plt) <- c("CpG","ID","Beta")
plt <- merge(plt, mt, by.x = "ID", by.y = 0) %>%
as.data.frame()
ggplot(plt, aes(Beta, group = ID, color = get(var))) +
geom_density() +
theme_bw() +
labs(x = "DNAm Beta Value")
}
BetaPlot(beta[anno$CHR == "X", ], "predictedSex")
BetaPlot(beta[anno$CHR == "Y", ], "predictedSex")
# Mom and Dad got switched
meta$Sample_Name[rownames(meta) == "Mom"] <- "Dad"
meta$Sample_Name[rownames(meta) == "Dad"] <- "Mom"
rownames(meta)[meta$Sample_Name == "Mom"] <- "Mom2"
rownames(meta)[meta$Sample_Name == "Dad"] <- "Dad"
rownames(meta)[meta$Sample_Name == "Mom"] <- "Mom" # id column keeps the original (wrong) labeling
```
### Check SNPs
```{r}
snps <- getSnpBeta(RGset)
colnames(snps) <- meta$Sample_Group
D <- dist(t(snps)) #snp probes
hc <- hclust(D, method = "ward.D2")
ggdendrogram(hc, rotate = TRUE)
```
### EstimateCellCounts2
```{r}
load("RData/902-ASXL1_Tcell_betas_norm.RData")
dataset <- beta
# ECC2 doesn't work - need to run homebrew MRP
source("../../Functions/MRP_accessory.R")
source("../../Functions/pickCompProbesCaret.R")
if (verbose)
cat("Loading Reference Dataset.\n")
load("/mnt/scratch/KoborLab/Personal_Folders/mfu/Projects/MRP/reference/FlowSorted.BloodExtended.EPIC_FN.RData")
sampType = rep("PB", ncol(dataset)) # c("PB", "CB")
class = "betas" # c("rgset", "betas")
norm = "QN.b" # c("Noob", "FN", "QN", "QN.b", "none")
normComb = TRUE
probeList = "Ttest" #c("Ttest", "Caret", "IDOL", "DHS")
method = "CP" #c("CP", "RPC", "SVR")
probeSelect = "both" #c("both", "any", "pval")
conditions = NULL
nProbes = 100
verbose = TRUE
plotRef = FALSE
removenRBC = T
EPIConly = F
seed = 3
reference = FlowSorted.BloodExtended.EPIC.FN # c(FlowSorted.CordBlood.450k.FN, FlowSorted.Blood.450k.FN, FlowSorted.Blood.EPIC.FN, FlowSorted.BloodExtended.EPIC.FN)
cellTypes = c("Bas", "Bmem", "Bnv", "CD4mem", "CD4nv",
"CD8mem", "CD8nv", "Eos", "Mono", "Neu", "NK", "Treg")
caretMods = c("EL", "BLR", "CART", "RF", "GBM", "RFEnNB", "RFEnSVM") # c("EL", "BLR", "CART", "RF", "GBM", "RFEnLDA", "RFEnRF", "RFEnNB", "RFEnSVM", "RFEnNN")
require(dplyr)
require(limma)
require(genefilter)
#require(FlowSorted.Blood.450k)
require(FlowSorted.Blood.EPIC)
#require(FlowSorted.CordBloodCombined.450k)
require(IlluminaHumanMethylation450kmanifest)
require(IlluminaHumanMethylationEPICmanifest)
#require(ExperimentHub)
#require(EpiDISH)
#hub <- ExperimentHub()
library(SIS)
```
#### Combine data / normalize
```{r}
if (verbose)
cat("Starting Cell Type Estimation.\n")
# if (removenRBC == T) {
# cellTypes <- c("CD8T", "CD4T", "NK", "Bcell", "Mono", "Gran")
# } else {
# cellTypes <- c("CD8T", "CD4T", "NK", "Bcell", "Mono", "Gran", "nRBC")
# }
if (norm == "FN") {
processMethod <- "preprocessFunnorm"
if (class == "betas") stop("A RGChannelSet is required for functional normalization")
} else if (norm == "Noob") {
processMethod <- "preprocessNoob"
if (class == "betas") stop("A RGChannelSet or is required for Noob normalization")
} else if (norm == "QN") {
processMethod <- "preprocessQuantile"
if (class == "betas") stop("A RGChannelSet is required for this quantile normalization method. If you only have betas, set normalization method to QN.b instead")
} else if (norm == "QN.b") {
processMethod <- "normalizeQuantiles"
if (class == "rgset") stop("QN.b is exclusively for beta matrix input. Use QN instead if you have an RGChannelSet")
}
sampCT <- rep("WBC", ncol(dataset))
if (norm != "none") {
processMethod <- get(processMethod)
}
### Data normalization
if (verbose)
cat("Combining Data with Flow Sorted Data and Normalizing.\n")
if (class == "betas") {
# if (all(sampType %in% "CB")) {
# ref <- betas(reference[pData(reference)$SampType == "CB", ])
# } else {
# ref <- betas(reference)
# }
if (class(reference) == "MethyLumiSet"){
ref <- betas(reference)
} else if (class(reference) %in% c("RGChannelSetExtended", "RGChannelSet", "GenomicRatioSet")){
ref <- getBeta(reference)
}
commonprobe <- intersect(as.character(rownames(dataset)), as.character(rownames(ref)))
if (norm == "QN.b") {
comb <- cbind(dataset[commonprobe, ], ref[commonprobe, ])
comb.n <- processMethod(comb)
samp.n <- comb.n[, colnames(dataset)]
ref.n <- comb.n[, colnames(ref)]
} else if (norm == "none") {
samp.n <- dataset[commonprobe, ]
ref.n <- ref[commonprobe, ]
}
} else {
dataset <- as(dataset, "RGChannelSet")
if (norm == "none") {
commonprobe <- intersect(as.character(rownames(dataset)), as.character(rownames(BloodCell)))
samp.n <- betas(BloodCell)[commonprobe, ]
ref.n <- getBeta(dataset)[commonprobe, ]
} else if (normComb) { # Combine all the datasets and normalize
combRGset <- combineArrays(dataset, reference, outType = "IlluminaHumanMethylation450k")
combRGset.N <- processMethod(combRGset)
comb.n <- getBeta(combRGset.N)
samp.n <- comb.n[, colnames(dataset)]
ref.n <- comb.n[, colnames(reference)]
}
}
combMeta <- data.frame(sampleNames = c(colnames(samp.n), colnames(ref.n)),
studyIndex = rep(c("user", "reference"), times = c(ncol(samp.n), ncol(ref.n))),
sampleType = c(sampType, as.character(pData(reference)$SampType)),
cellType = c(sampCT, as.character(pData(reference)$CellType)),
stringsAsFactors = FALSE)
refMeta <- combMeta[combMeta$studyIndex == "reference", ]
sampMeta <- combMeta[combMeta$studyIndex == "user", ]
# save(ref.n, samp.n, combMeta, file = "MRPref_CHILD_FN_0.RData")
# save(ref.n, samp.n, combMeta, file = "MRPref_CHILD_FN_1.RData")
# save(ref.n, samp.n, combMeta, file = "MRPref_CHILD_FN_5.RData")
```
#### Pick probes
```{r}
### Pick probes and estimate weights
if (verbose)
cat("Estimating Weights for Cell Type Prediction Based on Selected Probeset.\n")
if (probeList == "Ttest") {
coefs <- pickCompProbes2(betas = ref.n,
meta = refMeta,
nP = nProbes,
ct = cellTypes,
ps = probeSelect,
p.val = 0.05,
min.delta.beta = 0,
plot = plotRef) # Call the pickCompProbes2 function below to select the probes that can best discern cell types and calculate weights
} else if (probeList == "Caret") {
coefs_caret <- pickCompProbesCaret(betas = ref.n,
meta = refMeta,
ct = cellTypes,
caretMods = caretMods, # caretMods = c("EL", "BLR", "CART", "RF", "GBM", "LDA", "RFEnRF", "RFEnNB", "RFEnSVM", "RFEnNN")
verbose = verbose,
filtern = 10000,
seed = seed)
} else {
load("/mnt/scratch/KoborLab/Personal_Folders/mfu/Reference/Probe_libraries.RData")
if (probeList == "IDOL") {
if (unique(sampType) == "CB") {
pLib <- idol.c
} else if (nrow(samp.n) > 622399) {
pLib <- idol.a_EPIC
} else {
pLib <- idol.a_450
}
} else if (probeList == "DHS") {
pLib <- DHS
}
coefs <- pickCompProbes2(betas = ref.n, meta = refMeta, nP = nProbes,
ct = cellTypes, trainingProbes = pLib, plot = plotRef)
}
```
#### Estimate proportion
```{r}
### Estimate cell type proportion
if (verbose)
cat("Estimating Composition Based on Selected Projection Method.\n")
projectionMethod <- get(method)
if (probeList == "Caret"){
out <- lapply(coefs_caret$probeCoefs, function(coefs){
mat <- samp.n[rownames(coefs), ]
mat <- as.matrix(mat[complete.cases(mat), ])
mat.cb <- mat[, sampMeta$sampleType == "CB"]
mat.pb <- mat[, sampMeta$sampleType == "PB"]
coefs.cb <- as.matrix(coefs)
coefs.pb <- coefs.cb[, colnames(coefs.cb) != "nRBC"] # For peripheral blood, remove nRBC in prediction
if (ncol(mat.cb) > 0) {
if (is.null(conditions)) counts.cb <- projectionMethod(samp.n = mat.cb, coef = coefs.cb) %>%
as.data.frame()# Using the weights generated in the last step to stimate the proportion of each cell type
else counts.cb <- projectionMethod(samp.n = mat.cb, coef = coefs.cb, conditions = conditions) %>%
as.data.frame()
}
if (ncol(mat.pb) > 0) {
if (is.null(conditions)) counts.pb <- projectionMethod(samp.n = mat.pb, coef = coefs.pb) %>%
as.data.frame()
else counts.pb <- projectionMethod(samp.n = mat.pb, coef = coefs.pb, conditions = conditions) %>%
as.data.frame()
counts.pb$nRBC <- 0
}
if (exists("counts.cb") & exists("counts.pb")) {
counts <- rbind(counts.cb, counts.pb) %>% .[colnames(mat), ]
} else if (exists("counts.cb") & !exists("counts.pb")) {
counts <- counts.cb
} else if (!exists("counts.cb") & exists("counts.pb")) {
counts <- counts.pb
}
return(counts)
})
} else {
mat <- samp.n[rownames(coefs), ]
mat <- as.matrix(mat[complete.cases(mat), ])
mat.cb <- mat[, sampMeta$sampleType == "CB"]
mat.pb <- mat[, sampMeta$sampleType == "PB"]
coefs.cb <- as.matrix(coefs)
coefs.pb <- coefs.cb[, colnames(coefs.cb) != "nRBC"]
if (ncol(mat.cb) > 0) {
if (is.null(conditions)) counts.cb <- projectionMethod(samp.n = mat.cb, coef = coefs.cb) %>%
as.data.frame()
else counts.cb <- projectionMethod(samp.n = mat.cb, coef = coefs.cb, conditions = conditions) %>%
as.data.frame()
}
if (ncol(mat.pb) > 0) {
if (is.null(conditions)) counts.pb <- projectionMethod(samp.n = mat.pb, coef = coefs.pb) %>%
as.data.frame()
else counts.pb <- projectionMethod(samp.n = mat.pb, coef = coefs.pb, conditions = conditions) %>%
as.data.frame()
counts.pb$nRBC <- 0
}
if (exists("counts.cb") & exists("counts.pb")) {
counts <- rbind(counts.cb, counts.pb) %>% .[colnames(mat), ]
} else if (exists("counts.cb") & !exists("counts.pb")) {
counts <- counts.cb
} else if (!exists("counts.cb") & exists("counts.pb")) {
counts <- counts.pb
}
out <- counts
}
# out <- list(counts = counts, coefs = coefs, betas.n = samp.n)
```
#### Plot cell type
```{r}
meta <- cbind(meta, out)
BloodPlot <- function(mt, vartype = c("categorical", "continuous"), varname = NULL,
tissue = c("blood", "bloodextended", "cord")) {
require(dplyr)
require(ggpubr)
require(gridExtra)
if (tissue == "blood"){
ct <- c("CD8T", "CD4T", "NK", "Bcell", "Mono", "Gran")
} else if (tissue == "bloodextended"){
ct <- c("Bas", "Bmem", "Bnv", "CD4mem", "CD4nv",
"CD8mem", "CD8nv", "Eos", "Mono", "Neu", "NK", "Treg")
} else if (tissue == "Cord"){
ct <- c("CD8T", "CD4T", "NK", "Bcell", "Mono", "Gran", "nRBC")
}
counts <- mt[, c("Sample_Name", ct)] %>% as.data.table()
counts_plot <- melt(counts, id.vars = "Sample_Name")
covar <- mt[, c("Sample_Name", varname)]
plt <- merge(counts_plot, covar, by = "Sample_Name") %>%
as.data.frame()
p1 <- ggplot(plt, aes(get(varname), value, fill = get(varname))) +
geom_boxplot(alpha = 0.2) +
geom_point(shape = 21, aes(group = Sample_Name),
position = position_jitter(w = 0.1)) +
xlab(NULL) +
ylab("Cell Proportion") +
theme_bw() +
theme(axis.text = element_text(size = 12, color = "black"),
axis.title = element_text(size = 14),
legend.text = element_text(size = 11),
legend.title = element_text(size = 14),
strip.text = element_text(size = 14),
axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
facet_wrap(~ variable)
# if (vartype == "categorical") {
# p1 <- p1 + stat_compare_means(method = "t.test")
# }
plot(p1)
}
BloodPlot(mt = meta, vartype = "categorical", varname = "Sample_Group", tissue = "bloodextended") +
scale_fill_manual(values = group.colors)
# Compare predicted and flow cell type proportion
cor.test(meta$CD4_perc_flow, meta$CD4_perc_DNAm)
cor.test(meta$CD8_perc_flow, meta$CD8_perc_DNAm)
ggplot(meta, aes(CD4_perc_DNAm, CD4_perc_flow)) +
geom_smooth(method = "lm", color = "gray") +
geom_point(aes(color = Sample_Group), size = 2.5) +
scale_color_manual(values = group.colors) +
theme_bw() +
theme(text = element_text(size = 14))
ggplot(meta, aes(CD8_perc_DNAm, CD8_perc_flow)) +
geom_smooth(method = "lm", color = "gray") +
geom_point(aes(color = Sample_Group), size = 2.5) +
scale_color_manual(values = group.colors) +
theme_bw() +
theme(text = element_text(size = 14))
```
#### Make cell type PCs
```{r}
source("../../Functions/pcaCoDa_NG.R")
ct <- meta[, c("CD4mem", "CD4nv", "CD8mem", "CD8nv", "Treg")] %>%
as.data.frame()
sum(ct==0) #Are there any proportions predicted to be 0?
ct <- (ct + 0.0001) #If necessary, add the offset of 0.001
min(ct) # Cannot be = or < 0
pca_object <- pcaCoDa(ct)
CTP <- as.data.frame(pca_object$scores)
colnames(CTP) <- c("CTP_PC1", "CTP_PC2", "CTP_PC3", "CTP_PC4")
rownames(CTP) <- rownames(ct)
identical(rownames(meta), rownames(CTP))
meta <- cbind(meta, CTP)
save(beta, meta, anno, file = "RData/902-ASXL1_Tcell_betas_norm.RData")
```
### DNAm age
```{r}
load("RData/902-ASXL1_Tcell_betas_norm.RData")
# DNAm Age
bt <- cbind(CpG = rownames(beta), as.data.frame(beta))
cpgs.missing <- checkClocks(bt)
DNAmage <- DNAmAge(bt, clocks = c("Horvath", "Hannum", "skinHorvath", "Levine", "Wu"))
meta <- cbind(meta, DNAmage[, 2:6])
meta$Sample_Group <- factor(meta$Sample_Group, level = c('unrelated healthy control', 'family control', 'patient empty vector', 'patient wild type'))
ggplot(as.data.frame(meta), aes(Sample_Group, Horvath, fill = Sample_Group)) +
geom_boxplot() +
geom_point(size = 2) +
theme_bw() +
scale_fill_manual(values = group.colors) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
text = element_text(size = 15)) +
labs(x = "", y = "Horvath Epigenetic Clock DNAm Age", fill = "Sample Group")
save(beta, meta, anno, file = "RData/902-ASXL1_Tcell_betas_norm.RData")
```
### Variable correlation matrix
```{r}
library(corrplot)
plt <- meta[, c("Disease_Status", # Sample groups
"xMed", "yMed", "Sentrix_row", # Technical batch
"predictedSex", # demographic variables
"CD4mem", "CD4nv", "CD8mem", "CD8nv", "Treg", # cell type
"CTP_PC1", "CTP_PC2", "CTP_PC3", "CTP_PC4", # Cell type PCs
"Horvath", "Hannum", "Levine", "skinHorvath", "Wu") # DNAm age
] %>% as.data.frame()
plt$Disease_Status <- plt$Disease_Status %>%
gsub("Healthy control", 0, .) %>%
gsub("ASXL1 rescue", 1, .) %>%
gsub("ASXL1 variant", 2, .) %>%
as.numeric()
plt$predictedSex <- plt$predictedSex %>%
gsub("F", 0, .) %>%
gsub("M", 1, .) %>%
as.numeric()
# Calculate correlation statistics
cor.mat <- cor(plt)
# Calculate
cor.mtest <- function(mat, ...) {
mat <- as.matrix(mat)
n <- ncol(mat)
p.mat<- matrix(NA, n, n)
diag(p.mat) <- 0
for (i in 1:(n - 1)) {
for (j in (i + 1):n) {
tmp <- cor.test(mat[, i], mat[, j], ...)
p.mat[i, j] <- p.mat[j, i] <- tmp$p.value
}
}
colnames(p.mat) <- rownames(p.mat) <- colnames(mat)
p.mat
}
# matrix of the p-value of the correlation
p.mat <- cor.mtest(plt)
head(p.mat[, 1:5])
library(RColorBrewer)
corrplot(cor.mat, type="upper", order = "original",
col = brewer.pal(n = 8, name = "RdBu"),
tl.col = "black", tl.srt = 45,
p.mat = p.mat, sig.level = 0.05,
pch.col = "gray", pch.cex = 2, diag = F)
col <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF", "#77AADD", "#4477AA"))
corrplot(cor.mat, method = "color", col = col(200),
type = "upper", order = "original",
addCoef.col = "black", # Add coefficient of correlation
tl.col = "black", tl.srt = 45, #Text label color and rotation
# Combine with significance
p.mat = p.mat, sig.level = 0.05,
insig = "n", diag = F)
```
### Check DNAm clustering - Hierarchical and PCA
```{r}
# Heatmap
bt <- beta[sample(1:nrow(beta),50000), ]
pheatmap(bt, show_rownames = F)
# PCA
source("../../Functions/heatscreesimple.R")
PCA.C <- prcomp(beta)
meta_cat <- meta[, c("predictedSex", "Sample_Group")]
colnames(meta_cat) <- c("Predicted_Sex", "Sample_Group")
meta_con <- meta[, c("Sentrix_row", "CTP_PC1", "CTP_PC2", "CTP_PC3", "CTP_PC4")]
heatscreesimple(PCA.C$rotation, PCA.C$sdev^2, meta_cat, meta_con, 5) # Don't need to adjust for batch!
pcaObj <- PCA.C$rotation %>% as.data.frame() %>% cbind(., meta[, c("Sample_Group", "predictedSex")])
group.colors <- c("family control" = "#EBCB8BFF", "unrelated healthy control" = "#A3BE8CFF", "patient empty vector" ="#BF616AFF", "patient wild type" = "#B48EADFF")
ggplot(pcaObj, aes(PC1, PC2, color = Sample_Group, shape = predictedSex)) +
geom_point(size = 4) +
theme_bw() +
scale_color_manual(values = group.colors)
```
### Correct for cell type - correct for flow CD8 proportion
Even though cell types are not in top PCs
```{r}
load("RData/902-ASXL1_Tcell_betas_norm.RData")
residuals <- t(apply(beta, 1, function(x){
x <- as.numeric(x)
residuals(summary(lm(x ~ CD8_perc_flow, data = meta)))
}))
colnames(residuals) <- colnames(beta)
adj.residuals <- residuals + matrix(apply(beta, 1, mean), nrow = nrow(residuals), ncol = ncol(residuals))
adj.residuals[adj.residuals <= 0] <- 0.0001 # convert any values that are less than or equal to zero to 0.0001
adj.residuals[adj.residuals > 1] <- 0.9999
save(adj.residuals, file = "RData/902-ASXL1_Tcell_betas_ct_adjusted.RData")
```
## Data analysis
### Check if the patient samples are outside the HC range
```{r}
load("RData/902-ASXL1_Tcell_betas_norm.RData")
load("RData/902-ASXL1_Tcell_betas_ct_adjusted.RData")
beta <- adj.residuals # if using cell type corrected betas
# Compared to IQR / SD range
meta$Disease_Status <- gsub(".*control", "Healthy control", meta$Sample_Group) %>%
gsub(".*vector", "ASXL1 variant", .) %>%
gsub(".*type", "ASXL1 rescue", .)
# Subset for patient and HCs
beta.pat <- beta[, "P_EV"]
beta.res <- beta[, "P_WT ASXL1"]
beta.ref <- beta[, meta$Disease_Status == "Healthy control"]
# Calculate the reference range
beta.refIQR <- apply(beta.ref, 1, function(x) {quantile(x, c(0.025, 0.25, 0.5, 0.75, 0.975))}) %>% t() %>% as.data.frame()
beta.refIQR$iqr <- beta.refIQR[, 4] - beta.refIQR[, 2]
beta.refIQR$beta.refIQRl <- beta.refIQR[, 2] - 1.5*beta.refIQR$iqr
beta.refIQR$beta.refIQRh <- beta.refIQR[, 4] + 1.5*beta.refIQR$iqr
beta.refSD <- apply(beta.ref, 1, sd)
beta.refM <- apply(beta.ref, 1, mean)
ASXL1.test <- cbind(beta.refIQR, beta.refSD, beta.refM, beta.pat, beta.res) %>% as.data.frame()
ASXL1.test$beta.refSD2l <- ASXL1.test$beta.refM - (ASXL1.test$beta.refSD*2)
ASXL1.test$beta.refSD2h <- ASXL1.test$beta.refM + (ASXL1.test$beta.refSD*2)
ASXL1.test$beta.refSD3l <- ASXL1.test$beta.refM - (ASXL1.test$beta.refSD*3)
ASXL1.test$beta.refSD3h <- ASXL1.test$beta.refM + (ASXL1.test$beta.refSD*3)
ASXL1.test$beta.refSD4l <- ASXL1.test$beta.refM - (ASXL1.test$beta.refSD*4)
ASXL1.test$beta.refSD4h <- ASXL1.test$beta.refM + (ASXL1.test$beta.refSD*4)
ASXL1.test$beta.refSD5l <- ASXL1.test$beta.refM - (ASXL1.test$beta.refSD*5)
ASXL1.test$beta.refSD5h <- ASXL1.test$beta.refM + (ASXL1.test$beta.refSD*5)
# Set empty variable for tests
ASXL1.test$IQR.test.pat <- NA
ASXL1.test$IQR.test.res <- NA
ASXL1.test$IQR2.test.pat <- NA
ASXL1.test$IQR2.test.res <- NA
ASXL1.test$SD2.test.pat <- NA
ASXL1.test$SD2.test.res <- NA
ASXL1.test$SD3.test.pat <- NA
ASXL1.test$SD3.test.res <- NA
ASXL1.test$SD4.test.pat <- NA
ASXL1.test$SD4.test.res <- NA
ASXL1.test$SD5.test.pat <- NA
ASXL1.test$SD5.test.res <- NA
for (i in 1:nrow(ASXL1.test)) {
if(beta.pat[i] < ASXL1.test[i, "2.5%"] |
beta.pat[i] > ASXL1.test[i, "97.5%"]) {
ASXL1.test$IQR.test.pat[i] <- "s"
} else {
ASXL1.test$IQR.test.pat[i] <- "ns"
}
if(beta.res[i] < ASXL1.test[i, "2.5%"] |
beta.res[i] > ASXL1.test[i, "97.5%"]) {
ASXL1.test$IQR.test.res[i] <- "s"
} else {
ASXL1.test$IQR.test.res[i] <- "ns"
}
}
for (i in 1:nrow(ASXL1.test)) {
if(beta.pat[i] < ASXL1.test[i, "beta.refIQRl"] |
beta.pat[i] > ASXL1.test[i, "beta.refIQRh"]) {
ASXL1.test$IQR2.test.pat[i] <- "s"
} else {
ASXL1.test$IQR2.test.pat[i] <- "ns"
}
if(beta.res[i] < ASXL1.test[i, "beta.refIQRl"] |
beta.res[i] > ASXL1.test[i, "beta.refIQRh"]) {
ASXL1.test$IQR2.test.res[i] <- "s"
} else {
ASXL1.test$IQR2.test.res[i] <- "ns"
}
}
for (i in 1:nrow(ASXL1.test)) {
if(beta.pat[i] < ASXL1.test[i, "beta.refSD2l"] |
beta.pat[i] > ASXL1.test[i, "beta.refSD2h"]) {
ASXL1.test$SD2.test.pat[i] <- "s"
} else {
ASXL1.test$SD2.test.pat[i] <- "ns"
}
if(beta.res[i] < ASXL1.test[i, "beta.refSD2l"] |
beta.res[i] > ASXL1.test[i, "beta.refSD2h"]) {
ASXL1.test$SD2.test.res[i] <- "s"
} else {
ASXL1.test$SD2.test.res[i] <- "ns"
}
}
for (i in 1:nrow(ASXL1.test)) {
if(beta.pat[i] < ASXL1.test[i, "beta.refSD3l"] |
beta.pat[i] > ASXL1.test[i, "beta.refSD3h"]) {
ASXL1.test$SD3.test.pat[i] <- "s"
} else {
ASXL1.test$SD3.test.pat[i] <- "ns"
}
if(beta.res[i] < ASXL1.test[i, "beta.refSD3l"] |
beta.res[i] > ASXL1.test[i, "beta.refSD3h"]) {
ASXL1.test$SD3.test.res[i] <- "s"
} else {
ASXL1.test$SD3.test.res[i] <- "ns"
}
}
for (i in 1:nrow(ASXL1.test)) {
if(beta.pat[i] < ASXL1.test[i, "beta.refSD4l"] |
beta.pat[i] > ASXL1.test[i, "beta.refSD4h"]) {
ASXL1.test$SD4.test.pat[i] <- "s"
} else {
ASXL1.test$SD4.test.pat[i] <- "ns"
}
if(beta.res[i] < ASXL1.test[i, "beta.refSD4l"] |
beta.res[i] > ASXL1.test[i, "beta.refSD4h"]) {
ASXL1.test$SD4.test.res[i] <- "s"
} else {
ASXL1.test$SD4.test.res[i] <- "ns"
}
}
for (i in 1:nrow(ASXL1.test)) {
if(beta.pat[i] < ASXL1.test[i, "beta.refSD5l"] |
beta.pat[i] > ASXL1.test[i, "beta.refSD5h"]) {
ASXL1.test$SD5.test.pat[i] <- "s"
} else {
ASXL1.test$SD5.test.pat[i] <- "ns"
}
if(beta.res[i] < ASXL1.test[i, "beta.refSD5l"] |
beta.res[i] > ASXL1.test[i, "beta.refSD5h"]) {
ASXL1.test$SD5.test.res[i] <- "s"
} else {
ASXL1.test$SD5.test.res[i] <- "ns"
}
}
sum(ASXL1.test$IQR.test.pat == "s") # 395147 / 358871
sum(ASXL1.test$IQR.test.res == "s") # 363057 / 221819
sum(ASXL1.test$IQR2.test.pat == "s") # 257476 / 92269
sum(ASXL1.test$IQR2.test.res == "s") # 210664 / 46893
hits_rescued <- rownames(ASXL1.test)[ASXL1.test$IQR2.test.pat == "s" & ASXL1.test$IQR2.test.res == "ns"]
length(hits_rescued) # 151880
hits_not_rescued <- rownames(ASXL1.test)[ASXL1.test$IQR2.test.pat == "s" & ASXL1.test$IQR2.test.res == "s"]
length(hits_not_rescued) # 132792
sum(ASXL1.test$SD2.test.pat == "s") # 264844 / 2766
sum(ASXL1.test$SD2.test.res == "s") # 216981 / 1333
sum(ASXL1.test$SD3.test.pat == "s") # 168067 / 0
sum(ASXL1.test$SD3.test.res == "s") # 106935 / 0
sum(ASXL1.test$SD4.test.pat == "s") # 106935 / 0
sum(ASXL1.test$SD4.test.res == "s") # 62515 / 0
sum(ASXL1.test$SD5.test.pat == "s") # 67239 / 0
sum(ASXL1.test$SD5.test.res == "s") # 36362 / 0
# Check for hyper / hypo methylation
length(rownames(ASXL1.test)[ASXL1.test$SD2.test.pat == "s" & ASXL1.test$beta.pat > ASXL1.test$beta.refM]) # 81
length(rownames(ASXL1.test)[ASXL1.test$SD2.test.pat == "s" & ASXL1.test$beta.pat < ASXL1.test$beta.refM]) # 2685
length(rownames(ASXL1.test)[ASXL1.test$SD2.test.res == "s" & ASXL1.test$beta.res > ASXL1.test$beta.refM]) # 1209
length(rownames(ASXL1.test)[ASXL1.test$SD2.test.res == "s" & ASXL1.test$beta.res < ASXL1.test$beta.refM]) # 124
hits_rescued <- rownames(ASXL1.test)[ASXL1.test$SD2.test.pat == "s" & ASXL1.test$SD2.test.res == "ns"]
length(hits_rescued) # 50311 / 2766
hits_not_rescued <- rownames(ASXL1.test)[ASXL1.test$SD2.test.pat == "s" & ASXL1.test$SD2.test.res == "s"]
length(hits_not_rescued) # 16928 / 0
hits_messed_up <- rownames(ASXL1.test)[ASXL1.test$SD2.test.pat == "ns" & ASXL1.test$SD2.test.res == "s"]
length(hits_messed_up) # 19434 / 1333
saveRDS(ASXL1.test, file = "RData/903-ASXL1_Tcell_global_test.rds")
ASXL1.test.CC <- ASXL1.test
saveRDS(ASXL1.test.CC, file = "RData/903-ASXL1_Tcell_global_test_ct_adjusted.rds")
# hist(ASXL1.test$beta.refSD)
# hist(ASXL1.test$beta.refM)
# Make Heatmap
beta <- beta[, c("HC1", "HC2", "HC3", "Dad", "Mom", "Sister", "P_EV", "P_WT ASXL1")]
plt <- beta[hits_rescued, ] #%>%
# .[order(.[, "P_EV"]), ]
# using the SD5 definition
pheatmap(plt, # [sample(1:nrow(plt),50000),]
show_rownames = F,
scale = "row",
treeheight_row = 0,
cluster_cols = F,
cluster_rows = T) # do not show clustering
pheatmap(plt, # cannot plot all 75k
show_rownames = F,
scale = "none",
treeheight_row = 0,
cluster_cols = F)
plt <- beta[hits_not_rescued, ]
pheatmap(plt, # using the SD5 definition
show_rownames = F,
scale = "row",
treeheight_row = 0,
cluster_cols = F)
pheatmap(plt, # using the SD5 definition
show_rownames = F,
scale = "none",
treeheight_row = 0,
cluster_cols = F)
plt <- beta[hits_messed_up, ]
pheatmap(plt, # using the SD5 definition
show_rownames = F,
scale = "row",
treeheight_row = 0,
cluster_cols = F)
pheatmap(plt, # using the SD5 definition
show_rownames = F,
scale = "none",
treeheight_row = 0,
cluster_cols = F)
```
#### Explore reference range comparison results
##### Defining regions for DMR analysis
```{r}
anno <- readRDS("../../Reference/EPICv2_fdat.rds")
anno <- anno[!is.na(anno$MAPINFO), ]
anno <- anno[with(anno, order(CHR, MAPINFO)),]
# Region for finding DMR
anno$Mreg <- 1
reg <- 1
for (i in 2:nrow(anno)) {
if (anno$MAPINFO[i] - anno$MAPINFO[i-1] > 1000) {
reg <- reg + 1
}
anno$Mreg[i] <- reg
}
# Regions for gene region plotting
anno$Mreg_plt <- 1
reg <- 1
for (i in 2:nrow(anno)) {
if (anno$MAPINFO[i] - anno$MAPINFO[i-1] > 10000) {
reg <- reg + 1
}
anno$Mreg_plt[i] <- reg
}
saveRDS(anno, file = "../../Reference/EPICv2_fdat_Mreg.rds")
# anno$Mreg <- sapply(unique(anno$CHR), function(chr){
# i <- 1
# anno_chr <- anno[anno$CHR == chr, ] %>%
# .[order(.$MAPINFO), ]
# anno_chr$Mreg <- NA
# apply(anno_chr, 1, function(cpg){
#
# })
# })
anno_v2 <- readRDS("../../Reference/EPICv2_fdat_Mreg.rds")
load("../../Reference/EPIC_fdat_Mreg.RData")
anno_v1 <- fdat_EPIC_Mreg
```
##### Map hits to annotation - plot DMRs
```{r}
load("RData/902-ASXL1_Tcell_betas_norm.RData")
ASXL1.test <- readRDS("RData/903-ASXL1_Tcell_global_test.rds")
anno <- readRDS("../../Reference/EPICv2_fdat_Mreg.rds")
source("../../Functions/plotmultigeneregion.R")
source("../../Functions/plotGeneRegion.R")
ASXL1.test.anno <- merge(ASXL1.test, anno[, c("CHR", "MAPINFO", "Mreg", "Mreg_plt", "UCSC_RefGene_Name", "GencodeCompV12_NAME")], by = 0)
rownames(ASXL1.test.anno) <- ASXL1.test.anno$Row.names
# Take the biggest DMRs
hits.dmr <- table(ASXL1.test.anno[ASXL1.test.anno$SD5.test.pat == "s" & ASXL1.test.anno$SD5.test.res == "ns", "Mreg"]) %>% sort(decreasing = T) %>% .[.>3]
Mreg_size <- table(anno$Mreg)[names(hits.dmr)] # Also filter by proportion of hits in a region
hits_rescued.dmr <- (hits.dmr / Mreg_size) %>%
sort(decreasing = T) %>%
.[. >= 0.7] %>%
names(.) # At least 15%
# Make table of hits
length(hits_rescued.dmr) #502 at Mreg size >= 5
View(ASXL1.test.anno[ASXL1.test.anno$Mreg %in% hits_rescued.dmr, ])
# ASXL1.test.dmr <- table(ASXL1.test.anno[test, "Mreg"]) %>% sort(decreasing = T) %>% .[.>=3] %>% names()
hits_rescued.dmr.gene <- sapply(hits_rescued.dmr, function(x) {
test <- anno[anno$Mreg == x, "UCSC_RefGene_Name"] %>%
strsplit2(., ";") %>%
as.vector() %>%
unique()
if (identical(test, character(0))) test <- ""
if (length(test) > 1) {
test <- test[test != ""]
test <- paste0(test, collapse = ", ")
}
return(test)
})
dmr.genes <- do.call(c, hits_rescued.dmr.gene)
toString(shQuote(hits_rescued.dmr.gene))
genes <- c('LOC101927342', 'MAP4K4', 'MIR143HG, LOC728264', 'KCNB2', 'TMEM125', 'LOC400794', 'DISC1, TSNAX-DISC1', '', 'CACNA2D3', '', '', 'NXPH1', 'RNF19A', 'OR8D4', 'MTUS2', 'ARFRP1')
genes_plt <- genes
# If byvar = "Mreg"
hits_rescued.dmr.geneanno <- anno[anno$Mreg %in% hits_rescued.dmr, ]
# If byvar = "UCSC_RefGene_Name"
# hits_rescued.dmr.geneanno <- anno[grep(paste(genes_plt, collapse = "|"), anno$UCSC_RefGene_Name), ]
group.colors <- c("family control" = "#EBCB8BFF", "unrelated healthy control" = "#A3BE8CFF", "patient empty vector" ="#BF616AFF", "patient wild type" = "#B48EADFF")
mcolors <- c("family control" = "#EBCB8BFF", "unrelated healthy control" = "gray", "patient empty vector" ="#BF616AFF", "patient wild type" = "#B48EADFF")
malpha <- c("family control" = 0.3, "unrelated healthy control" = 0.3, "patient empty vector" = 1, "patient wild type" = 1)
plotmultigeneregion(bt = beta, # [, meta$Disease_Status == "Healthy Control" | rownames(meta) == "203077630141_R07C01"]