-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
414 lines (327 loc) · 15.9 KB
/
api.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
#!/usr/bin/env python3
#
# Description: POST service for exploration of
# data of Lung Cancer in the iASiS KG.
#
import sys
from flask import Flask, abort, request, make_response
import json
from SPARQLWrapper import SPARQLWrapper, JSON
import logging
import os
import urllib.parse
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
LIMIT=10
#KG="http://localhost:11384/sparql"
KG = os.environ["ENDPOINT"]
#KG="http://node1.research.tib.eu:41111/sparql"
#all
#KG="http://node2.research.tib.eu:18871/sparql"
#KG="http://node2.research.tib.eu:11789/sparql"
#drug_pub
#KG="http://node2.research.tib.eu:11124/sparql"
EMPTY_JSON = "{}"
app = Flask(__name__)
############################
#
# Query constants
#
############################
QUERY_DISORDERS_TO_DRUGS ="""
SELECT DISTINCT ?drug ?drugLabel WHERE { ?DrugDisorderInteraction a <http://research.tib.eu/p4-lucat/vocab/DrugDisorderInteraction>.
?DrugDisorderInteraction <http://research.tib.eu/p4-lucat/vocab/precipitantDrug> ?drug.
?DrugDisorderInteraction <http://research.tib.eu/p4-lucat/vocab/objectIndication> ?indication_ID.
?indication_ID <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?indication.
?drug <http://research.tib.eu/p4-lucat/vocab/drugLabel> ?drugLabel.
"""
QUERY_BIOMARKERS_TO_LC_DRUGS ="""
SELECT DISTINCT ?drug ?drugLabel WHERE { ?biomarker_ID <http://research.tib.eu/p4-lucat/vocab/biomarker_has_indication> ?drug .
?drug a <http://research.tib.eu/p4-lucat/vocab/LungCancerDrug>.
?biomarker_ID a <http://research.tib.eu/p4-lucat/vocab/Biomarker>.
?biomarker_ID <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?biomarker.
?drug <http://research.tib.eu/p4-lucat/vocab/drugLabel> ?drugLabel.
"""
QUERY_BIOMARKERS_TO_ALL_DRUGS ="""
SELECT DISTINCT ?drug ?drugLabel WHERE { ?biomarker_ID <http://research.tib.eu/p4-lucat/vocab/biomarker_has_indication> ?drug .
?biomarker_ID a <http://research.tib.eu/p4-lucat/vocab/Biomarker>.
?biomarker_ID <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?biomarker.
?drug <http://research.tib.eu/p4-lucat/vocab/drugLabel> ?drugLabel.
"""
QUERY_BIOMARKERS_TO_DEMENTIA_DRUGS ="""
SELECT DISTINCT ?drug ?drugLabel WHERE { ?biomarker_ID <http://research.tib.eu/p4-lucat/vocab/biomarker_has_indication> ?drug .
?drugdementia a <http://research.tib.eu/p4-lucat/vocab/DementiaDrug>.
?drug owl:sameAs ?drugdementia .
?biomarker_ID a <http://research.tib.eu/p4-lucat/vocab/Biomarker>.
?biomarker_ID <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?biomarker.
?drug <http://research.tib.eu/p4-lucat/vocab/drugLabel> ?drugLabel.
"""
QUERY_DISORDERS_TO_LCDRUGS ="""
SELECT DISTINCT ?drug ?drugLabel WHERE { ?drug a <http://research.tib.eu/p4-lucat/vocab/LungCancerDrug>.
?DrugDisorderInteraction a <http://research.tib.eu/p4-lucat/vocab/DrugDisorderInteraction>.
?DrugDisorderInteraction <http://research.tib.eu/p4-lucat/vocab/precipitantDrug> ?drug.
?DrugDisorderInteraction <http://research.tib.eu/p4-lucat/vocab/objectIndication> ?indication_ID.
?indication_ID <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?indication.
?drug <http://research.tib.eu/p4-lucat/vocab/drugLabel> ?drugLabel.
"""
QUERY_DISORDERS_TO_DEMENTIA_DRUGS ="""
SELECT DISTINCT ?drug ?drugLabel WHERE { ?drugdementia a <http://research.tib.eu/p4-lucat/vocab/DementiaDrug>.
?drug owl:sameAs ?drugdementia .
?drugDisorder a <http://research.tib.eu/p4-lucat/vocab/DrugDisorderInteraction>.
?drugDisorder <http://research.tib.eu/p4-lucat/vocab/interactor1_Drug> ?drug.
?drug <http://research.tib.eu/p4-lucat/vocab/drugLabel> ?drugLabel.
?drugDisorder <http://research.tib.eu/p4-lucat/vocab/interactor2Indication> ?indication_ID.
?indication_ID <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?indication.
"""
QUERY_CUI_TO_DRUGS = """
SELECT DISTINCT ?drug ?drugBankID WHERE {
?drug <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?drugCUI.
?drug <http://research.tib.eu/p4-lucat/vocab/drugBankID> ?drugBankID
FILTER(isURI(?drugBankID))
"""
QUERY_DRUGS_TO_SIDEEFFECTS_LC ="""
SELECT DISTINCT ?drugLabel ?sideEffectLabel WHERE { ?drug a <http://research.tib.eu/p4-lucat/vocab/Drug>.
?drug <http://research.tib.eu/p4-lucat/vocab/drugLabel> ?drugLabel.
?drug <http://research.tib.eu/p4-lucat/vocab/drug_isRelatedTo_dse> ?drugSideEffect.
?drugSideEffect <http://research.tib.eu/p4-lucat/vocab/dse_AvgFrequency> ?freqStr.
?sideEffectLabel <http://research.tib.eu/p4-lucat/vocab/sideEffect_isRelatedTo_dse> ?drugSideEffect.
"""
QUERY_DRUGS_TO_SIDEEFFECTS_ALL ="""
SELECT DISTINCT ?drugLabel ?sideEffectLabel WHERE { ?drug a <http://research.tib.eu/p4-lucat/vocab/Drug>.
?drug <http://research.tib.eu/p4-lucat/vocab/drugLabel> ?drugLabel.
?drug <http://research.tib.eu/p4-lucat/vocab/drug_isRelatedTo_dse> ?drugSideEffect.
?drugSideEffect <http://research.tib.eu/p4-lucat/vocab/dse_AvgFrequency> ?freqStr.
?sideEffectLabel <http://research.tib.eu/p4-lucat/vocab/sideEffect_isRelatedTo_dse> ?drugSideEffect.
"""
QUERY_DRUGS_TO_SIDEEFFECTS_AD_D ="""
SELECT DISTINCT ?drugLabel ?sideEffectLabel WHERE { ?drug a <http://research.tib.eu/p4-lucat/vocab/Drug>.
?drug <http://research.tib.eu/p4-lucat/vocab/drugLabel> ?drugLabel.
?drug <http://research.tib.eu/p4-lucat/vocab/drug_isRelatedTo_dse> ?drugSideEffect.
?drugSideEffect <http://research.tib.eu/p4-lucat/vocab/dse_AvgFrequency> ?freqStr.
?sideEffectLabel <http://research.tib.eu/p4-lucat/vocab/sideEffect_isRelatedTo_dse> ?drugSideEffect.
"""
QUERY_CUI_TO_LCDRUGS = """
SELECT DISTINCT ?drug ?drugBankID WHERE {
?drug a <http://research.tib.eu/p4-lucat/vocab/LungCancerDrug>.
?drug <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?drugCUI.
?drug <http://research.tib.eu/p4-lucat/vocab/drugBankID> ?drugBankID
FILTER(isURI(?drugBankID))
"""
QUERY_CUI_TO_DEMENTIA_DRUGS = """
SELECT DISTINCT ?drug ?drugBankID WHERE {
?drugdementia a <http://research.tib.eu/p4-lucat/vocab/DementiaDrug>.
?drug owl:sameAs ?drugdementia .
?drug <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?drugCUI.
?drug <http://research.tib.eu/p4-lucat/vocab/drugBankID> ?drugBankID.
FILTER(isURI(?drugBankID))
"""
QUERY_CUI_TO_AD_DRUGS = """
SELECT DISTINCT ?drug ?drugBankID WHERE {
?drug a <http://research.tib.eu/p4-lucat/vocab/ADDrug>.
?drug <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?drugCUI.
?drug <http://research.tib.eu/p4-lucat/vocab/drugBankID> ?drugBankID.
FILTER(isURI(?drugBankID))
"""
QUERY_DISORDERS_TO_AD_DRUGS ="""
SELECT DISTINCT ?drug ?drugLabel WHERE { ?drug a <http://research.tib.eu/p4-lucat/vocab/ADDrug>.
?drugDisorder a <http://research.tib.eu/p4-lucat/vocab/DrugDisorderInteraction>.
?drugDisorder <http://research.tib.eu/p4-lucat/vocab/interactor1_Drug> ?drug.
?drug <http://research.tib.eu/p4-lucat/vocab/drugLabel> ?drugLabel.
?drugDisorder <http://research.tib.eu/p4-lucat/vocab/interactor2Indication> ?indication_ID.
?indication_ID <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?indication.
"""
QUERY_BIOMARKERS_TO_AD_DRUGS ="""
SELECT DISTINCT ?drug ?drugLabel WHERE { ?biomarker_ID <http://research.tib.eu/p4-lucat/vocab/biomarker_has_indication> ?drug .
?drug a <http://research.tib.eu/p4-lucat/vocab/ADDrug>.
?biomarker_ID a <http://research.tib.eu/p4-lucat/vocab/Biomarker>.
?biomarker_ID <http://research.tib.eu/p4-lucat/vocab/hasCUIAnnotation> ?biomarker.
?drug <http://research.tib.eu/p4-lucat/vocab/drugLabel> ?drugLabel.
"""
############################
#
# Query generation
#
############################
def execute_query(query):
sparql_ins = SPARQLWrapper(KG)
sparql_ins.setQuery(query)
sparql_ins.setReturnFormat(JSON)
return sparql_ins.query().convert()['results']['bindings']
############################
#
# Processing results
#
############################
def biomarkers2drugs_query(biomarkers,drugType):
if drugType=="all":
query=QUERY_BIOMARKERS_TO_ALL_DRUGS
if drugType=="lc":
query=QUERY_BIOMARKERS_TO_LC_DRUGS
elif drugType=="dementia":
query=QUERY_BIOMARKERS_TO_DEMENTIA_DRUGS
elif drugType=="ad":
query=QUERY_BIOMARKERS_TO_AD_DRUGS
query+="FILTER(?biomarker in ("
for cui in biomarkers:
query+="<http://research.tib.eu/p4-lucat/entity/"+cui+">,"
query=query[:-1]
query+="))}"
qresults = execute_query(query)
qresults=[(item['drug']['value'],item['drugLabel']['value']) for item in qresults]
return qresults
def disorder2drugs_query(disorders,drugType='all'):
if drugType=='all':
query=QUERY_DISORDERS_TO_DRUGS
elif drugType=='lc' :
query=QUERY_DISORDERS_TO_LCDRUGS
elif drugType=='dementia' :
query=QUERY_DISORDERS_TO_DEMENTIA_DRUGS
elif drugType=='ad' :
query=QUERY_DISORDERS_TO_AD_DRUGS
query+="FILTER(?indication in ("
for cui in disorders:
query+="<http://research.tib.eu/p4-lucat/entity/"+cui+">,"
query=query[:-1]
query+="))}"
qresults = execute_query(query)
qresults=[(item['drug']['value'],item['drugLabel']['value']) for item in qresults]
return qresults
def drugsCUI2drugID_query(drugs,drugType='all'):
if drugType=='all':
query=QUERY_CUI_TO_DRUGS
elif drugType=='lc' :
query=QUERY_CUI_TO_LCDRUGS
elif drugType=='dementia' :
query=QUERY_CUI_TO_DEMENTIA_DRUGS
elif drugType=='ad' :
query=QUERY_CUI_TO_AD_DRUGS
query+="FILTER(?drugCUI in ("
for drug in drugs:
query+="<http://research.tib.eu/p4-lucat/entity/"+drug+">,"
query=query[:-1]
query+="))}"
qresults = execute_query(query)
qresults=[(item['drugBankID']['value'],item['drug']['value']) for item in qresults]
return qresults
def drug2sideEffect_query(drugs,topic,threshold):
if topic=="all":
query=QUERY_DRUGS_TO_SIDEEFFECTS_ALL
if topic=="lc":
query=QUERY_DRUGS_TO_SIDEEFFECTS_LC
elif topic=="dementia" or topic=="ad":
query=QUERY_DRUGS_TO_SIDEEFFECTS_AD_D
if threshold!=0:
query+="BIND(xsd:float(?freqStr) AS ?freq)"
query += "FILTER(?freq >= "+str(threshold/100)+")"
query+="FILTER(?drug in ("
for drug in drugs:
query+="<"+drug+">,"
query=query[:-1]
query+="))} ORDER BY DESC(?freqStr)"
qresults = execute_query(query)
qresults=[(item['drugLabel']['value'],item['sideEffectLabel']['value'].replace("http://research.tib.eu/p4-lucat/entity/","").replace("_"," ")) for item in qresults]
return qresults
def sideEffects_filtering_sorting(sideEffects, page, sort, limit):
# Sorting the side effects for each drug
for drug in sideEffects:
sideEffects[drug].sort(key=lambda x: x['sideEffect'])
# Sorting the drugs
sorted_drugs = sorted(sideEffects.items())
# Converting the sorted list back to a dictionary
sorted_dict = dict(sorted_drugs)
# if limit==-1: return the entire sorted_dict
if limit == -1:
return sorted_dict
# For pagination
if page == 0:
return {k: sorted_dict[k] for k in list(sorted_dict)[page:limit]}
else:
return {k: sorted_dict[k] for k in list(sorted_dict)[page*limit:(page*limit)+limit]}
def check_dict_duplicate(list_of_dict,dict_):
for dic in list_of_dict:
count=0
for key,value in dic.items():
if dict_[key]==value:
count=count+1
if count==len(dict_):
return True
return False
def remove_duplicates(lst):
seen = set()
no_duplicates = [item for item in lst if (item['sideEffect'], item['group']) not in seen and not seen.add((item['sideEffect'], item['group']))]
return no_duplicates
def proccesing_response(input_dicc, topic,limit,page,sort,threshold):
cuis=dict()
codicc=dict()
sideEffects=dict()
for elem in input_dicc:
lcuis = input_dicc[elem]
if len(lcuis)==0:
continue
for item in lcuis:
cuis[item]=elem
if len(cuis)==0:
continue
##############################sideEffects################################3
if elem=='comorbidities' or elem=='histology':
drugs=disorder2drugs_query(input_dicc[elem],topic)
elif elem=='biomarkers':
drugs=biomarkers2drugs_query(input_dicc[elem],topic)
elif elem in ['LCdrugs']:
drugs=drugsCUI2drugID_query(input_dicc[elem],topic)
if len(drugs)!=0:
drug_sideEffects=drug2sideEffect_query([drug[0] for drug in drugs],topic,threshold)
for item in drug_sideEffects:
if item[0] not in sideEffects:
sideEffects[item[0]]=[]
sideEffects[item[0]].append({"sideEffect": urllib.parse.unquote(item[1]) , "group": elem})
######################################################################################
for drug in sideEffects:
sideEffects[drug] = remove_duplicates(sideEffects[drug])
codicc['sideEffects']={}
codicc['sideEffects']['resultsTotal'] = len(sideEffects)
codicc['sideEffects']['results'] = sideEffects_filtering_sorting(sideEffects,page,0,limit)
return codicc
@app.route('/exploration', methods=['POST'])
def run_exploration_api():
if (not request.json):
abort(400)
if 'topic' in request.args:
topic = request.args['topic']
else:
abort(400)
if 'limit' in request.args:
limit = int(request.args['limit'])
else:
limit = LIMIT
if 'page' in request.args:
page = int(request.args['page'])
else:
page = 0
if 'sort' in request.args:
sort = request.args['sort']
else:
sort = 0
if 'threshold' in request.args:
threshold = int(request.args['threshold'])
else:
threshold = 0
input_list = request.json
if len(input_list) == 0:
logger.info("Error in the input format")
r = "{results: 'Error in the input format'}"
else:
response = proccesing_response(input_list, topic,limit,page,sort,threshold)
r = json.dumps(response, indent=4)
logger.info("Sending the results: ")
response = make_response(r, 200)
response.mimetype = "application/json"
return response
def main(*args):
if len(args) == 1:
myhost = args[0]
else:
myhost = "0.0.0.0"
app.run(debug=False, host=myhost)
if __name__ == '__main__':
main(*sys.argv[1:])