-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathprepare.R
More file actions
2105 lines (1853 loc) · 76.6 KB
/
Copy pathprepare.R
File metadata and controls
2105 lines (1853 loc) · 76.6 KB
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 Prepare GDC data
#' @description
#' Reads the data downloaded and prepare it into an R object
#' @param query A query for GDCquery function
#' @param save Save result as RData object?
#' @param save.filename Name of the file to be save if empty an automatic will be created
#' @param directory Directory/Folder where the data was downloaded. Default: GDCdata
#' @param summarizedExperiment Create a summarizedExperiment? Default TRUE (if possible)
#' @param remove.files.prepared Remove the files read? Default: FALSE
#' This argument will be considered only if save argument is set to true
#' @param add.gistic2.mut If a list of genes (gene symbol) is given, columns with gistic2 results from GDAC firehose (hg19)
#' and a column indicating if there is or not mutation in that gene (hg38)
#' (TRUE or FALSE - use the MAF file for more information)
#' will be added to the sample matrix in the summarized Experiment object.
#' @param mutant_variant_classification List of mutant_variant_classification that will be
#' consider a sample mutant or not. Default: "Frame_Shift_Del", "Frame_Shift_Ins",
#' "Missense_Mutation", "Nonsense_Mutation", "Splice_Site", "In_Frame_Del",
#' "In_Frame_Ins", "Translation_Start_Site", "Nonstop_Mutation"
#' @export
#' @examples
#' \dontrun{
#' query <- GDCquery(
#' project = "TCGA-KIRP",
#' data.category = "Simple Nucleotide Variation",
#' data.type = "Masked Somatic Mutation"
#' )
#' GDCdownload(query, method = "api", directory = "maf")
#' maf <- GDCprepare(query, directory = "maf")
#'
#' }
#' @return A summarizedExperiment or a data.frame
#' @importFrom S4Vectors DataFrame
#' @importFrom SummarizedExperiment metadata<-
#' @importFrom data.table setcolorder setnames
#' @importFrom GenomicRanges GRanges
#' @importFrom IRanges IRanges
#' @importFrom purrr map_chr
#' @author Tiago Chedraoui Silva
GDCprepare <- function(
query,
save = FALSE,
save.filename,
directory = "GDCdata",
summarizedExperiment = TRUE,
remove.files.prepared = FALSE,
add.gistic2.mut = NULL,
mutant_variant_classification = c(
"Frame_Shift_Del",
"Frame_Shift_Ins",
"Missense_Mutation",
"Nonsense_Mutation",
"Splice_Site",
"In_Frame_Del",
"In_Frame_Ins",
"Translation_Start_Site",
"Nonstop_Mutation"
)
){
isServeOK()
if(missing(query)) stop("Please set query parameter")
# test.duplicated.cases <- (
# any(
# duplicated(query$results[[1]]$cases)) & # any duplicated
# !(query$data.type %in% c(
# "Clinical data",
# "Protein expression quantification",
# "Raw intensities",
# "Masked Intensities",
# "Clinical Supplement",
# "Masked Somatic Mutation",
# "Biospecimen Supplement"
# )
# )
# )
#
#
# if(test.duplicated.cases) {
# dup <- query$results[[1]]$cases[duplicated(query$results[[1]]$cases)]
# cols <- c("tags","cases","experimental_strategy","analysis_workflow_type")
# cols <- cols[cols %in% colnames(query$results[[1]])]
# dup <- query$results[[1]][query$results[[1]]$cases %in% dup,cols]
# dup <- dup[order(dup$cases),]
# print(knitr::kable(dup))
# stop("There are samples duplicated. We will not be able to prepare it")
# }
if (!save & remove.files.prepared) {
stop("To remove the files, please set save to TRUE. Otherwise, the data will be lost")
}
cases_col <- ifelse(
any(grepl("TCGA|TARGET|CGCI-HTMCP-CC|CPTAC-2|BEATAML1.0-COHORT",query$results[[1]]$project %>% unlist())),
"cases",
"sample.submitter_id"
)
tbl = query$results[[1]]
cases = tbl[[cases_col]]
if (any(duplicated(cases))) {
message("Removing duplicated cases (with older updated time)")
tbl2 = tbl |> dplyr::arrange(dplyr::desc(tbl$updated_datetime))
tbl2 = tbl2[!duplicated(tbl2[[cases_col]]), ]
n_dup = nrow(tbl) - nrow(tbl2)
query$results[[1]] = tbl2
cases = tbl2[[cases_col]]
message(" => ", n_dup, " records removed")
}
# We save the files in project/data.category/data.type/file_id/file_name
files <- file.path(
query$results[[1]]$project,
gsub(" ","_",query$results[[1]]$data_category),
gsub(" ","_",query$results[[1]]$data_type),
gsub(" ","_",query$results[[1]]$file_id),
gsub(" ","_",query$results[[1]]$file_name)
)
files <- file.path(directory, files)
# For IDAT prepare since we need to put all IDATs in the same folder the code below will not work
# a second run
if (!all(file.exists(files))) {
# We have to check we moved the files
if (
unique(query$results[[1]]$data_type) == "Masked Intensities" |
unique(query$results[[1]]$data_category) == "Raw microarray data"
){
files.idat <- file.path(
query$results[[1]]$project,
gsub(" ","_",query$results[[1]]$data_category),
gsub(" ","_",query$results[[1]]$data_type),
gsub(" ","_",query$results[[1]]$file_name)
)
files.idat <- file.path(directory, files.idat)
if (!all(file.exists(files) | file.exists(files.idat))) {
stop(
paste0(
"I couldn't find all the files from the query. ",
"Please check if the directory parameter is right ",
"or `GDCdownload` downloaded the samples."
)
)
}
} else {
stop(
paste0(
"I couldn't find all the files from the query. ",
"Please check if the directory parameter is right ",
"or `GDCdownload` downloaded the samples."
)
)
}
}
if (grepl("Transcriptome Profiling", query$data.category, ignore.case = TRUE)){
if(unique(query$results[[1]]$experimental_strategy) == "scRNA-Seq"){
#if (grepl("Single Cell Analysis", unique(query$results[[1]]$data_type), ignore.case = TRUE)){
data <- readSingleCellAnalysis(
files = files,
data_format = unique(query$results[[1]]$data_format),
workflow.type = unique(query$results[[1]]$analysis_workflow_type),
cases = cases
)
return(data)
} else {
data <- readTranscriptomeProfiling(
files = files,
data.type = ifelse(!is.na(query$data.type), as.character(query$data.type), unique(query$results[[1]]$data_type)),
workflow.type = unique(query$results[[1]]$analysis_workflow_type),
cases = cases,
summarizedExperiment
)
}
} else if(grepl("Copy Number Variation",query$data.category,ignore.case = TRUE)) {
if (unique(query$results[[1]]$data_type) == "Gene Level Copy Number Scores") {
data <- readGISTIC(files, query$results[[1]]$cases)
} else if (unique(query$results[[1]]$data_type) == "Gene Level Copy Number") {
data <- read_gene_level_copy_number(
files = files,
cases = query$results[[1]]$sample.submitter_id,
summarizedExperiment = summarizedExperiment
)
} else {
data <- read_copy_number_variation(
files = files, cases = query$results[[1]]$cases
)
}
} else if (grepl("Methylation Beta Value",unique(query$results[[1]]$data_type), ignore.case = TRUE)) {
data <- readDNAmethylation(
files = files,
cases = cases,
summarizedExperiment = summarizedExperiment,
platform = unique(query$results[[1]]$platform)
)
} else if (grepl("Raw intensities|Masked Intensities",query$data.type, ignore.case = TRUE)) {
# preparing IDAT files
data <- readIDATDNAmethylation(
files = files,
barcode = cases,
summarizedExperiment = summarizedExperiment,
platform = unique(query$results[[1]]$platform)
)
} else if (grepl("Proteome Profiling",query$data.category,ignore.case = TRUE)) {
data <- readProteomeProfiling(files, cases = cases)
} else if (grepl("Protein expression",query$data.category,ignore.case = TRUE)) {
data <- readProteinExpression(files, cases = cases)
if (summarizedExperiment) {
message("SummarizedExperiment not implemented, if you need samples metadata use the function TCGAbiolinks:::colDataPrepare")
}
} else if (grepl("Simple Nucleotide Variation",query$data.category,ignore.case = TRUE)) {
if (grepl("Masked Somatic Mutation",query$results[[1]]$data_type[1],ignore.case = TRUE)){
data <- readSimpleNucleotideVariationMaf(files)
}
} else if (grepl("Clinical|Biospecimen", query$data.category, ignore.case = TRUE)){
data <- read_clinical(files, query$data.type, cases = cases)
summarizedExperiment <- FALSE
} else if (grepl("Gene expression",query$data.category,ignore.case = TRUE)) {
if (query$data.type == "Gene expression quantification")
data <- read_gene_expression_quantification(
files = files,
cases = cases,
summarizedExperiment = summarizedExperiment,
genome = "hg38",
experimental.strategy = unique(query$results[[1]]$experimental_strategy)
)
if (query$data.type == "miRNA gene quantification")
data <- read_gene_expression_quantification(
files = files,
cases = cases,
summarizedExperiment = FALSE,
genome = "hg38",
experimental.strategy = unique(query$results[[1]]$experimental_strategy)
)
if (query$data.type == "miRNA isoform quantification")
data <- readmiRNAIsoformQuantification(
files = files,
cases = query$results[[1]]$cases
)
if (query$data.type == "Isoform expression quantification")
data <- readIsoformExpressionQuantification(files = files, cases = cases)
if (query$data.type == "Exon quantification")
data <- readExonQuantification(
files = files,
cases = cases,
summarizedExperiment = summarizedExperiment
)
}
# Add data release to object
if (summarizedExperiment & !is.data.frame(data)) {
metadata(data) <- list("data_release" = getGDCInfo()$data_release)
}
if ((!is.null(add.gistic2.mut)) & summarizedExperiment) {
message("=> Adding GISTIC2 and mutation information....")
genes <- tolower(levels(EAGenes$Gene))
if (!all(tolower(add.gistic2.mut) %in% genes)) {
message(
paste("These genes were not found:\n",
paste(add.gistic2.mut[! tolower(add.gistic2.mut) %in% genes],collapse = "\n=> ")
)
)
}
add.gistic2.mut <- add.gistic2.mut[tolower(add.gistic2.mut) %in% tolower(genes)]
if (length(add.gistic2.mut) > 0){
info <- colData(data)
for(i in unlist(query$project)){
info <- get.mut.gistc.information(
info,
i,
add.gistic2.mut,
mutant_variant_classification = mutant_variant_classification
)
}
colData(data) <- info
}
}
if("samples" %in% colnames(data)){
if(any(duplicated(data$sample))) {
message("Replicates found.")
if(any(data$is_ffpe)) message("FFPE should be removed. You can modify the data with the following command:\ndata <- data[,!data$is_ffpe]")
print(as.data.frame(colData(data)[data$sample %in% data$sample[duplicated(data$sample)],c("is_ffpe"),drop = FALSE]))
}
}
if(save){
if(missing(save.filename) & !missing(query)) save.filename <- paste0(query$project,gsub(" ","_", query$data.category),gsub(" ","_",date()),".RData")
message(paste0("=> Saving file: ",save.filename))
save(data, file = save.filename)
message("=> File saved")
# save is true, due to the check in the beggining of the code
if(remove.files.prepared){
# removes files and empty directories
remove_files_recursively(files)
}
}
return(data)
}
remove_files_recursively <- function(files){
files2rm <- dirname(files)
unlink(files2rm,recursive = TRUE)
files2rm <- dirname(files2rm) # data category
if(length(list.files(files2rm)) == 0) remove_files_recursively(files2rm)
}
read_clinical <- function(files, data.type, cases){
if(data.type == "Clinical data"){
suppressMessages({
ret <- plyr::alply(files,.margins = 1,readr::read_tsv, .progress = "text")
})
names(ret) <- gsub("nationwidechildrens.org_","",gsub(".txt","",basename(files)))
} else if(data.type %in% c("Clinical Supplement","Biospecimen Supplement")){
ret <- plyr::alply(files,.margins = 1,function(f) {
readr::read_tsv(f,col_types = readr::cols())
}, .progress = "text")
names(ret) <- gsub("nationwidechildrens.org_","",gsub(".txt","",basename(files)))
}
return(ret)
}
readSingleCellAnalysis <- function(
files = files,
data_format = NULL,
workflow.type = NULL,
cases = cases
) {
if(data_format == "MEX" & workflow.type == "CellRanger - 10x Filtered Counts"){
check_package("Seurat")
ret <- plyr::llply(files,.fun = function(f){
untar(tarfile = f,exdir = dirname(f))
Seurat::Read10X(data.dir = gsub("\\.tar\\.gz","",f))
},.progress = "time")
names(ret) <- cases
}
if(data_format == "MEX" & workflow.type == "CellRanger - 10x Raw Counts"){
ret <- plyr::llply(files,.fun = function(f){
# uncompress raw file
untar(tarfile = f,exdir = dirname(f))
Read10X(data.dir = gsub("\\.tar\\.gz","",f))
},.progress = "time")
names(ret) <- cases
}
# TSV files
if(data_format == "TSV"){
ret <- plyr::llply(files,.fun = function(f){
readr::read_tsv(f)
},.progress = "time")
names(ret) <- cases
}
if(data_format == "HDF5"){
stop("We are not preparing loom files")
# check_package("SeuratDisk")
# check_package("Seurat")
# ret <- SeuratDisk::Connect(filename = files, mode = "r")
# ret <- Seurat::as.Seurat(ret)
print(files)
}
# HDF5
return(ret)
}
#' @importFrom tidyr separate
readExonQuantification <- function (
files,
cases,
summarizedExperiment = TRUE
){
pb <- txtProgressBar(min = 0, max = length(files), style = 3)
assay.list <- NULL
for (i in seq_along(files)) {
data <- fread(files[i], header = TRUE, sep = "\t", stringsAsFactors = FALSE)
if(!missing(cases)) {
assay.list <- gsub(" |\\(|\\)|\\/","_",colnames(data)[2:ncol(data)])
# We will use this because there might be more than one col for each samples
setnames(data,colnames(data)[2:ncol(data)],
paste0(gsub(" |\\(|\\)|\\/","_",colnames(data)[2:ncol(data)]),"_",cases[i]))
}
if (i == 1) {
df <- data
} else {
df <- merge(df, data, by=colnames(data)[1], all = TRUE)
}
setTxtProgressBar(pb, i)
}
setDF(df)
rownames(df) <- df[,1]
df <- df %>% separate(exon,into = c("seqnames","coordinates","strand"),sep = ":") %>%
separate(coordinates,into = c("start","end"),sep = "-")
if(summarizedExperiment) {
suppressWarnings({
assays <- lapply(assay.list, function (x) {
return(data.matrix(subset(df, select = grep(x,colnames(df),ignore.case = TRUE))))
})
})
names(assays) <- assay.list
regex <- paste0(
"[:alnum:]{4}-[:alnum:]{2}-[:alnum:]{4}",
"-[:alnum:]{3}-[:alnum:]{3}-[:alnum:]{4}-[:alnum:]{2}"
)
samples <- na.omit(unique(str_match(colnames(df),regex)[,1]))
colData <- colDataPrepare(samples)
assays <- lapply(assays, function(x){
colnames(x) <- NULL
rownames(x) <- NULL
return(x)
})
rowRanges <- makeGRangesFromDataFrame(df)
message("Available assays in SummarizedExperiment : \n => ",paste(names(assays), collapse = "\n => "))
rse <- SummarizedExperiment(
assays = assays,
rowRanges = rowRanges,
colData = colData
)
return(rse)
}
return(df)
}
readIsoformExpressionQuantification <- function (files, cases){
pb <- txtProgressBar(min = 0, max = length(files), style = 3)
for (i in seq_along(files)) {
data <- fread(files[i], header = TRUE, sep = "\t", stringsAsFactors = FALSE)
if(!missing(cases)) {
assay.list <- gsub(" |\\(|\\)|\\/","_",colnames(data)[2:ncol(data)])
# We will use this because there might be more than one col for each samples
setnames(data,colnames(data)[2:ncol(data)],
paste0(gsub(" |\\(|\\)|\\/","_",colnames(data)[2:ncol(data)]),"_",cases[i]))
}
if (i == 1) {
df <- data
} else {
df <- merge(df, data, by=colnames(data)[1], all = TRUE)
}
setTxtProgressBar(pb, i)
}
setDF(df)
rownames(df) <- df[,1]
df[,1] <- NULL
return(df)
}
readmiRNAIsoformQuantification <- function (files, cases){
pb <- txtProgressBar(min = 0, max = length(files), style = 3)
for (i in seq_along(files)) {
data <- fread(files[i], header = TRUE, sep = "\t", stringsAsFactors = FALSE)
data$barcode <- cases[i]
if (i == 1) {
df <- data
} else {
df <- rbind(df, data)
}
setTxtProgressBar(pb, i)
}
setDF(df)
}
readSimpleNucleotideVariationMaf <- function(files){
ret <- files |>
purrr::map_dfr(.f = function(x) {
tab <- readr::read_tsv(
x,
show_col_types = FALSE,
comment = "#",
col_types = readr::cols(
SOMATIC = col_character(),
PUBMED = col_character(),
miRNA = col_character(),
HGVS_OFFSET = col_integer(),
PHENO = col_character(),
Entrez_Gene_Id = col_integer(),
Start_Position = col_integer(),
End_Position = col_integer(),
t_depth = col_integer(),
t_ref_count = col_integer(),
t_alt_count = col_integer(),
n_depth = col_integer(),
TRANSCRIPT_STRAND = col_integer(),
PICK = col_integer(),
TSL = col_integer(),
Allele = col_character(),
Tumor_Seq_Allele1 = col_character(),
Reference_Allele = col_character(),
Tumor_Seq_Allele2 = col_character(),
DISTANCE = col_integer()
))
# empty MAF file
# https://portal.gdc.cancer.gov/files/7917fcbe-cb66-447d-8ea8-3a324feee3fa
if(nrow(tab) == 0) {return (NULL)}
tab
})
return(ret)
}
read_gene_expression_quantification <- function(
files,
cases,
genome = "hg19",
summarizedExperiment = TRUE,
experimental.strategy,
platform
){
skip <- unique((ifelse(experimental.strategy == "Gene expression array",1,0)))
if(length(skip) > 1) stop("It is not possible to handle those different platforms together")
print.header(paste0("Reading ", length(files)," files"),"subsection")
ret <- plyr::alply(
.data = seq_along(files),
.margins = 1,
.fun = function(i,cases){
data <- fread(
input = files[i],
header = TRUE,
sep = "\t",
stringsAsFactors = FALSE,
skip = skip
)
if(!missing(cases)) {
assay.list <<- gsub(" |\\(|\\)|\\/","_",colnames(data)[2:ncol(data)])
# We will use this because there might be more than one col for each samples
setnames(
data,
colnames(data)[2:ncol(data)],
paste0(gsub(" |\\(|\\)|\\/","_",colnames(data)[2:ncol(data)]),"_",cases[i])
)
}
data
},.progress = "time",cases = cases)
print.header(paste0("Merging ", length(files)," files"),"subsection")
# Just check if the data is in the same order, since we will not merge
# the data frames to save memory
stopifnot(all(unlist(ret %>% map(function(y){all(y[,1] == ret[[1]][,1])}) )))
# need to check if it works in all cases
df <- ret %>% map( ~ (.x %>% dplyr::select(-1))) %>% bind_cols()
df <- bind_cols(ret[[1]][,1],df)
if (summarizedExperiment) {
df <- make_se_from_gene_exoression_quantification(df, assay.list, genome = genome)
} else {
rownames(df) <- df$gene_id
df$gene_id <- NULL
}
return(df)
}
make_se_from_gene_exoression_quantification <- function(
df,
assay.list,
genome = "hg19"
){
# Access genome information to create SE
gene.location <- get.GRCh.bioMart(genome)
if(all(grepl("\\|",df[[1]]))){
aux <- strsplit(df$gene_id,"\\|")
GeneID <- unlist(lapply(aux,function(x) x[2]))
df$entrezgene_id <- as.numeric(GeneID)
gene.location <- gene.location[!duplicated(gene.location$entrezgene_id),]
df <- merge(df, gene.location, by = "entrezgene_id")
} else {
df$external_gene_name <- as.character(df[[1]])
df <- merge(df, gene.location, by = "external_gene_name")
}
if("transcript_id" %in% assay.list){
rowRanges <- GRanges(
seqnames = paste0("chr", df$chromosome_name),
ranges = IRanges(start = df$start_position,
end = df$end_position),
strand = df$strand,
gene_id = df$external_gene_name,
entrezgene = df$entrezgene_id,
ensembl_gene_id = df$ensembl_gene_id,
transcript_id = subset(df, select = 5)
)
names(rowRanges) <- as.character(df$gene_id)
assay.list <- assay.list[which(assay.list != "transcript_id")]
} else {
rowRanges <- GRanges(
seqnames = paste0("chr", df$chromosome_name),
ranges = IRanges(
start = df$start_position,
end = df$end_position
),
strand = df$strand,
gene_id = df$external_gene_name,
entrezgene = df$entrezgene_id,
ensembl_gene_id = df$ensembl_gene_id
)
names(rowRanges) <- as.character(df$external_gene_name)
}
suppressWarnings({
assays <- lapply(assay.list, function(x) {
return(
data.matrix(
subset(df, select = grep(x,colnames(df),ignore.case = TRUE))
)
)
})
})
names(assays) <- assay.list
regex <- paste0("[:alnum:]{4}-[:alnum:]{2}-[:alnum:]{4}",
"-[:alnum:]{3}-[:alnum:]{3}-[:alnum:]{4}-[:alnum:]{2}")
samples <- na.omit(unique(str_match(colnames(df),regex)[,1]))
colData <- colDataPrepare(samples)
assays <- lapply(assays, function(x){
colnames(x) <- NULL
rownames(x) <- NULL
return(x)
})
message("Available assays in SummarizedExperiment : \n => ",paste(names(assays), collapse = "\n => "))
rse <- SummarizedExperiment(
assays = assays,
rowRanges = rowRanges,
colData = colData
)
return(rse)
}
#' @importFrom downloader download
#' @importFrom S4Vectors DataFrame
makeSEFromDNAMethylationMatrix <- function(
betas,
genome = "hg38",
met.platform = c(
"Illumina Human Methylation 450",
"Illumina Human Methylation 27",
"Illumina Methylation Epic"
)
) {
message("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")
message("Creating a SummarizedExperiment from DNA methylation input")
# Instead of looking on the size, it is better to set it as a argument as the annotation is different
annotation <- getMetPlatInfo(platform = met.platform, genome = genome)
rowRanges <- annotation[names(annotation) %in% rownames(betas),,drop = FALSE]
colData <- tryCatch({
colDataPrepare(colnames(betas))
}, error = function(e){
DataFrame(samples = colnames(betas))
})
betas <- betas[rownames(betas) %in% names(rowRanges),,drop = FALSE]
betas <- betas[names(rowRanges),,drop = FALSE]
assay <- data.matrix(betas)
betas <- SummarizedExperiment(
assays = assay,
rowRanges = rowRanges,
colData = colData
)
return(betas)
}
makeSEfromDNAmethylation <- function(df, probeInfo = NULL){
if(is.null(probeInfo)) {
rowRanges <- GRanges(
seqnames = paste0("chr", df$Chromosome),
ranges = IRanges(start = df$Genomic_Coordinate,
end = df$Genomic_Coordinate),
probeID = df$Composite.Element.REF,
Gene_Symbol = df$Gene_Symbol
)
names(rowRanges) <- as.character(df$Composite.Element.REF)
colData <- colDataPrepare(colnames(df)[5:ncol(df)])
assay <- data.matrix(subset(df,select = c(5:ncol(df))))
} else {
rowRanges <- makeGRangesFromDataFrame(probeInfo, keep.extra.columns = TRUE)
colData <- colDataPrepare(colnames(df)[(ncol(probeInfo) + 1):ncol(df)])
assay <- data.matrix(subset(df,select = c((ncol(probeInfo) + 1):ncol(df))))
}
colnames(assay) <- rownames(colData)
rownames(assay) <- as.character(df$Composite.Element.REF)
rse <- SummarizedExperiment(assays = assay, rowRanges = rowRanges, colData = colData)
}
readIDATDNAmethylation <- function(
files,
barcode,
summarizedExperiment,
platform
) {
check_package("sesame")
# Check if moved files would be moved outside of scope folder, if so, path doesn't change
moved.files <- sapply(files,USE.NAMES = FALSE,function(x){
if (grepl("Raw_intensities|Masked_Intensities",dirname(dirname(x)))) {
return(file.path(dirname(dirname(x)), basename(x)))
}
return(x)
})
# for each file move it to upper parent folder if necessary
plyr::a_ply(files, 1,function(x){
if (grepl("Raw_intensities|Masked_Intensities",dirname(dirname(x)))) {
tryCatch(
move(x,
file.path(dirname(dirname(x)), basename(x)),
keep.copy = FALSE
),
error = function(e){
})
}
})
samples <- unique(gsub("_Grn.idat|_Red.idat","",moved.files))
message("Processing IDATs with Sesame - http://bioconductor.org/packages/sesame/")
message("Running opensesame - applying quality masking and nondetection masking (threshold P-value 0.05)")
message("Please cite: doi: 10.1093/nar/gky691 and 10.1093/nar/gkt090")
message("This might take a while....")
betas <- sesame::openSesame(samples) %>% as.matrix
barcode <- unique(data.frame("file" = gsub("_Grn.idat|_Red.idat","",basename(moved.files)), "barcode" = barcode))
colnames(betas) <- barcode$barcode[match(basename(samples),barcode$file)]
if (summarizedExperiment) {
betas <- makeSEFromDNAMethylationMatrix(
betas = betas,
genome ="hg38",
met.platform = platform
)
colData(betas) <- DataFrame(colDataPrepare(colnames(betas)))
}
return(betas)
}
# We will try to make this function easier to use this function in its own data
# In case it is not TCGA I should not consider that there is a barcode in the header
# Instead the user should be able to add the names to his data
# The only problem is that the data from the user will not have all the columns
# TODO: Improve this function to be more generic as possible
#' @importFrom GenomicRanges makeGRangesFromDataFrame
#' @importFrom tibble as_data_frame
#' @importFrom data.table fread
readDNAmethylation <- function(
files,
cases,
summarizedExperiment = TRUE,
platform
){
if(length(platform) > 1){
print(knitr::kable(platform))
stop("More than one DNA methylation platform found. Only one is accepted")
}
if (missing(cases)) cases <- NULL
if (grepl("OMA00",platform)) {
pb <- txtProgressBar(min = 0, max = length(files), style = 3)
for (i in seq_along(files)) {
data <- fread(
files[i],
header = TRUE,
sep = "\t",
stringsAsFactors = FALSE,
skip = 1,
na.strings = "N/A",
colClasses = c(
"character", # Composite Element REF
"numeric" # # beta value
)
)
setnames(data,gsub(" ", "\\.", colnames(data)))
if (!is.null(cases)) setnames(data,2,cases[i])
if (i == 1) {
df <- data
} else {
df <- merge(df, data, by = "Composite.Element.REF")
}
setTxtProgressBar(pb, i)
}
setDF(df)
rownames(df) <- df$Composite.Element.REF
df$Composite.Element.REF <- NULL
} else if (all(grepl("methylation_array.sesame.level3betas", files))){
# methylation_array.sesame.level3betas has only two columns with not header
print.header(paste0("Reading ", length(files)," files"),"subsection")
x <- plyr::alply(files,1, function(f) {
data <- fread(
f,
header = FALSE,
sep = "\t",
stringsAsFactors = FALSE,
skip = 0,
colClasses = c(
"character", # CpG
"numeric" # beta value
)
)
setnames(data,gsub(" ", "\\.", colnames(data)))
if (!is.null(cases)) setnames(data,2,cases[which(f == files)])
}, .progress = "time")
print.header(paste0("Merging ", length(files)," files"),"subsection")
# Just check if the data is in the same order, since we will not merge
# the data frames to save memory
# C3N-01362-01 has less probes than C3L-00913-03 due to version of the array
# CPTAC cohort: 55 samples with EPIC v1 and 1808 with EPIC V2
# EPIC v1 has less probes than EPIC V2
# In case we have multiple versions of the array we will
# 1. Check the names of all of the same nrow
# 2. Bind the ones with same nrow
# 3. Full join the two objects
nrow_vec <- purrr::map_int(x,nrow) # number of rows each file
nrow_vec_numbers <- nrow_vec %>% unique # unique number of rows
for(nb_rows in nrow_vec_numbers){
aux <- x[which(nrow_vec == nb_rows)]
stopifnot(all(unlist(aux %>% map(function(y){all(y[,1]$V1 == aux[[1]][,1]$V1)}) )))
}
df <- map(nrow_vec_numbers,.f = function(nb_rows){
file_equal_probes <- x[which(nrow_vec == nb_rows)]
df <- file_equal_probes %>% map_df(2)
colnames(df) <- file_equal_probes %>% map_chr(.f = function(y) colnames(y)[2])
df$V1 <- file_equal_probes[[1]]$V1
if (any(duplicated(colnames(df)))){
message("oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo")
message("Duplicated samples names were found. Adding _rep suffix to name")
message("oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo")
}
colnames(df)[duplicated(colnames(df))] <- paste0(colnames(df)[duplicated(colnames(df))],"_rep")
df
}) %>% purrr::reduce(dplyr::full_join,by = "V1") %>% as.data.frame()
rownames(df) <- df$V1
df$V1 <- NULL
df <- data.matrix(df)
if (summarizedExperiment) {
df <- makeSEFromDNAMethylationMatrix(
betas = df,
genome = "hg38",
met.platform = platform
)
}
} else {
skip <- ifelse(all(grepl("hg38",files)), 0,1)
colClasses <- NULL
if (!all(grepl("hg38",files))) {
colClasses <- c(
"character", # Composite Element REF
"numeric", # beta value
"character", # Gene symbol
"character", # Chromosome
"integer"
)
}
x <- plyr::alply(files,1, function(f) {
data <- fread(
f,
header = TRUE,
sep = "\t",
stringsAsFactors = FALSE,
skip = skip,
colClasses = colClasses
)
setnames(data,gsub(" ", "\\.", colnames(data)))
if (!is.null(cases)) setnames(data,2,cases[which(f == files)])
setcolorder(data,c(1, 3:ncol(data), 2))
}, .progress = "time")
print.header(paste0("Merging ", length(files)," files"),"subsection")
# Just check if the data is in the same order, since we will not merge
# the data frames to save memory
stopifnot(all(unlist(x %>% map(function(y){all(y[,1] == x[[1]][,1])}) )))
# if hg38 we have 10 columns with probe metadata
# if hg19 we have 4 columns with probe metadata
idx.dnam <- grep("TCGA",colnames(x[[1]]))
df <- x %>% map_df(idx.dnam)
colnames(df) <- x %>% map_chr(.f = function(y) colnames(y)[idx.dnam])
df <- bind_cols(x[[1]][,1:(idx.dnam-1)],df)
if (summarizedExperiment) {
if(skip == 0) {
df <- makeSEfromDNAmethylation(
df,
probeInfo = data.frame(df)[,grep("TCGA",colnames(df),invert = TRUE)]
)
} else {
df <- makeSEfromDNAmethylation(df)
}
} else {
setDF(df)
rownames(df) <- df$Composite.Element.REF
df$Composite.Element.REF <- NULL
}
}
return(df)
}
# Barcode example MMRF_1358_1_BM_CD138pos_T1_TSMRU_L02337
colDataPrepareMMRF <- function(
barcode
){
DataFrame(
barcode = barcode,
sample = barcode,
patient = substr(barcode,1,9)
)
}
colDataPrepareTARGET <- function(
barcode
){
message("Adding description to TARGET samples")
tissue.code <- c(
'01',
'02',
'03',
'04',
'05',
'06',
'07',
'08',
'09',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'17',
'20',
'40',
'41',
'42',
'50',
'60',