-
Notifications
You must be signed in to change notification settings - Fork 0
/
Module_A.R
3324 lines (3260 loc) · 156 KB
/
Module_A.R
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
# =============================================================================
# TCGA-Assembler version 2
#
# Copyright (C) <2017> <Yitan Zhu>
# This file is part of TCGA-Assembler.
#
# TCGA-Assembler is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# TCGA-Assembler is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with TCGA-Assembler. If not, see <http://www.gnu.org/licenses/>.
# =============================================================================
# =============================================================================
# TCGA-Assembler Version 2 Module A
# =============================================================================
# =============================================================================
# variable prefix example
# =============================================================================
# s : string
# n : number
# v : vector
# d : data.frame
# m : matrix
# l : list
# lv : list of vector
# ld : list of data.frame
# =============================================================================
# internal functions, NOT used directly by user
# =============================================================================
#' Get fields names of GDC entities
#'
#' @param arch String of archive type: "legacy" or "".
#' @param endp String of endpoint: "files".
#' @return Character vector of all available field names.
#' @examples
#' fieldsList <- FieldsList("legacy")
#' fieldsList <- FieldsList("")
FieldsList <- function(arch = "legacy",
endp = "files") {
library(rjson)
#url <- paste("https://gdc-api.nci.nih.gov/",
url <- paste("https://api.gdc.cancer.gov/",
arch,
ifelse(arch == "", "", "/"),
endp,
"/_mapping",
sep = "")
opt <- "--silent --show-error"
arg <- paste(opt, url)
jsn <- paste(system2("curl", arg, stdout = T), collapse = "")
return(fromJSON(jsn)$fields)
}
#' Define the default fields used in metadata file
#'
#' @return Character vector of selected fields names for metadata.
FieldsMeta <- function() {
return(c(# "access",
"archive.file_name",
# "cases.case_id",
"cases.project.project_id",
"cases.samples.portions.analytes.aliquots.submitter_id", # 1st
# "cases.samples.portions.analytes.submitter_id",
"cases.samples.portions.submitter_id", # 2nd
"cases.samples.sample_type",
"cases.samples.sample_type_id", # sprintf("%02d", c(seq(14), 20, 40, 50, 60, 61))
"data_category",
"data_type",
"experimental_strategy",
"file_id",
"file_name",
"file_size",
# "md5sum",
"platform",
"updated_datetime"))
}
#' Get count of GDC entities in /archive/endpoint
#'
#' @param arch String of archive type: "legacy" or "".
#' @param endp String of endpoint: "files".
#' @return Count of entities in specified archive & endpoint.
#' @examples
#' entityCount <- EntityCount("legacy")
#' entityCount <- EntityCount("")
EntityCount <- function(arch = "legacy",
endp = "files") {
library(rjson)
#url <- paste("https://gdc-api.nci.nih.gov/",
url <- paste("https://api.gdc.cancer.gov/",
arch,
ifelse(arch == "", "", "/"),
endp,
sep = "")
opt <- "--silent --show-error"
arg <- paste(opt, url)
jsn <- paste(system2("curl", arg, stdout = T), collapse = "")
# stopifnot(length(fromJSON(jsn)$warnings) == 0)
return(fromJSON(jsn)$data$pagination$total)
}
#' Get a string of current time (YYYYMMDDhhmmss)
#'
#' @return String of current time (YYYYMMDDhhmmss).
#' @examples
#' TimeNow()
TimeNow <- function() {
return(gsub("[- :]", "", as.character(Sys.time())))
}
#' Get index of the entity with newest archive file version
#'
#' @param archiveNames Character vector of "archive.file_name". All of
#' these entities have same "file_name".
#' @return Index of the newest one.
#' @examples
#' v <- c("mdanderson.org_BRCA.MDA_RPPA_Core.Level_3.114.1.0.tar.gz",
#' "mdanderson.org_BRCA.MDA_RPPA_Core.Level_3.2.1.0.tar.gz",
#' "mdanderson.org_BRCA.MDA_RPPA_Core.Level_3.10.1.0.tar.gz")
#' n <- ArchiveNewest(v)
ArchiveNewest <- function(archiveNames) {
m <- sapply(strsplit(archiveNames, split = "\\."),
function(x){rev(x)[5 : 3]})
mode(m) <- "numeric" # OR class(m) <- "numeric"
vOrder <- do.call(order, lapply(seq(nrow(m)), function(x){m[x, ]}))
return(vOrder[length(vOrder)])
}
#' Get vector of bool indicate the one with newest archive file version or not
#' in one group
#'
#' @param archiveNames Character vector of "archive.file_name". All of
#' these entities have same "file_name".
#' @return Bool vector to indicate the newest one in one group
ArchiveNewestInGroup <- function(archiveNames) {
b <- seq(length(archiveNames)) == ArchiveNewest(archiveNames)
return(ifelse(b, T, F))
}
#' Get vector of bool indicate the one with newest archive file version or not
#' in every group
#'
#' @param archiveNames Character vector of "archive.file_name", could be
#' split into groups, each group with a unique "file_name".
#' @param splitFactor Character vector of "file_name" (sorted).
#' @return Bool vector to indicate the newest one in every group.
ArchiveNewestInGroups <- function(archiveNames,
splitFactor) {
stopifnot(all(splitFactor == splitFactor[order(splitFactor)])) # splitFactor should be sorted before split
return(unlist(lapply(split(archiveNames, splitFactor),
ArchiveNewestInGroup)))
}
#' Choose columns from a file
#'
#' @param fileName String of filename.
#' @param fileId String of fileId with same length of fileName.
#' @param colNames Character vector of colname, specify the columns choosed.
#' @param sortBy Name one column which acts as the rownames.
#' @param skipLines Number of lines skipped in \code{read.csv}.
#' @param naStrings String indicating the \code{NA} in \code{read.csv}.
#' @return A \code{data.frame} with specified columns from one file.
ColumnsFromFile <- function(fileName,
fileId,
colNames,
sortBy = "",
skipLines = 0,
naStrings) {
d <- read.csv(fileName,
sep = "\t",
row.names = NULL,
as.is = T,
skip = skipLines,
na.strings = naStrings)
if (sortBy != "") {
if (length(d[, sortBy]) != length(unique(d[, sortBy]))) { # probe duplicated, check same value for each probe group
stopifnot(all(tapply(Reduce(paste, d[, colNames]), d[, sortBy],
function(x){length(unique(x)) == 1})))
d <- d[!duplicated(d[, sortBy]), ]
}
stopifnot(length(d[, sortBy]) == length(unique(d[, sortBy])))
rownames(d) <- d[, sortBy]
d <- d[order(d[, sortBy]), colNames]
} else {
d <- cbind("fileId" = rep(fileId, dim(d)[1]), d[, colNames])
}
return(d)
}
#' Choose columns from each file of filenames
#'
#' @param fileName String of filename, named with file_id.
#' @param colNames Character vector of colname, specify the columns choosed.
#' @param sortBy Name one column which acts as the rownames.
#' @param skipLines Number of lines skipped in \code{read.csv}.
#' @param naStrings String indicating the \code{NA} in \code{read.csv}.
#' @return List of \code{data.frame} with specified columns from each file.
ColumnsFromFiles <- function(fileNameById,
colNames,
sortBy = "",
skipLines = 0,
naStrings = "NA") {
l <- lapply(names(fileNameById),
function(x){
ColumnsFromFile(fileNameById[x],
x,
colNames,
sortBy,
skipLines,
naStrings)
})
names(l) <- names(fileNameById)
return(l)
}
#' Strip characters at left or right end of each string in a vector
#'
#' @param vUnstripped Character vector of unstripped strings.
#' @param stripNum Number of characters need to be stripped.
#' @param stripEnd Sting indicating the terminal: "right" or "left".
#' @return Character vector of stripped strings.
StripEnd <- function(vUnstripped,
stripNum,
stripEnd = "right") {
if (stripNum == 0) {
vStripped <- vUnstripped
} else {
if (stripEnd %in% c("r", "right")) {
vStripped <- sapply(strsplit(vUnstripped, split = ""),
function(x){
paste(x[-((length(x) - stripNum + 1) : length(x))],
collapse = "")
})
} else if (stripEnd %in% c("l", "left")) {
vStripped <- sapply(strsplit(vUnstripped, split = ""),
function(x){
paste(x[-(1 : stripNum)], collapse = "")
})
} else {
print("stripEnd should be one of 'right', 'r', 'l' or 'left'")
}
}
return(vStripped)
}
#' Make a vector of values named with probes
#'
#' @param dProbeValue A \code{data.frame}, usually read from filename.
#' @param colProbe String of column name of probe, used as name.
#' @param colValue String of column name of value.
#' @param stripNum Number of characters need to be stripped from "probe".
#' @param stripEnd Sting indicating the terminal: "right" or "left".
#' @return Named vector.
ProbeValue <- function(dProbeValue,
colProbe,
colValue,
stripNum = 0,
stripEnd = "right") {
v <- dProbeValue[, colValue]
names(v) <- StripEnd(dProbeValue[, colProbe], stripNum, stripEnd)
return(v)
}
#' Cut the "*\\.1\\.*" columns and rows with \code{NA} only
#'
#' @param metaData A \code{data.frame} read from metadata file.
#' @param colPattern String of regular expression pattern to filter colname.
#' @return A \code{data.frame} after cutting.
MetaCut <- function(metaData,
colPattern = "\\.1\\.") {
colIdx <- grep(colPattern, colnames(metaData))
rowIdx <- sapply(seq(dim(metaData)[1]),
function(x){
ifelse(all(is.na(metaData[x, colIdx])), T, F)
})
metaCut <- metaData[rowIdx, seq(dim(metaData)[2])[-colIdx]]
return(metaCut)
}
#' Define the filters with specified assay platform
#'
#' @param sAssay String of assay platform.
#' @return List of filter.
#' @example
#' filter <- Filter("methylation_450")
Filter <- function(sAssay) {
filter <- list()
vAssay <- c(# Copy number segmentation
"cna_cnv.hg18",
"cna_cnv.hg19",
"cna_nocnv.hg18",
"cna_nocnv.hg19",
# Exon junction quantification
"exonJunction_RNAseq",
"exonJunction_TotalRNAseq",
# Exon quantification
"exon_RNAseq",
"exon_TotalRNAseq",
# Gene expression quantification
"gene_Array",
"gene.normalized_RNAseq",
"gene_RNAseq",
"gene.normalized_TotalRNAseq",
"gene_TotalRNAseq",
# Isoform expression quantification
"isoform.normalized_RNAseq",
"isoform_RNAseq",
"isoform.normalized_TotalRNAseq",
"isoform_TotalRNAseq",
# Methylation beta value
"methylation_27",
"methylation_450",
# miRNA gene quantification
"mir_GA.hg18",
"mir_GA.hg19",
"mir_GA.hg19.mirbase20",
# miRNA gene quantification
"mir_HiSeq.hg18",
"mir_HiSeq.hg19",
"mir_HiSeq.hg19.mirbase20",
# miRNA isoform quantification
"mirIsoform_GA.hg18",
"mirIsoform_GA.hg19",
"mirIsoform_GA.hg19.mirbase20",
# miRNA isoform quantification
"mirIsoform_HiSeq.hg18",
"mirIsoform_HiSeq.hg19",
"mirIsoform_HiSeq.hg19.mirbase20",
# Protein expression quantification
"protein_RPPA",
# Simple somatic mutation
"somaticMutation_DNAseq",
# CPTAC
"glycoproteome_iTRAQ",
"phosphoproteome_iTRAQ",
"proteome_iTRAQ")
if (!sAssay %in% vAssay) { # assayPlatform = sAssay
print(paste(c("assayPlatform should be one of:", vAssay), collapse = " "))
} else if (sAssay == "cna_cnv.hg18") {
filter$data_category <- c("Copy number variation")
filter$data_type <- c("Copy number segmentation")
filter$experimental_strategy <- "Genotyping array"
filter$platform <- "Affymetrix SNP Array 6.0"
filter$file_name <- "\\.hg18\\.seg\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "cna_cnv.hg19") {
filter$data_category <- c("Copy number variation")
filter$data_type <- c("Copy number segmentation")
filter$experimental_strategy <- "Genotyping array"
filter$platform <- "Affymetrix SNP Array 6.0"
filter$file_name <- "\\.hg19\\.seg\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "cna_nocnv.hg18") {
filter$data_category <- c("Copy number variation")
filter$data_type <- c("Copy number segmentation")
filter$experimental_strategy <- "Genotyping array"
filter$platform <- "Affymetrix SNP Array 6.0"
filter$file_name <- "\\.nocnv_hg18\\.seg\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "cna_nocnv.hg19") {
filter$data_category <- c("Copy number variation")
filter$data_type <- c("Copy number segmentation")
filter$experimental_strategy <- "Genotyping array"
filter$platform <- "Affymetrix SNP Array 6.0"
filter$file_name <- "\\.nocnv_hg19\\.seg\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "exon_RNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Exon quantification"
filter$experimental_strategy <- "RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.bt\\.exon_quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "exon_TotalRNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Exon quantification"
filter$experimental_strategy <- "Total RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.bt\\.exon_quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "exonJunction_RNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Exon junction quantification"
filter$experimental_strategy <- "RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.junction_quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "exonJunction_TotalRNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Exon junction quantification"
filter$experimental_strategy <- "Total RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.junction_quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "gene_Array") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Gene expression quantification"
filter$experimental_strategy <- "Gene expression array"
filter$platform <- "AgilentG4502A_07_3"
filter$file_name <- "\\.txt_lmean\\.out\\.logratio\\.gene\\.tcga_level3\\.data\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "gene.normalized_RNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Gene expression quantification"
filter$experimental_strategy <- "RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.rsem\\.genes\\.normalized_results"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "gene_RNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Gene expression quantification"
filter$experimental_strategy <- "RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.rsem\\.genes\\.results"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "gene.normalized_TotalRNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Gene expression quantification"
filter$experimental_strategy <- "Total RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.rsem\\.genes\\.normalized_results"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "gene_TotalRNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Gene expression quantification"
filter$experimental_strategy <- "Total RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.rsem\\.genes\\.results"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "isoform.normalized_RNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Isoform expression quantification"
filter$experimental_strategy <- "RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.rsem\\.isoforms\\.normalized_results"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "isoform_RNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Isoform expression quantification"
filter$experimental_strategy <- "RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.rsem\\.isoforms\\.results"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "isoform.normalized_TotalRNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Isoform expression quantification"
filter$experimental_strategy <- "Total RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.rsem\\.isoforms\\.normalized_results"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "isoform_TotalRNAseq") {
filter$data_category <- c("Gene expression")
filter$data_type <- "Isoform expression quantification"
filter$experimental_strategy <- "Total RNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "\\.rsem\\.isoforms\\.results"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mir_GA.hg18") {
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA gene quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina GA"
filter$file_name <- "^[^\\.]*\\.mirna\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mir_GA.hg19") {
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA gene quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina GA"
filter$file_name <- "^[^\\.]*\\.hg19\\.mirna\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mir_GA.hg19.mirbase20") {
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA gene quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina GA"
filter$file_name <- "^[^\\.]*\\.hg19\\.mirbase20\\.mirna\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mir_HiSeq.hg18") {
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA gene quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "^[^\\.]*\\.mirna\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mir_HiSeq.hg19") {
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA gene quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "^[^\\.]*\\.hg19\\.mirna\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mir_HiSeq.hg19.mirbase20") {
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA gene quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "^[^\\.]*\\.hg19\\.mirbase20\\.mirna\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mirIsoform_GA.hg18") { # rows different
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA isoform quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina GA"
filter$file_name <- "^[^\\.]*\\.isoform\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mirIsoform_GA.hg19") { # rows different
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA isoform quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina GA"
filter$file_name <- "^[^\\.]*\\.hg19\\.isoform\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mirIsoform_GA.hg19.mirbase20") { # rows different
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA isoform quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina GA"
filter$file_name <- "^[^\\.]*\\.hg19\\.mirbase20\\.isoform\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mirIsoform_HiSeq.hg18") { # rows different
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA isoform quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "^[^\\.]*\\.isoform\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mirIsoform_HiSeq.hg19") { # rows different
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA isoform quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "^[^\\.]*\\.hg19\\.isoform\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "mirIsoform_HiSeq.hg19.mirbase20") { # rows different
filter$data_category <- c("Gene expression")
filter$data_type <- "miRNA isoform quantification"
filter$experimental_strategy <- "miRNA-Seq"
filter$platform <- "Illumina HiSeq"
filter$file_name <- "^[^\\.]*\\.hg19\\.mirbase20\\.isoform\\.quantification\\.txt"
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "methylation_27") {
filter$data_category <- "DNA methylation"
filter$data_type <- "Methylation beta value"
filter$experimental_strategy <- "Methylation array"
filter$platform <- "Illumina Human Methylation 27"
filter$file_name <- "jhu-usc\\.edu_.*\\.HumanMethylation27\\."
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "methylation_450") {
filter$data_category <- "DNA methylation"
filter$data_type <- "Methylation beta value"
filter$experimental_strategy <- "Methylation array"
filter$platform <- "Illumina Human Methylation 450"
filter$file_name <- "jhu-usc\\.edu_.*\\.HumanMethylation450\\."
filter$submitter_id <- "cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id"
} else if (sAssay == "protein_RPPA") { # differnt "archive.file_name"
filter$data_category <- "Protein expression"
filter$data_type <- "Protein expression quantification"
filter$experimental_strategy <- "Protein expression array"
filter$platform <- "MDA_RPPA_Core"
filter$file_name <-
"mdanderson\\.org_.*\\.MDA_RPPA_Core\\.protein_expression\\.Level_3\\."
filter$submitter_id <- "cases.0.samples.0.portions.0.submitter_id"
} else if (sAssay == "somaticMutation_DNAseq") {
filter$data_category <- "Simple nucleotide variation"
filter$data_type <- "Simple somatic mutation"
filter$experimental_strategy <- "DNA-Seq"
filter$platform <- c("Illumina GA", "Illumina HiSeq", "Mixed platforms")
filter$file_name <- "\\.somatic\\.maf"
filter$submitter_id <- c("cases.0.samples.0.portions.0.submitter_id", # both exist
"cases.0.samples.0.portions.0.analytes.0.aliquots.0.submitter_id")
} else if (sAssay == "glycoproteome_iTRAQ") { # from CTPAC not GDC
filter$data_category <- NA
filter$data_type <- NA
filter$experimental_strategy <- NA
filter$platform <- "glycoproteome_iTRAQ"
filter$file_name <- "_Glycoproteome\\.glycosite\\.itraq\\.tsv"
filter$submitter_id <- NA
} else if (sAssay == "phosphoproteome_iTRAQ") { # from CTPAC not GDC
filter$data_category <- NA
filter$data_type <- NA
filter$experimental_strategy <- NA
filter$platform <- "phosphoproteome_iTRAQ"
filter$file_name <- "_Phosphoproteome\\.phosphosite\\.itraq\\.tsv"
filter$submitter_id <- NA
} else if (sAssay == "proteome_iTRAQ") { # from CTPAC not GDC
filter$data_category <- NA
filter$data_type <- NA
filter$experimental_strategy <- NA
filter$platform <- "proteome_iTRAQ"
filter$file_name <- "_Proteome.(itraq|spectral_counts|CDAP\\.r2\\.spectral_counts)\\.tsv"
filter$submitter_id <- NA
}
return(filter)
}
#' Get metadata of biospecimen & clinical data files with defined filter
#'
#' @param tmpDir String of directory for temporary files.
#' @param arch String of archive type: "legacy" or "".
#' @param fieldsMeta Character vector of colnames in metadata.
#' @param entityCount Number of entity (row) in the metadata: "-1" means all.
#' @param endp String of endpoint: "files".
#' @return A \code{data.frame} of metadata.
#' @example
#' metadata <- MetaDataClin(tmpDir = ".")
MetaDataClin <- function(tmpDir = ".",
arch = "legacy",
fieldsMeta = "",
entityCount = (-1),
endp = "files") {
library(rjson)
if (entityCount == (-1)) {
entityCount <- EntityCount(arch, endp)
}
if (fieldsMeta == "") {
fieldsMeta <- FieldsMeta()
} else {
fieldsList <- FieldsList(arch, endp)
print("fields names: checking ...")
stopifnot(all(fieldsMeta %in% fieldsList))
print("fields names: checking done!")
}
print("metadata file: preparing ...")
out <- paste(tmpDir, "/tmp_metadata_", endp, ".tsv", sep = "")
#url <- paste('"https://gdc-api.nci.nih.gov/',
url <- paste("https://api.gdc.cancer.gov/",
arch,
ifelse(arch == '', '', '/'), endp,
sep = '')
opt <- paste("-o ", out,
" --silent --show-error --request POST",
" --header Content-Type:application/json --data @",
tmpDir, "/tmp_metadata.json",
sep = "")
arg <- paste(opt, url)
filter2 <- list()
filter2$access <- list(op = "=",
content = list(field = "access", value = "open"))
filter2$data_format <- list(op = "in",
content = list(field = "data_format",
value = "Biotab"))
filterAll <- list(op = "and",
content = list(filter2$access,
filter2$data_format))
payload <- list(filters = filterAll,
format = "TSV",
sort = "file_id",
from = 0,
size = entityCount,
fields = paste(fieldsMeta, collapse = ","))
cat(toJSON(payload), file = paste(tmpDir, "/tmp_metadata.json", sep = ""))
stdOut <- system2("curl", arg, stdout = T)
if (!is.null(attr(stdOut, "status"))) {
print("error (download): check the proxy")
}
stopifnot(is.null(attr(stdOut, "status")))
if ("data" %in% dir()) {file.remove("data")}
metaData <- tryCatch(read.csv(out,
sep = "\t",
row.names = NULL,
as.is = T,
na.strings = ""),
error = function(e){print(e$message); return(NULL)})
if (!is.null(metaData)) { # > 0 lines available in input
if (nrow(metaData) == 0) {
metaData <- NULL
} else {
write.table(metaData,
file = paste(tmpDir,
"/tmp_metadata_clinical__",
arch,
"__",
endp,
".tsv",
sep = ""),
quote = F,
sep = "\t",
col.names = NA,
row.names = T)
}
}
print("metadata file: preparing done!")
return(metaData)
}
#' Get metadata of somatic mutation data files with defined filter
#'
#' @param vCancer String of cancer type.
#' @param sAssay String of assay platform, used in \code{Filter}.
#' @param sampleTypeId Character vector of sample_type_id: "01", ..., "14", etc.
#' @param tmpDir String of directory for temporary files.
#' @param arch String of archive type: "legacy" or "".
#' @param fieldsMeta Character vector of colnames in metadata.
#' @param entityCount Number of entity (row) in the metadata: "-1" means all.
#' @param endp String of endpoint: "files".
#' @return A \code{data.frame} of metadata.
MetaDataSoma <- function(vCancer = "BRCA",
sAssay,
sampleTypeId = sprintf("%02d", c(seq(14), 20, 40, 50, 60, 61)),
tmpDir = ".",
arch = "legacy",
fieldsMeta = "",
entityCount = (-1),
endp = "files") {
library(rjson)
if (entityCount == (-1)) {
entityCount <- EntityCount(arch, endp)
}
if (fieldsMeta == "") {
fieldsMeta <- FieldsMeta()
} else {
fieldsList <- FieldsList(arch, endp)
print("fields names: checking ...")
stopifnot(all(fieldsMeta %in% fieldsList))
print("fields names: checking done!")
}
filter <- Filter(sAssay)
print("metadata file: preparing ...")
out <- paste(tmpDir, "/tmp_metadata_", endp, ".tsv", sep = "")
#url <- paste('"https://gdc-api.nci.nih.gov/',
url <- paste("https://api.gdc.cancer.gov/",
arch,
ifelse(arch == '', '', '/'), endp,
sep = '')
opt <- paste("-o ", out, " --silent --show-error --request POST ",
"--header Content-Type:application/json --data @",
tmpDir, "/tmp_metadata.json", sep = "")
arg <- paste(opt, url)
filter2 <- list()
filter2$access <- list(op = "=" ,
content = list(field = "access",
value = "open"))
filter2$data_format <- list(op = "in",
content = list(field = "data_format",
value = "MAF"))
filter2$project_id <- list(op = "in",
content = list(field = "cases.project.project_id",
value = paste("TCGA", vCancer,
sep = "-")))
filter2$data_category <- list(op = "in",
content = list(field = "data_category",
value = filter$data_category))
filter2$data_type <- list(op = "in",
content = list(field = "data_type",
value = filter$data_type))
filter2$experimental_strategy <- list(op = "in",
content = list(field = "experimental_strategy",
value = filter$experimental_strategy))
filter2$platform <- list(op = "in",
content = list(field = "platform",
value = filter$platform))
filterAll <- list(op = "and",
content = list(filter2$access,
filter2$data_format,
filter2$project_id,
filter2$data_category,
filter2$data_type,
filter2$experimental_strategy,
filter2$platform))
payload <- list(filters = filterAll,
format = "TSV",
sort = "file_id",
from = 0,
size = entityCount,
fields = paste(fieldsMeta, collapse = ","))
cat(toJSON(payload), file = paste(tmpDir, "/tmp_metadata.json", sep = ""))
stdOut <- system2("curl", arg, stdout = T)
if (!is.null(attr(stdOut, "status"))) {
print("error (download): check the proxy")
}
stopifnot(is.null(attr(stdOut, "status")))
if ("data" %in% dir()) {file.remove("data")}
metaData <- tryCatch(read.csv(out,
sep = "\t",
row.names = NULL,
as.is = T,
na.strings = ""),
error = function(e){print(e$message); return(NULL)})
if (!is.null(metaData)) { # > 0 lines available in input
colNames <- c("archive.file_name",
"cases.0.project.project_id",
"data_category",
"data_type",
"experimental_strategy",
"file_id",
"file_name",
"file_size",
"platform",
"updated_datetime")
metaData <- metaData[, colNames]
rownames(metaData) <- metaData[, "file_id"]
write.table(metaData,
file = paste(tmpDir,
"/tmp_metadata_byType__",
arch,
"__",
endp,
"__",
paste(vCancer, collapse = "_"),
"__",
sAssay,
".tsv",
sep = ""),
quote = F,
sep = "\t",
col.names = NA,
row.names = T)
}
print("metadata file: preparing done!")
return(metaData)
}
#' Get metadata of spefified assay platform files with defined filter
#'
#' @param vCancer String of cancer type.
#' @param sAssay String of assay platform, used in \code{Filter}.
#' @param sampleTypeId Character vector of sample_type_id: "01", ..., "14", etc.
#' @param tmpDir String of directory for temporary files.
#' @param arch String of archive type: "legacy" or "".
#' @param fieldsMeta Character vector of colnames in metadata.
#' @param entityCount Number of entity (row) in the metadata: "-1" means all.
#' @param endp String of endpoint: "files".
#' @return A \code{data.frame} of metadata.
#' @example
#' metaData <- function(vCancer = "BRCA",
#' sAssay = "gene_RNAseq",
#' sampleTypeId = sprintf("%02d", c(seq(14), 20, 40, 50, 60, 61)),
#' tmpDir = ".",
#' arch = "legacy",
#' fieldsMeta = "",
#' entityCount = (-1),
#' endp = "files")
MetaData <- function(vCancer = "BRCA",
sAssay,
sampleTypeId = sprintf("%02d", c(seq(14), 20, 40, 50, 60, 61)),
tmpDir = ".",
arch = "legacy",
fieldsMeta = "",
entityCount = (-1),
endp = "files") {
library(rjson)
if (entityCount == (-1)) {
entityCount <- EntityCount(arch, endp)
}
if (fieldsMeta == "") {
fieldsMeta <- FieldsMeta()
} else {
fieldsList <- FieldsList(arch, endp)
print("fields names: checking ...")
stopifnot(all(fieldsMeta %in% fieldsList))
print("fields names: checking done!")
}
filter <- Filter(sAssay)
print("metadata file: preparing ...")
out <- paste(tmpDir, "/tmp_metadata_", endp, ".tsv", sep = "")
#url <- paste('"https://gdc-api.nci.nih.gov/',
url <- paste("https://api.gdc.cancer.gov/",
arch,
ifelse(arch == '', '', '/'), endp,
sep = '')
opt <- paste("-o ", out,
" --silent --show-error --request POST",
" --header Content-Type:application/json --data @",
tmpDir, "/tmp_metadata.json",
sep = "")
arg <- paste(opt, url)
filter2 <- list()
filter2$access <- list(op = "=" ,
content = list(field = "access",
value = "open"))
filter2$data_format <- list(op = "in",
content = list(field = "data_format",
value = "TXT"))
filter2$project_id <- list(op = "in",
content = list(field = "cases.project.project_id",
value = paste("TCGA", vCancer,
sep = "-")))
filter2$data_category <- list(op = "in",
content = list(field = "data_category",
value = filter$data_category))
filter2$data_type <- list(op = "in",
content = list(field = "data_type",
value = filter$data_type))
filter2$experimental_strategy <- list(op = "in",
content = list(field = "experimental_strategy",
value = filter$experimental_strategy))
filter2$platform <- list(op = "in",
content = list(field = "platform",
value = filter$platform))
names(sampleTypeId) <- NULL # avoid names added into tmp_metadata.json
fieldSampleTypeId <- "cases.samples.sample_type_id"
filterSampleTypeId <- list(op = "in",
content = list(field = fieldSampleTypeId,
value = sampleTypeId))
filterAll <- list(op = "and",
content = list(filter2$access,
filter2$data_format,
filter2$project_id,
filter2$data_category,
filter2$data_type,
filter2$experimental_strategy,
filter2$platform,
filterSampleTypeId))
payload <- list(filters = filterAll,
format = "TSV",
sort = "file_id",
from = 0,
size = entityCount,
fields = paste(fieldsMeta, collapse = ","))
cat(toJSON(payload), file = paste(tmpDir, "/tmp_metadata.json", sep = ""))
stdOut <- system2("curl", arg, stdout = T)
if (!is.null(attr(stdOut, "status"))) {
print("error (download): check the proxy")
}
stopifnot(is.null(attr(stdOut, "status")))
if ("data" %in% dir()) {file.remove("data")}
metaData <- tryCatch(read.csv(out,
sep = "\t",
row.names = NULL,
as.is = T,
na.strings = "",
colClasses = "character"),
error = function(e){print(e$message); return(NULL)})
if (!is.null(metaData)) { # > 0 lines available in input
if (length(grep("\\.1\\.", colnames(metaData))) > 0) {
metaData <- MetaCut(metaData, colPattern = "\\.1\\.")
}
metaCut <- metaData[grep(filter$file_name, metaData$file_name),
sort(colnames(metaData))] # filter with filename
if (nrow(metaCut) == 0) {
metaData <- NULL
} else {
metaCut <- metaCut[order(metaCut$file_name), ] # sort before split !!
if (any(table(metaCut[, filter$submitter_id]) != 1)) { # duplicated files with same barcode
boolRow <- ArchiveNewestInGroups(metaCut$archive.file_name,
metaCut$file_name)
# not filter$submitter_id because of one barcode to multi files
metaCut <- metaCut[boolRow, ]
}
stopifnot(all(table(metaCut[, filter$submitter_id]) == 1)) # duplicated files with same barcode
rownames(metaCut) <- metaCut[, filter$submitter_id]
metaData <- metaCut[order(rownames(metaCut)), order(colnames(metaCut))] # sort by barcode
stopifnot(all(rownames(metaData) == metaData[filter$submitter_id]))
write.table(metaData,
file = paste(tmpDir,
"/tmp_metadata_byType__",
arch,
"__",
endp,
"__",
paste(vCancer, collapse = "_"),
"__",
sAssay,
".tsv",
sep = ""),
quote = F, sep = "\t", col.names = NA, row.names = T)
}
}
print("metadata file: preparing done!")
return(metaData)
}
#' Download files by \code{file_id}
#'
#' @param fileId2Bar Character vector of barcode with file_id as the name.
#' @param tmpDir String of directory for temporary files.
#' @param arch String of archive type: "legacy" or "".
#' @return Character vector of downloaded filename with file_id as the name.
#' @example
#' fileNameById <- FileNameById(metaData$file_id, tmpDir = ".")
FileNameById <- function(fileId2Bar,
tmpDir = ".",
arch = "legacy") {
if (length(fileId2Bar) == 0) { # no files available for this filter
fileNameById <- NULL
} else {
stopifnot(length(fileId2Bar) > 0) # no files available for this filter
library(rjson)
tmpTar <- paste(tmpDir, "/gdc_download_", TimeNow(), ".tar.gz", sep = "")
#url <- paste("https://gdc-api.nci.nih.gov/",
url <- paste("https://api.gdc.cancer.gov/",
arch,
ifelse(arch == "", "", "/"),
"data",