-
Notifications
You must be signed in to change notification settings - Fork 0
/
proteinValidation.py
240 lines (211 loc) · 9.23 KB
/
proteinValidation.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
import pandas
import requests
import logging
import subprocess
import os
import numpy
import hashlib
logger = logging.getLogger(__name__)
def md5sum(filePath):
md5_hash = hashlib.md5()
with open(filePath, "rb") as file:
for chunk in iter(lambda: file.read(4096), b""):
md5_hash.update(chunk)
return md5_hash.hexdigest()
def existing_md5sums(logger, projectName, dataType, proteinSamplesDict):
existingFiles = [file for file in os.listdir(f"gdcFiles/{projectName}/{dataType}") if not file.startswith(".")]
existingMd5sumFileDict = {md5sum(f"gdcFiles/{projectName}/{dataType}/{file}"): file for file in existingFiles}
gdcMd5sumFileDict = {proteinSamplesDict[sample][fileID]["md5sum"]: fileID for sample in proteinSamplesDict for fileID in proteinSamplesDict[sample]}
logger.info(f"{len(gdcMd5sumFileDict)} files found from the GDC for {dataType} data for {projectName}")
logger.info(f"{len(existingMd5sumFileDict)} files found at gdcFiles/{projectName}/{dataType}")
fileIdDict = {innerKey: value
for outerDict in proteinSamplesDict.values()
for innerKey, value in outerDict.items()}
filesNeededToUpdate = {gdcMd5sumFileDict[md5sum]: fileIdDict[gdcMd5sumFileDict[md5sum]]["fileName"] for md5sum in gdcMd5sumFileDict if md5sum not in existingMd5sumFileDict}
logger.info(f"{len(filesNeededToUpdate)} files needed to update")
return filesNeededToUpdate
x = 5
def getXenaSamples(xenaFile):
with open(xenaFile, "r") as xenaData:
header = xenaData.readline() # get column labels from xena matrix
sampleList = header.split("\t") # split tsv file into list
sampleList.pop(0) # remove unnecessary label
sampleList = [sample.strip() for sample in sampleList] # make sure there isn't extra whitespace
return sampleList
def proteinSamples(projectName):
filesEndpoint = "https://api.gdc.cancer.gov/files"
proteinSamplesFilter = {
"op": "and",
"content": [
{
"op": "in",
"content": {
"field": "cases.project.project_id",
"value": [
projectName
]
}
},
{
"op": "in",
"content": {
"field": "data_category",
"value": [
"proteome profiling"
]
}
},
{
"op": "in",
"content": {
"field": "data_type",
"value": [
"Protein Expression Quantification"
]
}
},
{
"op": "in",
"content": {
"field": "experimental_strategy",
"value": [
"Reverse Phase Protein Array"
]
}
},
{
"op": "in",
"content": {
"field": "platform",
"value": [
"rppa"
]
}
},
{
"op": "in",
"content": {
"field": "access",
"value": [
"open"
]
}
}
]
}
params = {
"filters": proteinSamplesFilter,
"fields": "cases.samples.submitter_id,file_id,file_name,md5sum",
"format": "json",
"size": 20000
}
response = requests.post(filesEndpoint, json=params, headers={"Content-Type": "application/json"})
responseJson = response.json()["data"]["hits"]
proteinSamplesDict = {}
for caseDict in responseJson:
for submitterDict in caseDict["cases"][0]["samples"]:
sampleName = submitterDict["submitter_id"]
if sampleName in proteinSamplesDict:
proteinSamplesDict[sampleName][caseDict["file_id"]] = {"fileName": caseDict["file_name"],
"md5sum": caseDict["md5sum"]
}
else:
proteinSamplesDict[sampleName] = {}
proteinSamplesDict[sampleName][caseDict["file_id"]] = {"fileName": caseDict["file_name"],
"md5sum": caseDict["md5sum"]
}
return proteinSamplesDict
def downloadFiles(fileList, projectName, dataType):
if isinstance(fileList, list):
ids = fileList
elif isinstance(fileList, dict):
ids = list(fileList.keys())
jsonPayload = {
"ids": ids
}
with open("payload.txt", "w") as payloadFile:
payloadFile.write(str(jsonPayload).replace("\'", "\""))
logger.info("Downloading from GDC: ")
outputDir = f"gdcFiles/{projectName}/{dataType}"
os.makedirs(outputDir, exist_ok=True)
curlCommand = [
"curl", "--request", "POST", "--header", "Content-Type: application/json",
"--data", "@payload.txt", "https://api.gdc.cancer.gov/data"
]
if len(fileList) != 1:
outputFile = "gdcFiles.tar.gz"
curlCommand.extend(["-o", outputFile])
subprocess.run(curlCommand)
os.system(f"tar --strip-components=1 -xzf gdcFiles.tar.gz -C {outputDir}")
else:
outputFile = f"{outputDir}/{list(fileList.values())[0]}"
curlCommand.extend(["-o", outputFile])
subprocess.run(curlCommand)
def proteinDataframe(proteinSamples, projectName, dataType):
proteinDataframe = pandas.DataFrame()
for sample in proteinSamples:
sampleDataframe = pandas.DataFrame()
fileCount = 0
for fileName in [x["fileName"] for x in list(proteinSamples[sample].values())]:
filePath = "gdcFiles/{}/{}/{}".format(projectName, dataType, fileName)
tempDF = pandas.read_csv(filePath, sep="\t", usecols=[4, 5], index_col=0)
tempDF["nonNanCount"] = tempDF.apply(
lambda x: 1 if (not (pandas.isna(x["protein_expression"]))) else 0, axis=1)
tempDF.fillna(0, inplace=True)
fileCount += 1
if fileCount == 1:
sampleDataframe = tempDF
else:
sampleDataframe += tempDF
sampleDataframe["protein_expression"] = sampleDataframe.apply(
lambda x: x["protein_expression"] / x["nonNanCount"] if x["nonNanCount"] != 0 else numpy.nan, axis=1)
sampleDataframe.drop("nonNanCount", inplace=True, axis=1)
sampleDataframe.rename(columns={"protein_expression": sample}, inplace=True)
proteinDataframe[sample] = sampleDataframe[sample]
return proteinDataframe
def compare(logger, gdcDF, xenaDF):
failed = []
sampleNum = 1
total = len(gdcDF.columns)
for sample in gdcDF:
xenaColumn = xenaDF[sample]
gdcColumn = gdcDF[sample]
if not xenaColumn.equals(gdcColumn):
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 main(projectName, xenaFilePath, dataType):
xenaSamples = getXenaSamples(xenaFilePath)
proteinSamplesDict = proteinSamples(projectName)
if sorted(proteinSamplesDict) != 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(proteinSamplesDict)}")
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 proteinSamplesDict if x not in xenaSamples]}")
logger.info(f"Samples from Xena and not in GDC: {[x for x in xenaSamples if x not in proteinSamplesDict]}")
exit(1)
if os.path.isdir(f"gdcFiles/{projectName}/{dataType}"):
fileIDs = existing_md5sums(logger, projectName, dataType, proteinSamplesDict)
else:
fileIDs = [fileID for sample in proteinSamplesDict for fileID in proteinSamplesDict[sample]]
logger.info(f"{len(fileIDs)} files found from the GDC for {dataType} data for {projectName}")
logger.info(f"0 files found at gdcFiles/{projectName}/{dataType}")
logger.info(f"{len(fileIDs)} files needed to download")
if len(fileIDs) != 0:
downloadFiles(fileIDs, projectName, dataType)
xenaDF = pandas.read_csv(xenaFilePath, sep="\t", index_col=0)
gdcDF = proteinDataframe(proteinSamplesDict, projectName, dataType)
logger.info("Testing in progress ...")
result = compare(logger, gdcDF, xenaDF)
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"