forked from kellrott/tcgaImport
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tcgaImport.py
executable file
·1797 lines (1561 loc) · 68.4 KB
/
tcgaImport.py
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
#!/usr/bin/env python
"""
Script to scan and extract TCGA data and compile it into coherent matrices
"""
from xml.dom.minidom import parseString
import urllib
import time
import os
import csv
import sys
import hashlib
import tempfile
import re
import random
import json
import datetime
import hashlib
import subprocess
from glob import glob
import shutil
import subprocess
import logging
from argparse import ArgumentParser
from urlparse import urlparse
import pandas as pd
import string
"""
Net query code
"""
class dccwsItem(object):
baseURL = "http://tcga-data.nci.nih.gov/tcgadccws/GetXML?query="
def __init__(self):
self.url = None
def __iter__(self):
next = self.url
while next != None:
retry_count = 3
while retry_count > 0:
try:
data = None
handle = urllib.urlopen(next)
data = handle.read()
handle.close()
dom = parseString(data)
retry_count = 0
except Exception, e:
retry_count -= 1
if retry_count <= 0:
sys.stderr.write("URL %s : Message Error: %s\n" % (next, data ) )
raise e
time.sleep(random.randint(10, 35))
# there might not be any archives for a dataset
if len(dom.getElementsByTagName('queryResponse')) > 0:
response = dom.getElementsByTagName('queryResponse').pop()
classList = response.getElementsByTagName('class')
for cls in classList:
className = cls.getAttribute("recordNumber")
outData = {}
#aObj = Archive()
for node in cls.childNodes:
nodeName = node.getAttribute("name")
if node.hasAttribute("xlink:href"):
outData[ nodeName ] = node.getAttribute("xlink:href")
else:
outData[ nodeName ] = getText( node.childNodes )
yield outData
if len( dom.getElementsByTagName('next') ) > 0:
nextElm = dom.getElementsByTagName('next').pop()
next = nextElm.getAttribute( 'xlink:href' )
else:
next = None
class CustomQuery(dccwsItem):
def __init__(self, query):
super(CustomQuery, self).__init__()
if query.startswith("http://"):
self.url = query
else:
self.url = dccwsItem.baseURL + query
"""
Build Configuration
"""
class BuildConf:
def __init__(self, platform, name, version, meta, tarlist):
self.platform = platform
self.name = name
self.version = version
self.meta = meta
self.tarlist = tarlist
self.abbr = ''
self.uuid_table = None
if 'annotations' in meta and 'acronym' in meta['annotations']:
self.abbr = meta['annotations']['acronym']
def addOptions(self, opts):
self.workdir_base = opts.workdir_base
self.outdir = opts.outdir
self.sanitize = opts.sanitize
self.mirror = opts.mirror
self.outpath = opts.outpath
self.download = opts.download
self.metapath = opts.metapath
self.errorpath = opts.errorpath
self.clinical_type = opts.clinical_type
self.rmControl = opts.rmControl
self.clinical_type_map = {}
for t, path, meta in opts.out_clinical:
self.clinical_type_map[ "." + t] = (path, meta)
if opts.uuid_table is not None:
self.uuid_table = {}
handle = open(opts.uuid_table)
for line in handle:
tmp = line.rstrip().split("\t")
self.uuid_table[tmp[0]] = tmp[1]
def getURLPath(self, url):
if self.mirror is None:
print "Define mirror location"
sys.exit(1)
src = url # "https://tcga-data.nci.nih.gov/" + url
path = urlparse(url).path
dst = os.path.join(self.mirror, re.sub("^/", "", path))
dir = os.path.dirname(dst)
if not os.path.exists(dir):
print "mkdir", dir
os.makedirs(dir)
if not os.path.exists( dst ):
if self.download:
print "download %s to %s" % (src, dst)
urllib.urlretrieve(src, dst)
else:
raise Exception("Missing source file: %s" % url)
return dst
def buildRequest(self):
return self.meta
def translateUUID(self, uuid):
if self.uuid_table is None or uuid not in self.uuid_table:
return uuid
return self.uuid_table[uuid]
def getOutPath(self, nameGen):
"""
if self.outpath is not None:
return self.outpath
if name in self.clinical_type_map:
return self.clinical_type_map[name][0]
if not os.path.exists(self.outdir):
os.makedirs(self.outdir)
"""
return os.path.join(self.outdir, nameGen(self.name))
def getOutMeta(self, nameGen):
"""
if self.outpath is not None:
if self.metapath is not None:
return self.metapath
return self.outpath + ".json"
if name in self.clinical_type_map:
return self.clinical_type_map[name][1]
"""
return os.path.join(self.outdir, nameGen(self.name)) + ".json"
def getOutError(self, name):
if self.outpath is not None:
if self.errorpath is not None:
return self.errorpath
return self.outpath + ".error"
return os.path.join(self.outdir, self.name) + name + ".error"
def getBaseBuildConf(basename, platform, mirror):
dates = []
logging.debug("TCGA Query for: %s" % (basename))
q = tcgaConfig[platform].getArchiveQuery(basename)
urls = {}
meta = None
platform = None
for e in q:
dates.append( datetime.datetime.strptime( e['addedDate'], "%m-%d-%Y" ) )
if meta is None:
meta = {
#'name' : basename,
'annotations' : {'species' : 'Homo sapiens', 'disease' : 'cancer'},
'provenance' : { 'name' : 'tcgaImport', 'used' : [] }
}
for e2 in CustomQuery(e['platform']):
platform = e2['name']
meta['annotations']['platform'] = e2['name']
meta['annotations']['platformTitle'] = e2['displayName']
for e2 in CustomQuery(e['disease']):
meta['annotations']['acronym'] = e2['abbreviation']
meta['annotations']['diseaseTitle'] = e2['name']
for e3 in CustomQuery(e2['tissueCollection']):
meta['annotations']['tissue'] = e3['name']
for e2 in CustomQuery(e['center']):
meta['annotations']['centerTitle'] = e2['displayName']
meta['annotations']['center'] = e2['name']
meta['annotations']['basename'] = basename
meta['provenance']['used'].append(
{
'url' : "https://tcga-data.nci.nih.gov" + e['deployLocation'],
"concreteType": "org.sagebionetworks.repo.model.provenance.UsedURL"
}
)
urls[ mirror + e['deployLocation'] ] = platform
logging.debug("TCGA Query for mage-tab: %s" % (basename))
q = CustomQuery("Archive[@baseName=%s][@isLatest=1][ArchiveType[@type=mage-tab]]" % (basename))
for e in q:
dates.append( datetime.datetime.strptime( e['addedDate'], "%m-%d-%Y" ) )
q2 = CustomQuery(e['platform'])
platform = None
for e2 in q2:
logging.debug("%s" % (e2))
platform = e2['name']
meta['provenance']['used'].append(
{
"concreteType": "org.sagebionetworks.repo.model.provenance.UsedURL",
"url" : "https://tcga-data.nci.nih.gov" + e['deployLocation']
}
)
urls[ mirror + e['deployLocation'] ] = platform
if len(dates) == 0:
logging.debug("No Files found")
return
dates.sort()
dates.reverse()
versionDate = dates[0].strftime( "%Y-%m-%d" )
return BuildConf(platform, basename, versionDate, meta, urls)
class TableReader:
def __init__(self, path):
self.path = path
def __iter__(self):
if self.path is not None and os.path.exists(self.path):
handle = open(self.path)
for line in handle:
tmp = line.rstrip().split("\t")
yield tmp[0], json.loads(tmp[1])
handle.close()
############
# Importer Classes
############
class FileImporter:
dataSubTypes = {}
excludes = [
"MANIFEST.txt$",
"CHANGES_DCC.txt$",
"README_DCC.txt$",
"README.txt$",
"CHANGES.txt$",
"DCC_ALTERED_FILES.txt$",
r'.wig$',
"DESCRIPTIO$"
]
def __init__(self, config, build_req):
self.config = config
self.build_req = build_req
#variable df, which is the data frame keeping all the data, it will be assigned in the run() method
self.df = None
def extractTars(self):
if not os.path.exists(self.config.workdir_base):
os.makedirs(self.config.workdir_base)
self.work_dir = tempfile.mkdtemp(dir=self.config.workdir_base)
print "Extract to ", self.work_dir
for record in self.build_req['provenance']['used']:
url = record['url']
path = self.config.getURLPath(url)
subprocess.check_call([ "tar", "xzf", path, "-C", self.work_dir])#, stderr=sys.stdout)
def run(self):
self.extractTars()
#scan the magetab
self.out = {}
self.ext_meta = {}
self.scandirs(self.work_dir, None)
for o in self.out:
self.out[o].close()
for dsubtype in self.dataSubTypes:
self.df = pd.DataFrame()
print "Extracting: ", dsubtype
filterInclude = None
filterExclude = None
if 'fileInclude' in self.dataSubTypes[dsubtype]:
filterInclude = re.compile(self.dataSubTypes[dsubtype]['fileInclude'])
if 'fileExclude' in self.dataSubTypes[dsubtype]:
filterExclude = re.compile(self.dataSubTypes[dsubtype]['fileExclude'])
self.inc = 0
self.errors = []
self.ext_meta = {}
self.out = {}
self.scandirs(self.work_dir, dsubtype, filterInclude=filterInclude, filterExclude=filterExclude)
for o in self.out:
self.out[o].close()
self.fileBuild(dsubtype)
shutil.rmtree(self.work_dir)
def checkExclude( self, name ):
for e in self.excludes:
if re.search( e, name ):
return True
return False
def scandirs(self, path, dataSubType, filterInclude=None, filterExclude=None):
if os.path.isdir(path):
for a in glob(os.path.join(path, "*")):
self.scandirs(a, dataSubType, filterInclude, filterExclude)
else:
name = os.path.basename(path)
if self.isMage(path):
if dataSubType is None:
self.mageScan(path)
else:
if dataSubType is not None:
if not self.checkExclude(name):
if (filterInclude is None or filterInclude.match(name)) and (filterExclude is None or not filterExclude.match(path)):
self.fileScan(path, dataSubType)
def isMage(self, path):
if path.endswith( '.sdrf.txt' ) or path.endswith( '.idf.txt' ) or path.endswith("DESCRIPTION.txt"):
return True
def emit(self, key, data, port):
if port not in self.out:
self.out[port] = open(self.work_dir + "/" + port, "w")
self.out[port].write( "%s\t%s\n" % (key, json.dumps(data)))
def emitFile(self, dataSubType, meta, file):
md5 = hashlib.md5()
oHandle = open(self.config.getOutPath(self.dataSubTypes[dataSubType]['nameGen']), "wb")
with open(file,'rb') as f:
for chunk in iter(lambda: f.read(8192), ''):
md5.update(chunk)
oHandle.write(chunk)
oHandle.close()
md5str = md5.hexdigest()
meta['annotations']['md5'] = md5str
mHandle = open(self.config.getOutMeta(self.dataSubTypes[dataSubType]['nameGen']), "w")
mHandle.write( json.dumps(meta))
mHandle.close()
if len(self.errors):
eHandle = open( self.config.getOutError(dataSubType), "w" )
for msg in self.errors:
eHandle.write( msg + "\n" )
eHandle.close()
def addError(self, msg):
self.errors.append(msg)
commonMap = {
"mean" : "seg.mean",
"Segment_Mean" : "seg.mean",
"Start" : "loc.start",
"End" : "loc.end",
"Chromosome" : "chrom"
}
idfMap = {
"Investigation Title" : "title",
"Experiment Description" : "experimentalDescription",
"Person Affiliation" : "dataProducer",
"Date of Experiment" : "experimentalDate"
}
CONTROL_SAMPLES = ["TCGA-07-0249", "TCGA-07-7600", "TCGA-AV-A03E", "TCGA-AV-A3E6", "TCGA-AV-A03D", "TCGA-07-0227", "231 Control", "231 IGF", "468 Control", "468 EGF", "Control_Jurkat", "Jurkat Control", "Jurkat Fas", "Mixed Lysate", "BD_Human_Tissue_Ref_RNA_Extract", "BioChain_RtHanded_Total_", "tratagene_Cell_Line_Hum_Ref_RNA_Extract"]
class TCGAGeneticImport(FileImporter):
def mageScan(self, path):
if path.endswith(".sdrf.txt"):
iHandle = open(path, "rU")
read = csv.reader( iHandle, delimiter="\t" )
colNum = None
for row in read:
if colNum is None:
colNum = {}
for i in range(len(row)):
colNum[ row[i] ] = i
else:
if not colNum.has_key("Material Type") or ( not row[ colNum[ "Material Type" ] ] in [ "genomic_DNA", "total_RNA", "MDA cell line" ] ):
try:
if colNum.has_key( "Derived Array Data File" ):
self.emit( row[ colNum[ "Derived Array Data File" ] ].split('.')[0], row[ colNum[ "Extract Name" ] ], "targets" )
self.emit( row[ colNum[ "Derived Array Data File" ] ], row[ colNum[ "Extract Name" ] ], "targets" )
if colNum.has_key("Derived Array Data Matrix File" ):
self.emit( row[ colNum[ "Derived Array Data Matrix File" ] ], row[ colNum[ "Extract Name" ] ], "targets" )
if colNum.has_key( "Derived Data File"):
self.emit( row[ colNum[ "Derived Data File" ] ].split('.')[0], row[ colNum[ "Extract Name" ] ], "targets" )
self.emit( row[ colNum[ "Derived Data File" ] ], row[ colNum[ "Extract Name" ] ], "targets" )
if colNum.has_key( "Hybridization Name" ):
self.emit( row[ colNum[ "Hybridization Name" ] ] , row[ colNum[ "Extract Name" ] ], "targets" )
if colNum.has_key( "Sample Name" ):
self.emit( row[ colNum[ "Sample Name" ] ] , row[ colNum[ "Extract Name" ] ], "targets" )
self.emit( row[ colNum[ "Extract Name" ] ] , row[ colNum[ "Extract Name" ] ], "targets" )
except IndexError:
pass #there can be blank lines in the SDRF
if path.endswith(".idf.txt"):
iHandle = open(path)
for line in iHandle:
row = line.split("\t")
if len(row):
if row[0] in idfMap:
self.ext_meta[ idfMap[row[0]] ] = row[1]
iHandle.close()
if path.endswith("DESCRIPTION.txt"):
handle = open(path)
self.description = handle.read()
handle.close()
@staticmethod
def getOutputList():
yield "default"
@staticmethod
def getArchiveQuery(basename):
q = CustomQuery("Archive[@baseName=%s][@isLatest=1][ArchiveType[@type=Level_3]]" % (basename))
for e in q:
yield e
@staticmethod
def getMageQuery(basename):
q = "Archive[@baseName=%s][@isLatest=1][ArchiveType[@type=mage-tab]]" % (basename)
for e in q:
yield e
@staticmethod
def getArchiveUrls(basename):
q = CustomQuery("Archive[@baseName=%s][@isLatest=1][ArchiveType[@type=Level_3]]" % (basename))
for e in q:
yield e['deployLocation']
@staticmethod
def getMageUrl(basename):
q = CustomQuery("Archive[@baseName=%s][@isLatest=1][ArchiveType[@type=mage-tab]]" % (basename))
out = None
for e in q:
out = e['deployLocation']
return out
@staticmethod
def getArchiveList(platform):
q = CustomQuery("Archive[Platform[@name=%s]][@isLatest=1]" % platform)
out = {}
for e in q:
name = e['baseName']
if name not in out:
yield name
out[name] = True
def translateUUID(self, uuid):
return self.config.translateUUID(uuid)
def getTargetMap(self):
handle = TableReader(self.work_dir + "/targets")
tTrans = {}
for key, value in handle:
tTrans[ key ] = value
return tTrans
def fileScan(self, path, dataSubType):
"""
This function takes a TCGA level 3 genetic file (file name and input handle),
and tries to extract probe levels or target mappings (experimental ID to TCGA barcode)
it emits these values to a handle, using the 'targets' and 'probes' string to identify
the type of data being emited
"""
iHandle = open(path)
mode = None
#modes
#1 - segmentFile - one sample per file/no sample info inside file
#2 - two col header matrix file
#3 - segmentFile - sample information inside file
#None something else
target = None
colName = None
colType = None
firstLine = iHandle.readline()
colName = firstLine.rstrip().split("\t")
print colName, path
if colName[0] == "Hybridization REF" or colName[0] == "Sample REF":
mode = 2
elif colName[0] == "Chromosome" or colName[0] == "chromosome":
mode = 1
target = os.path.basename( path ).split('.')[0]
elif colName[1] == "chrom":
mode = 3
target = os.path.basename( path ).split('.')[0]
if mode == 2:
colName = [commonMap.get(colName[i], colName[i]) for i in range(len(colName))]
secondLine = iHandle.readline()
colType = secondLine.rstrip().split("\t")
colType = [commonMap.get(colType[i], colType[i]) for i in range(len(colType))]
tmp = pd.read_csv(iHandle, sep="\t", header=None, names=colType[1:], index_col=0)
wantedProbeFields = self.dataSubTypes[dataSubType]['probeFields']
idx = [col in wantedProbeFields for col in colType]
idx = idx[1:]
tmp = tmp.ix[:,idx]
tmp.columns = [colName[1]]
tmp = tmp.dropna()
self.df = pd.concat([self.df, tmp], axis=1)
else:
tmp = pd.read_csv(iHandle, sep="\t", header=None, names=colName, index_col=0)
tmp["file"] = os.path.basename(path)
if mode==1:
tmp["key"] = target
self.df = pd.concat([self.df,tmp], axis=1)
elif mode == 3:
self.df = pd.concat([self.df, tmp], axis=1)
else:
tmp = tmp.drop("file", 1)
wantedProbeFields = self.dataSubTypes[dataSubType]['probeFields']
idx = [col in wantedProbeFields for col in colName]
idx = idx[1:]
tmp = tmp.ix[:,idx]
tmp.columns = [os.path.basename(path).split(".")[0]]
self.df = pd.concat([self.df, tmp], axis=1)
class TCGASegmentImport(TCGAGeneticImport):
def fileScan(self, path, dataSubType):
"""
This function takes a TCGA level 3 genetic file (file name and input handle),
and tries to extract probe levels or target mappings (experimental ID to TCGA barcode)
it emits these values to a handle, using the 'targets' and 'probes' string to identify
the type of data being emitted
"""
with open(path,'U') as iHandle:
tmp = pd.read_csv(iHandle, sep="\t", header=0, dtype='object')
tmp['key'] = os.path.basename(path)
tmp.columns = [commonMap.get(col, col) for col in tmp.columns]
self.df = self.df.append(tmp[["chrom", "loc.start", "loc.end", "key", "seg.mean"]])
self.df = self.df[["chrom", "loc.start", "loc.end", "key", "seg.mean"]] #Fix order to be bed5 compatible
def getMeta(self, name, dataSubType):
# fileType hardcoded into getMeta function, and fileType listed here is used to write
# extension when files are uploaded to Synapse, as synapseLoad_files reads from associated .json file
matrixInfo = {
'name' : name + "." + dataSubType + ".seg",
'annotations' : {
'fileType' : 'seg',
"lastModified" : self.config.version,
'rowKeySrc' : "tcga.%s" % (self.config.abbr),
'dataSubType' : dataSubType,
'dataProducer' : 'TCGA',
}
}
matrixInfo = dict_merge(matrixInfo, self.ext_meta)
matrixInfo = dict_merge(matrixInfo, self.config.meta)
return matrixInfo
def fileBuild(self, dataSubType):
#use the target table to create a name translation table
#also setup target name enumeration, so they will have columns
#numbers
segFile = "%s/%s.segment_file" % (self.work_dir, dataSubType)
tmap = self.getTargetMap()
self.df["key"] = [self.translateUUID(tmap.get(key, key).lower()) for key in self.df["key"]]
self.df = self.df[self.df.key != 'NA']
self.df["chrom"] = self.df["chrom"].apply(numChrom)
if self.config.rmControl: #Filter out control samples
idx = [not any([k.startswith(item) for item in CONTROL_SAMPLES]) for k in self.df['key']]
self.df = self.df[idx]
self.df = self.df[['key', 'chrom', 'loc.start', 'loc.end', 'seg.mean']]
self.df.columns = ['Sample', 'Chromosome', 'Start', 'End', 'Segment_Mean']
self.df.to_csv(segFile, index=False, sep="\t", float_format="%0.6g")
matrixName = self.config.name
self.emitFile( dataSubType, self.getMeta(matrixName, dataSubType), segFile)
class TCGAMatrixImport(TCGAGeneticImport):
def getMeta(self, name, dataSubType):#return a dictionary
matrixInfo = {
'annotations' : {
'fileType' : 'genomicMatrix',
"lastModified" : self.config.version,
'dataSubType' : dataSubType,
'dataProducer' : 'TCGA',
'rowKeySrc' : self.dataSubTypes[dataSubType]['probeMap'],
'columnKeySrc' : "tcga.%s" % (self.config.abbr)
},
'name' : name + "." + dataSubType + ".tsv",
}
matrixInfo = dict_merge(matrixInfo, self.ext_meta)
matrixInfo = dict_merge(matrixInfo, self.config.meta)
return matrixInfo
def fileBuild(self, dataSubType):
#use the target table to create a name translation table
#also setup target name enumeration, so they will have columns
#numbers
matrixFile = None
f=open(self.work_dir +"/targets", "r")
d = dict()
for line in f:
arr = line.strip().split("\t")
if len(arr) < 2: continue
d[arr[0]] = arr[1].strip("\"").strip(".SD")
f.close()
d["key"] = "probes"
self.df.columns = [ self.translateUUID(d.get(key, key)) for key in self.df.columns]
if self.config.rmControl: #Filter out control samples
newCols = [col for col in self.df.columns if not any([col.startswith(item) for item in CONTROL_SAMPLES])]
self.df = self.df.ix[:, list(set(newCols))]
sortedIndex = sorted(self.df.index)
sortedCol = sorted(list(set(self.df.columns)))
self.df = self.df.ix[:, sortedCol]
#self.df = self.df.ix[sortedIndex, sortedCol]
matrixFile = "%s/%s.matrix_file" % (self.work_dir, dataSubType)
self.df.to_csv(matrixFile, header=True, sep="\t", index=True, float_format="%0.6g")
matrixName = self.config.name
self.emitFile( dataSubType, self.getMeta(matrixName, dataSubType), matrixFile)
class TCGASegmentImport_HumanHap(TCGASegmentImport):
def fileScan(self, path, dataSubType):
"""
This function takes a TCGA level 3 genetic file (file name and input handle),
and tries to extract probe levels or target mappings (experimental ID to TCGA barcode)
it emits these values to a handle, using the 'targets' and 'probes' string to identify
the type of data being emited
"""
with open(path,'U') as iHandle:
tmp = pd.read_csv(iHandle, sep="\t", header=0, dtype='object')
colNames = list(tmp.columns)
#TODO reformat output to match SNP_6
colNames[0] = "key"
tmp.columns = colNames
tmp.columns = [commonMap.get(col, col) for col in tmp.columns]
self.df = self.df.append(tmp[["chrom", "loc.start", "loc.end", "key", "seg.mean"]])
self.df = self.df.ix[:,["chrom", "loc.start", "loc.end", "key", "seg.mean"]]
adminNS = "http://tcga.nci/bcr/xml/administration/2.3"
def dom_scan(node, query):
stack = query.split("/")
if node.localName == stack[0]:
return dom_scan_iter(node, stack[1:], [stack[0]])
def dom_scan_iter(node, stack, prefix):
if len(stack):
for child in node.childNodes:
if child.nodeType == child.ELEMENT_NODE:
if child.localName == stack[0]:
for out in dom_scan_iter(child, stack[1:], prefix + [stack[0]]):
yield out
elif '*' == stack[0]:
for out in dom_scan_iter(child, stack[1:], prefix + [child.localName]):
yield out
else:
if node.nodeType == node.ELEMENT_NODE:
yield node, prefix, dict(node.attributes.items()), getText( node.childNodes )
elif node.nodeType == node.TEXT_NODE:
yield node, prefix, None, getText( node.childNodes )
class TCGAClinicalImport(FileImporter):
def fileScan(self, path, dataSubType):
print "Parsing", dataSubType, path
handle = open(path)
data = handle.read()
handle.close()
xml=parseString(data)
self.parseXMLFile(xml, dataSubType)
def getText(self, nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
@staticmethod
def getOutputList():
return ["patient", "aliquot", "analyte", "portion", "sample", "drugs", "radiation", "followup"]
@staticmethod
def getArchiveQuery(basename):
q = CustomQuery("Archive[@baseName=%s][@isLatest=1]" % (basename))
for e in q:
yield e
@staticmethod
def getArchiveUrls(basename):
q = CustomQuery("Archive[@baseName=%s][@isLatest=1][platform[@alias=bio]]" % (basename))
for e in q:
yield e['deployLocation']
@staticmethod
def getMageUrl(basename):
q = CustomQuery("Archive[@baseName=%s][@isLatest=1][ArchiveType[@type=mage-tab]]" % (basename))
out = None
for e in q:
out = e['deployLocation']
return out
def parseXMLFile(self, dom, dataSubType):
root_node = dom.childNodes[0]
admin = {}
for node, stack, attr, text in dom_scan(root_node, "tcga_bcr/admin/*"):
admin[stack[-1]] = { 'value' : text }
patient_barcode = None
for node, stack, attr, text in dom_scan(root_node, 'tcga_bcr/patient/bcr_patient_barcode'):
patient_barcode = text
patient_data = {}
for node, stack, attr, text in dom_scan(root_node, "tcga_bcr/patient/*"):
if 'xsd_ver' in attr:
#print patientName, stack[-1], attr, text
p_name = attr.get('preferred_name', stack[-1])
if len(p_name) == 0:
p_name = stack[-1]
patient_data[p_name] = { "value" : text }
if dataSubType == "patient":
for node, stack, attr, text in dom_scan(root_node, "tcga_bcr/patient/stage_event/*"):
if 'xsd_ver' in attr:
p_name = attr.get('preferred_name', stack[-1])
if len(p_name) == 0:
p_name = stack[-1]
patient_data[p_name] = { "value" : text }
for node, stack, attr, text in dom_scan(root_node, "tcga_bcr/patient/stage_event/*/*"):
if 'xsd_ver' in attr:
p_name = attr.get('preferred_name', stack[-1])
if len(p_name) == 0:
p_name = stack[-1]
patient_data[p_name] = { "value" : text }
for node, stack, attr, text in dom_scan(root_node, "tcga_bcr/patient/stage_event/tnm_categories/*/*"):
if 'xsd_ver' in attr:
p_name = attr.get('preferred_name', stack[-1])
if len(p_name) == 0:
p_name = stack[-1]
patient_data[p_name] = { "value" : text }
self.emit( patient_barcode, patient_data, "patient" )
if dataSubType == "sample":
for s_node, s_stack, s_attr, s_text in dom_scan(root_node, "tcga_bcr/patient/samples/sample"):
sample_barcode = None
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "sample/bcr_sample_barcode"):
sample_barcode = c_text
sample_data = {}
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "sample/*"):
if 'xsd_ver' in c_attr:
sample_data[c_attr.get('preferred_name', c_stack[-1])] = { "value" : c_text }
self.emit( sample_barcode, sample_data, "sample" )
if dataSubType == "portion":
for s_node, s_stack, s_attr, s_text in dom_scan(root_node, "tcga_bcr/patient/samples/sample/portions/portion"):
portion_barcode = None
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "portion/bcr_portion_barcode"):
portion_barcode = c_text
portion_data = {}
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "portion/*"):
if 'xsd_ver' in c_attr:
portion_data[c_attr.get('preferred_name', c_stack[-1])] = { "value" : c_text }
self.emit( portion_barcode, portion_data, "portion" )
if dataSubType == "analyte":
for s_node, s_stack, s_attr, s_text in dom_scan(root_node, "tcga_bcr/patient/samples/sample/portions/portion/analytes/analyte"):
analyte_barcode = None
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "analyte/bcr_analyte_barcode"):
analyte_barcode = c_text
analyte_data = {}
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "analyte/*"):
if 'xsd_ver' in c_attr:
analyte_data[c_attr.get('preferred_name', c_stack[-1])] = { "value" : c_text }
self.emit( analyte_barcode, analyte_data, "analyte" )
if dataSubType == "aliquot":
for s_node, s_stack, s_attr, s_text in dom_scan(root_node, "tcga_bcr/patient/samples/sample/portions/portion/analytes/analyte/aliquots/aliquot"):
aliquot_barcode = None
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "aliquot/bcr_aliquot_barcode"):
aliquot_barcode = c_text
aliquot_data = {}
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "aliquot/*"):
if 'xsd_ver' in c_attr:
aliquot_data[c_attr.get('preferred_name', c_stack[-1])] = { "value" : c_text }
self.emit( aliquot_barcode, aliquot_data, "aliquot" )
if dataSubType == "drug":
for s_node, s_stack, s_attr, s_text in dom_scan(root_node, "tcga_bcr/patient/drugs/drug"):
drug_barcode = None
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "drug/bcr_drug_barcode"):
drug_barcode = c_text
drug_data = {}
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "drug/*"):
if 'xsd_ver' in c_attr:
drug_data[c_attr.get('preferred_name', c_stack[-1])] = { "value" : c_text }
self.emit( drug_barcode, drug_data, "drug" )
if dataSubType == "radiation":
for s_node, s_stack, s_attr, s_text in dom_scan(root_node, "tcga_bcr/patient/radiations/radiation"):
radiation_barcode = None
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "radiation/bcr_radiation_barcode"):
radiation_barcode = c_text
radiation_data = {}
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "radiation/*"):
if 'xsd_ver' in c_attr:
radiation_data[c_attr.get('preferred_name', c_stack[-1])] = { "value" : c_text }
self.emit( radiation_barcode, radiation_data, "radiation" )
if dataSubType == "followup":
for s_node, s_stack, s_attr, s_text in dom_scan(root_node, "tcga_bcr/patient/follow_ups/follow_up"):
follow_up_barcode = None
sequence = s_attr['sequence']
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "follow_up/bcr_followup_barcode"):
follow_up_barcode = c_text
follow_up_data = { "sequence" : {"value" : sequence}}
for c_node, c_stack, c_attr, c_text in dom_scan(s_node, "follow_up/*"):
if 'xsd_ver' in c_attr:
follow_up_data[c_attr.get('preferred_name', c_stack[-1])] = { "value" : c_text }
self.emit( follow_up_barcode, follow_up_data, "followup" )
def getMeta(self, name, dataSubType):
fileInfo = {
"name" : name + "." + dataSubType + ".tsv",
"annotations" : {
"fileType" : "clinicalMatrix",
"lastModified" : self.config.version,
'dataSubType' : dataSubType,
"rowKeySrc" : "tcga.%s" % (self.config.abbr)
}
}
fileInfo = dict_merge(fileInfo, self.ext_meta)
fileInfo = dict_merge(fileInfo, self.config.meta)
return fileInfo
def fileBuild(self, dataSubType):
if os.path.exists( "%s/%s" % (self.work_dir, dataSubType)):
subprocess.call("cat %s/%s | sort -k 1 > %s/%s.sort" % (self.work_dir, dataSubType, self.work_dir, dataSubType), shell=True)
handle = TableReader(self.work_dir + "/" + dataSubType + ".sort")
matrix = {}
colEnum = {}
for key, value in handle:
if key not in matrix:
matrix[key] = {}
for col in value:
matrix[key][col] = value[col]
if col not in colEnum:
if not self.config.sanitize or col not in [ 'race', 'ethnicity' ]:
colEnum[col] = len(colEnum)
handle = open( os.path.join(self.work_dir, dataSubType + "_file"), "w")
cols = [None] * (len(colEnum))
for col in colEnum:
cols[colEnum[col]] = col
handle.write("sample\t%s\n" % ("\t".join(cols)))
for key in matrix:
cols = [""] * (len(colEnum))
for col in colEnum:
if col in matrix[key]:
cols[colEnum[col]] = matrix[key][col]['value']
handle.write("%s\t%s\n" % (key, "\t".join(cols).encode("ASCII", "replace")))
handle.close()
self.emitFile( dataSubType, self.getMeta(self.config.name, dataSubType), "%s/%s_file" % (self.work_dir, dataSubType))
class AgilentImport(TCGAMatrixImport):
dataSubTypes = {
'geneExp' : {
'probeMap' : 'hugo',
'sampleMap' : 'tcga.iddag',
'dataType' : 'genomicMatrix',
'fileExclude' : r'.*targets$',
'probeFields' : ['log2 lowess normalized (cy5/cy3) collapsed by gene symbol'],
'extension' : 'tsv',
'nameGen' : lambda x : "%s.geneExp.tsv" % (x)
}
}
class CGH1x1mImport(TCGASegmentImport):
dataSubTypes = {
'cna' : {
"sampleMap" : 'tcga.iddag',
"dataType" : 'genomicSegment',
"probeFields" : ['seg.mean'],
'fileExclude' : r'.*targets$',
'nameGen' : lambda x : "%s.cna.seg" % (x)
}
}
class SNP6Import(TCGASegmentImport):
assembly = 'hg19'
# Dictionary which defines dictionaries for each dataSubType, i.e. 'cna'.
dataSubTypes = {
'cna' : {
'sampleMap' :'tcga.iddag',
'dataType' : 'genomicSegment',
'probeFields' : ['seg.mean', 'Segment_Mean'],
'fileInclude' : r'^.*\.hg19.seg.txt$|^.*\.segmented.dat$',
'extension' : 'seg',
'nameGen' : lambda x : "%s.hg19.cna.seg" % (x)
},
'cna_nocnv' : {
'sampleMap' :'tcga.iddag',
'dataType' : 'genomicSegment',
'probeFields' : ['seg.mean', 'Segment_Mean'],
'fileInclude' : r'^.*\.nocnv_hg19.seg.txt$|^.*\.segmented.dat$',
'extension' : 'seg',
'nameGen' : lambda x : "%s.hg19.cna_nocnv.seg" % (x)
},
'cna_probecount' : {
'sampleMap' :'tcga.iddag',
'dataType' : 'genomicSegment',
'probeFields' : ['Num_Probes'],
'fileInclude' : r'^.*\.hg19.seg.txt$|^.*\.segmented.dat$',
'extension' : 'seg',
'nameGen' : lambda x : "%s.hg19.cna_probecount.seg" % (x)
},
'cna_nocnv_probecount' : {
'sampleMap' :'tcga.iddag',
'dataType' : 'genomicSegment',
'probeFields' : ['Num_Probes'],
'fileInclude' : r'^.*\.nocnv_hg19.seg.txt$|^.*\.segmented.dat$',
'extension' : 'seg',
'nameGen' : lambda x : "%s.hg19.cna_nocnv_probecount.seg" % (x)
}
}
def fileScan(self, path, dataSubType):
with open(path) as handle:
tmp = pd.read_csv(handle, sep="\t", dtype='object')
tmp = tmp.ix[:, ['Sample', 'Chromosome', 'Start', 'End', 'Num_Probes', 'Segment_Mean']]
self.df = self.df.append(tmp)
self.df = self.df.ix[:,['Sample', 'Chromosome', 'Start', 'End', 'Num_Probes', 'Segment_Mean']]
def fileBuild(self, dataSubType):
tmap = self.getTargetMap()
segFile = "%s/%s.out" % (self.work_dir, dataSubType)
self.df["Sample"] = [self.translateUUID(tmap.get(key, key)) for key in self.df["Sample"]]
# Convert Num_Probes and Start cols to type int to remove decimal point
self.df['Num_Probes'] = self.df['Num_Probes'].astype(int)
self.df['Start'] = self.df['Start'].astype(int)
if self.config.rmControl: #Filter out control samples
idx = [not any([k.startswith(item) for item in CONTROL_SAMPLES]) for k in self.df['Chromosome']]
self.df.to_csv(segFile, index=False, sep="\t", float_format="%0.6g")
meta = self.getMeta(self.config.name + ".hg19", dataSubType)
meta['annotations']['assembly'] = { "@id" : 'hg19' }
self.emitFile(dataSubType, meta, segFile)
class HmiRNAImport(TCGAMatrixImport):
dataSubTypes = {
'miRNAExp' : {
'probeMap' : 'agilentHumanMiRNA',
'sampleMap' : 'tcga.iddag',
'dataType' : 'genomicMatrix',
'probeFields' : ['unc_DWD_Batch_adjusted'],
'fileExclude' : r'.*targets$',