-
Notifications
You must be signed in to change notification settings - Fork 0
/
clinicalValidation.py
751 lines (656 loc) · 29.9 KB
/
clinicalValidation.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
import sys
import requests
import json
import pandas
import numpy
import pandas
import ast
import logging
logger = logging.getLogger(__name__)
GDC_DROPPED_FIELDS = {
'cases.aliquot_ids',
'cases.submitter_aliquot_ids',
'cases.created_datetime',
'cases.sample_ids',
'diagnosis_ids', # cases.diagnoses.diagnosis_id
'cases.submitter_sample_ids',
'submitter_diagnosis_ids', # no submitter diagnosis id
'cases.updated_datetime',
'cases.index_date', #does not exist
'cases.state',
'cases.project.dbgap_accession_number',
'cases.project.releasable', # no project.releasable
'cases.project.state',
'cases.project.program.dbgap_accession_number',
'cases.project.program.program_id',
'cases.project.released',
'cases.diagnoses.created_datetime',
'cases.diagnoses.updated_datetime',
'cases.diagnoses.state',
'cases.diagnoses.submitter_id',
'cases.diagnoses.diagnosis_id',
'cases.demographic.submitter_id',
'cases.demographic.created_datetime',
'cases.demographic.demographic_id',
'cases.demographic.updated_datetime',
'cases.demographic.state',
'cases.submitter_slide_ids',
'cases.submitter_analyte_ids',
'cases.follow_ups', #Doesn't exist
'cases.portion_ids',
'cases.submitter_portion_ids',
'case.slide_ids',
'cases.analyte_ids',
'diagnoses', # Doesn't exist diagnose._____
'diagnoses.treatments', # Doesn't exist diagnoses.treatments._______
'cases.family_histories.updated_datetime',
'cases.family_histories.submitter_id',
'cases.family_histories.state',
'cases.family_histories.created_datetime',
'cases.family_histories.family_history_id',
'cases.exposures.submitter_id',
'cases.exposures.created_datetime',
'cases.exposures.updated_datetime',
'cases.exposures.exposure_id',
'cases.exposures.state',
'cases.samples.created_datetime',
'cases.samples.updated_datetime',
'cases.samples.state',
'cases.samples.portions', #cases.samples.portions_______
}
def unpack_dict(d, parent_key='', sep='.'):
"""
Unpacks a dictionary recursively, handling lists of dictionaries,
and returns a new dictionary with composite keys and lists of values.
Leaves specified keys unchanged and handles single-item lists by
converting them to the item itself.
:param d: The dictionary to unpack.
:param parent_key: The base key string used to build composite keys.
:param sep: Separator used in composite keys.
:param special_keys: Set of keys to be left unchanged.
"""
items = {}
# Iterate through the dictionary
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if k == "samples":
items[new_key] = v
elif isinstance(v, dict):
# Recurse into nested dictionaries
items.update(unpack_dict(v, new_key, sep))
elif isinstance(v, list):
if len(v) == 1:
# If the list contains a single item, use the item itself
v = v[0]
if isinstance(v, dict):
# If it's a single dictionary, unpack its values directly
items.update(unpack_dict(v, new_key, sep))
else:
# If it's a single non-dict item, add it directly
items[new_key] = v
elif all(isinstance(i, dict) for i in v):
# unpack this before going into it?
v = [unpack_dict(x) for x in v]
# Handle lists of dictionaries
all_keys = set()
# maybe don't include keys that have list of dicts as values?
for item in v:
all_keys.update(item.keys())
# Initialize new dictionary with composite keys and empty lists
for sub_key in all_keys:
composite_key = f"{new_key}{sep}{sub_key}"
items[composite_key] = []
# Populate the lists with values from each dictionary in the list
for sub_key in all_keys:
composite_key = f"{new_key}{sep}{sub_key}"
for item in v:
retrievedValue = item.get(sub_key, '')
items[composite_key].append(retrievedValue if retrievedValue is not None else '')
# if sub_key.startswith(("treatments", "pathology_details", "annotations")) and any(isinstance(i, list) for i in items[composite_key]):
# organizedList = []
# for entry in items[composite_key]:
# if isinstance(entry, list):
# organizedList.extend(entry)
# items[composite_key] = organizedList
else:
# Handle non-dict elements in lists (if necessary)
items[new_key] = v
else:
# Directly add the value if it's not a nested dictionary or list of dictionaries
items[new_key] = v
return items
def customMin(minList):
convertedList = []
for value in minList:
try:
convertedList.append(float(value))
except:
convertedList.append(float("inf"))
return min(convertedList)
def general_compare(val1, val2):
# Normalize "None" and "NaN" string representations
if isinstance(val1, str):
val1_lower = val1.lower()
if val1_lower == "none":
val1 = None
elif val1_lower == "nan":
val1 = float('nan')
if isinstance(val2, str):
val2_lower = val2.lower()
if val2_lower == "none":
val2 = None
elif val2_lower == "nan":
val2 = float('nan')
# Handle None and NaN equivalence
if (val1 is None and isinstance(val2, float) and numpy.isnan(val2)) or \
(val2 is None and isinstance(val1, float) and numpy.isnan(val1)):
return True
# Handle None values
if val1 is None or val2 is None:
return val1 is val2
# Handle NaN values
if isinstance(val1, float) and isinstance(val2, float):
if numpy.isnan(val1) and numpy.isnan(val2):
return True
# Convert string representation of a list to an actual list if necessary
if isinstance(val1, str) and val1.startswith('[') and val1.endswith(']'):
try:
val1 = ast.literal_eval(val1)
except (ValueError, SyntaxError):
return False
if isinstance(val2, str) and val2.startswith('[') and val2.endswith(']'):
try:
val2 = ast.literal_eval(val2)
except (ValueError, SyntaxError):
return False
# Ensure both values are lists before comparing
if isinstance(val1, list) and isinstance(val2, list):
if len(val1) != len(val2):
return False
for v1, v2 in zip(val1, val2):
if not general_compare(v1, v2):
return False
return True
# Attempt to convert both values to floats for comparison
try:
return numpy.format_float_scientific(float(val1), precision=8) == numpy.format_float_scientific(float(val2),
precision=8)
except (ValueError, TypeError):
# If conversion to float fails, compare values as strings
return str(val1).lower() == str(val2).lower()
def flatten_json(json_obj, prefix=""):
flattened_json = {}
for key, value in json_obj.items():
if isinstance(value, dict):
flattened_json.update(flatten_json(value, prefix + key + "."))
else:
flattened_json[prefix + key] = value
return flattened_json
def update_dict_without_overwriting(original_dict, new_dict):
"""
Update the original dictionary with the new dictionary’s values,
appending to the existing values without overwriting.
:param original_dict: The dictionary to update.
:param new_dict: The dictionary with new values.
:return: The updated dictionary.
"""
for key, value in new_dict.items():
if key in original_dict:
if value == original_dict[key]:
continue
# If the key exists and both values are lists, extend the list
if isinstance(original_dict[key], list) and isinstance(value, list):
original_dict[key].extend(value)
# If the key exists and both values are sets, update the set
elif isinstance(original_dict[key], set) and isinstance(value, set):
original_dict[key].update(value)
# If the key exists and both values are strings, concatenate the strings
elif isinstance(original_dict[key], str) and isinstance(value, str):
original_dict[key] = [original_dict[key]]
original_dict[key].append(value)
# If the key exists and both values are dictionaries, update the dictionary recursively
elif isinstance(original_dict[key], dict) and isinstance(value, dict):
update_dict_without_overwriting(original_dict[key], value)
# Otherwise, convert both values to a list and append the new value
else:
if not isinstance(original_dict[key], list):
original_dict[key] = [original_dict[key]]
original_dict[key].append(value)
else:
original_dict[key] = value
return original_dict
def availableFields():
response = requests.get("https://api.gdc.cancer.gov/files/_mapping")
availableFields = response.json()["fields"]
wantedFields = []
for field in availableFields:
if field not in GDC_DROPPED_FIELDS and not field.startswith('cases.summary.') and field.startswith("cases.") and not field.startswith("cases.follow_ups.") and not field.startswith("cases.samples.portions"):
wantedFields.append(field)
return wantedFields
def unpeelJson(jsonObj):
jsonObj = jsonObj.get("data").get("hits")
return jsonObj
def getFieldData(fields, projectName):
projectFields = [x.removeprefix("cases.project.") for x in fields if "cases.project." in x]
for x in fields:
if "cases.project." in x:
fields.remove(x)
sampleFields = [x.removeprefix("cases.") for x in fields if "cases.samples." in x]
for x in fields:
if "cases.samples." in x:
fields.remove(x)
projectFilter = {
"op": "and",
"content": [
{
"op": "in",
"content": {
"field": "project_id",
"value": [
projectName
]
}
}
]
}
caseFilter = {
"op": "and",
"content": [
{
"op": "in",
"content": {
"field": "project.project_id",
"value": [
projectName
]
}
}
]
}
fileFilter = {
"op": "and",
"content": [
{
"op": "in",
"content": {
"field": "cases.project.project_id",
"value": [
projectName
]
}
}
]
}
caseParams = {
"filters": json.dumps(caseFilter),
"fields": ",".join(sampleFields) + ",case_id",
"format": "json",
"size": 2000000
}
response = requests.post("https://api.gdc.cancer.gov/cases/", json=caseParams, headers={"Content-Type": "application/json"})
sampleResponseJson = unpeelJson(response.json())
sampleResponseDictionary = {case["case_id"]: case for case in sampleResponseJson}
for case in sampleResponseDictionary:
for key in list(sampleResponseDictionary[case].keys()):
if key != "samples":
del sampleResponseDictionary[case][key]
projectParams = {
"filters": json.dumps(projectFilter),
"fields": ",".join(projectFields),
"format": "json",
"size": 2000000
}
response = requests.post("https://api.gdc.cancer.gov/projects/", json=projectParams, headers={"Content-Type": "application/json"})
projectResponseJson = unpeelJson(response.json())
projectData = {"project": projectResponseJson[0]}
callOneFields = fields[(len(fields)//2):]
params = {
"filters": json.dumps(fileFilter),
"fields": ",".join(callOneFields) + ",cases.case_id" + ',cases.diagnoses.treatments.treatment_id'+ ",cases.diagnoses.diagnosis_id",
"format": "json",
"size": 2000000
}
response = requests.post("https://api.gdc.cancer.gov/files/", json=params, headers={"Content-Type": "application/json"})
response1Json = unpeelJson(response.json())
response1Dictionary = {case["cases"][0]["case_id"]: case["cases"][0] for case in response1Json}
callTwoFields = fields[:(len(fields)//2)]
params = {
"filters": json.dumps(fileFilter),
"fields": ",".join(callTwoFields) + ",cases.case_id" + ',cases.diagnoses.treatments.treatment_id' + ",cases.diagnoses.diagnosis_id",
"format": "json",
"size": 2000000
}
response = requests.post("https://api.gdc.cancer.gov/files/", json=params, headers={"Content-Type": "application/json"})
response2Json = unpeelJson(response.json())
response2Dictionary = {case["cases"][0]["case_id"]: case["cases"][0] for case in response2Json}
combinedData = update_dict_without_overwriting(response1Dictionary, response2Dictionary)
del projectData["project"]["id"]
for caseId in combinedData:
combinedData[caseId].update(projectData)
combinedData[caseId].update(sampleResponseDictionary[caseId])
return combinedData
# ***
def validSamples(caseData, projectName):
fileFilter = {
"op": "and",
"content": [
{
"op": "in",
"content": {
"field": "cases.project.project_id",
"value": [
projectName
]
}
},
{
"op": "in",
"content": {
"field": "access",
"value": [
'open'
]
}
},
{
"op": "in",
"content": {
"field": "files.data_category",
"value": [
'transcriptome profiling', 'proteome profiling', 'dna methylation', 'copy number variation', 'simple nucleotide variation'
]
}
}
]
}
params = {
"filters": json.dumps(fileFilter),
"fields": 'data_category,cases.samples.submitter_id,cases.samples.tissue_type',
"format": "json",
"size": 2000000
}
response = requests.post("https://api.gdc.cancer.gov/files/", json=params, headers={"Content-Type": "application/json"})
response = unpeelJson(response.json())
keepSamples = []
for file in response:
samples = file["cases"][0]["samples"]
# Get samples associated with transcriptome, proteome, and/or methylation file(s)
if file['data_category'] in ['Transcriptome Profiling', 'Proteome Profiling', 'DNA Methylation']:
for sample in samples:
submitter_id = sample['submitter_id']
if submitter_id not in keepSamples:
keepSamples.append(submitter_id)
# Get 'Tumor' samples associated with copy number variation and/or simple nucleotide variation file(s)
if file['data_category'] in ['Copy Number Variation', 'Simple Nucleotide Variation']:
for sample in samples:
submitter_id = sample['submitter_id']
if sample['tissue_type'] == 'Tumor' and submitter_id not in keepSamples:
keepSamples.append(submitter_id)
for caseID, caseInfo in caseData.items():
sampleIndex = 0
while sampleIndex < (len(caseInfo["samples"])):
sample = caseInfo["samples"][sampleIndex]
if sample["submitter_id"] not in keepSamples:
caseInfo["samples"].pop(sampleIndex)
sampleIndex -= 1
sampleIndex += 1
return caseData
# *****
def formatDiagnosis(caseData):
for case in caseData:
case = caseData[case]
if "diagnoses" in case:
diagnosisTempDict = {}
for diagnosis in case["diagnoses"]:
id = diagnosis["diagnosis_id"]
if id not in diagnosisTempDict:
del diagnosis["diagnosis_id"]
diagnosisTempDict[id] = diagnosis
else:
del diagnosis["diagnosis_id"]
update_dict_without_overwriting(diagnosisTempDict[id], diagnosis)
# diagnosisTempDict = update_dict_without_overwriting(diagnosisTempDict, diagnosis)
case["diagnoses"] = [diagnosisTempDict[diagnosis] for diagnosis in diagnosisTempDict]
return caseData
# ***
def formatTreatments(caseData):
for case in caseData:
case = caseData[case]
if "diagnoses" in case:
for diagnosis in case["diagnoses"]:
if "treatments" in diagnosis:
treatmentTempDict = {}
for treatment in diagnosis["treatments"]:
if treatment["treatment_id"] not in treatmentTempDict:
treatmentTempDict[treatment["treatment_id"]] = treatment
else:
update_dict_without_overwriting(treatmentTempDict[treatment["treatment_id"]], treatment )
diagnosis["treatments"] = [treatmentTempDict[treatment] for treatment in treatmentTempDict]
return caseData
def formatPathology(caseData):
for case in caseData:
case = caseData[case]
pathologyKeys = set()
if "diagnoses" in case:
for diagnosis in case["diagnoses"]:
if "pathology_details" in diagnosis:
tempPathologyDict = {x["pathology_detail_id"]: x for x in case["diagnoses"]["pathology_details"]}
case["diagnoses"]["pathology_details"] = tempPathologyDict
for pathology in case["diagnoses"]["pathology_details"]:
pathology = case["diagnoses"]["pathology_details"][pathology]
pathologyKeys.update(set(pathology.keys()))
pathologyDict = {key: [] for key in pathologyKeys}
for diagnosis in case["diagnoses"]:
if "pathology_details" in diagnosis:
for pathology in case["diagnoses"]["pathology_details"]:
pathology = case["diagnoses"]["pathology_details"][pathology]
for key in pathologyDict:
pathologyDict[key].append(pathology.get(key, ''))
# x = [sample["submitter_id"] for case in caseData for sample in caseData[case]["samples"]]
# df = pandas.read_csv("/Users/jaimes28/Desktop/gdcData/CGCI-HTMCP-DLBCL/Xena_Matrices/CGCI-HTMCP-DLBCL.clinical.tsv", sep="\t")
# samples = list(df["sample"])
# t = 5
def formatAnnotations(caseData):
for case in caseData:
case = caseData[case]
annotationKeys = set()
if "annotations" in case:
tempAnnotations = {x["annotation_id"]: x for x in case["annotations"]}
case["annotations"] = tempAnnotations
for annotation in case["annotations"]:
annotation = case["annotations"][annotation]
annotationKeys.update(annotation.keys())
annotationDict = {key: [] for key in annotationKeys}
for annotation in case["annotations"]:
annotation = case["annotations"][annotation]
for key in annotation:
annotationDict[key].append(annotation.get(key, ''))
if len(case["annotations"]) == 1:
annotationDict = {key: annotationDict[key][0] for key in annotationDict}
# ***
# def unpack(caseData):
# for caseName in caseData:
# # Flatten case
# case = flatten_json(caseData[caseName])
# if isinstance(case["diagnoses"], list) and len(case["diagnoses"]) == 1:
# case["diagnoses"] = case["diagnoses"][0]
# case = flatten_json(case)
# x=5
# elif isinstance(case["diagnoses"], list) and len(case["diagnoses"]) > 1:
# allKeys = {key for dictionary in case["diagnoses"] for key in dictionary if key != "pathology_details" and key != "treatments"}
# tempDict = {"diagnoses." + key: [] for key in allKeys}
# for dictionary in case["diagnoses"]:
# for key in allKeys:
# tempDict["diagnoses." + key].append(dictionary.get(key, '') if dictionary.get(key, '') is not None else '')
# pathologyHolder = [x for x in case["diagnoses"] if "pathology_details" in x]
# treatmentHolder = [x for x in case["diagnoses"] if "treatments" in x]
# tempDict.update({"diagnoses.treatments": treatmentHolder[0]["treatments"]})
# tempDict.update({"diagnoses.pathology_details": pathologyHolder[0]["pathology_details"]})
# case.update(tempDict)
# del case["diagnoses"]
#
# if "diagnoses.treatments" in case:
# treatmentTempDict = {}
# for treatment in case["diagnoses.treatments"]:
# if treatment["treatment_id"] not in treatmentTempDict:
# treatmentTempDict[treatment["treatment_id"]] = treatment
# else:
# update_dict_without_overwriting(treatmentTempDict[treatment["treatment_id"]], treatment)
#
# case["diagnoses.treatments"] = [treatmentTempDict[treatment] for treatment in treatmentTempDict]
#
#
#
#
# # collect all keys to remove from caseData
# keysToDelete = []
# # create new dictionary to collect unpacked data
# unpackedDict = {}
#
# for key, value in case.items():
# # if we have a list of dictionaries (and not samples)
# if value is None:
# keysToDelete.append(key)
# continue
# if isinstance(value, list) and len(value) == 1 and not isinstance(value[0], dict):
# case[key] = value[0]
# continue
# if key != "samples" and isinstance(value, list) and len(value) > 0 and isinstance(value[0], dict):
# # Add to the list the unpacked key that we should delete from original caseData dict
# keysToDelete.append(key)
# # Create temp value list to hold value with Null values removed
# tempValue = []
# # add each dict without null values to list
# for dictionary in value:
# tempDict = {key: value for key, value in dictionary.items() if value is not None}
# tempValue.append(tempDict)
# # assign value to this
# value = tempValue
#
# # if value only has one dict then no need to format it like a list
# if len(value) == 1:
# # iterate through each entry in the dict and add it to the unpacked dict and add parent dict at
# # beginning of key
# for entry in value[0]:
# unpackedDict[key + "." + entry] = value[0][entry]
# # go onto next key value pair
# continue
#
# # if there are multiple dicts collect all keys across each dict in a set
# allKeys = {key for dictionary in value for key in dictionary}
# # create a temp dict to hold all these keys with an empty list as the value
# tempDict = {key + "." + nestedKey: [] for nestedKey in allKeys}
# # for each dictionary in value
# for dictionary in value:
# # get every key from the dictionary and append it to the temp dict
# for key2 in allKeys:
# # use .get to handle case where key is not in that dictionary (Key Error) and return an empty
# # string to append
# tempDict[key + "." + key2].append(dictionary.get(key2, ''))
# unpackedDict.update(tempDict)
# case.update(unpackedDict)
# for key in keysToDelete:
# del case[key]
# caseData[caseName] = case
# print("here")
def processSamples(caseData):
sampleOrientedData = {}
for caseName in caseData:
case = caseData[caseName]
samples = case["samples"]
for sample in samples:
sampleDict = {"samples." + key: value for key, value in sample.items() if value is not None}
sampleDict.update(case)
del sampleDict["samples"]
sampleOrientedData[sampleDict["samples.submitter_id"]] = sampleDict
return sampleOrientedData
def compare(logger, gdcDF, xenaDF):
failed = []
sampleNum = 1
total = len(gdcDF)
for i in range(0, len(gdcDF)):
gdcRow = gdcDF.iloc[i]
xenaRow = xenaDF.iloc[i]
sample = xenaRow["sample"]
hasFailed = False
for column in gdcDF:
if column.endswith((".treatments.diagnoses", ".annotations.diagnoses", ".pathology_details.diagnoses")):
continue
xenaCell = xenaRow[column]
gdcCell = gdcRow[column]
if pandas.isna(xenaCell) and pandas.isna(gdcCell):
continue
if not general_compare(xenaCell, gdcCell):
hasFailed = True
break
if hasFailed:
status = "[{:d}/{:d}] Sample: {} - Failed"
logger.info(status.format(sampleNum, total, sample))
failed.append('{} ({})'.format(sample, sampleNum))
else:
status = "[{:d}/{:d}] Sample: {} - Passed"
logger.info(status.format(sampleNum, total, sample))
sampleNum += 1
return failed
def formatGDCDataframe(gdcDF):
for col in gdcDF.columns:
if col == "samples.submitter_id":
gdcDF.rename(columns={col: "sample"}, inplace=True)
continue
gdcDF.rename(columns={col: ".".join((col.split("."))[::-1])}, inplace=True)
gdcDF["id"] = gdcDF["case_id"]
if "age_at_diagnosis.diagnoses" in gdcDF.columns:
gdcDF["age_at_earliest_diagnosis.diagnoses.xena_derived"] = gdcDF['age_at_diagnosis.diagnoses'].apply(lambda x: customMin(x) if isinstance(x, list) else x)
gdcDF["age_at_earliest_diagnosis_in_years.diagnoses.xena_derived"] = gdcDF["age_at_earliest_diagnosis.diagnoses" \
".xena_derived"].apply(lambda x: x/365)
return gdcDF
def main(projectName, xenaFilePath, dataType):
wantedFields = availableFields()
caseData = getFieldData(wantedFields, projectName)
caseData = formatDiagnosis(caseData)
caseData = formatTreatments(caseData)
for id in caseData:
caseData[id] = unpack_dict(caseData[id])
caseData = validSamples(caseData, projectName)
sampleOrientedData = processSamples(caseData)
xenaDataframe = pandas.read_csv(xenaFilePath, sep='\t')
gdcDataframe = pandas.DataFrame(list(sampleOrientedData.values()))
gdcDataframe = formatGDCDataframe(gdcDataframe)
xenaSamples = xenaDataframe["sample"].tolist()
gdcSamples = gdcDataframe["sample"].tolist()
if sorted(gdcSamples) != sorted(xenaSamples):
logger.info("ERROR: Samples retrieved from the GDC do not match those found in Xena matrix.")
logger.info(f"Number of samples from the GDC: {len(gdcSamples)}")
logger.info(f"Number of samples in Xena matrix: {len(xenaSamples)}")
logger.info(f"Samples from GDC and not in Xena: {[x for x in gdcSamples if x not in xenaSamples]}")
logger.info(f"Samples from Xena and not in GDC: {[x for x in xenaSamples if x not in gdcSamples]}")
exit(1)
gdcDataframe.dropna(axis=1, how='all', inplace=True)
gdcColumns = gdcDataframe.columns.tolist()
xenaColumns = xenaDataframe.columns.tolist()
xenaExcludedColumns = [x for x in xenaColumns if not x.endswith((".treatments.diagnoses", ".annotations.diagnoses", ".pathology_details.diagnoses"))]
gdcExcludedColumns = [x for x in gdcColumns if not x.endswith((".treatments.diagnoses", ".annotations.diagnoses", ".pathology_details.diagnoses"))]
if sorted(xenaExcludedColumns) != sorted(gdcExcludedColumns):
logger.info("ERROR: Columns retrieved from the GDC do not match those found in Xena matrix.")
logger.info(f"Number of columns from the GDC: {len(gdcExcludedColumns)}")
logger.info(f"Number of columns in Xena matrix: {len(xenaExcludedColumns)}")
logger.info(f"Columns from GDC and not in Xena: {[x for x in gdcExcludedColumns if x not in xenaExcludedColumns]}")
logger.info(f"Columns from Xena and not in GDC: {[x for x in xenaExcludedColumns if x not in gdcExcludedColumns]}")
exit(1)
gdcDataframe = gdcDataframe[list(xenaDataframe.columns)]
gdcDataframe.convert_dtypes().dtypes
xenaDataframe.convert_dtypes().dtypes
gdcDataframe.fillna(pandas.NA, inplace=True)
xenaDataframe.fillna(pandas.NA, inplace=True)
gdcDataframe.sort_values(by=["sample"], inplace=True)
xenaDataframe.sort_values(by=["sample"], inplace=True)
gdcDataframe.reset_index(drop=True, inplace=True)
xenaDataframe.reset_index(drop=True, inplace=True)
result = compare(logger, gdcDataframe, xenaDataframe)
if len(result) == 0:
logger.info("[{}] test passed for [{}].".format(dataType, projectName))
return "PASSED"
else:
logger.info("[{}] test passed for [{}].".format(dataType, projectName))
logger.info("Samples failed: {}".format(result))
return "FAILED"