Repository navigation
Expand file tree
/
Copy pathkgg_utils.py
More file actions
2355 lines (1858 loc) · 73.1 KB
/
Copy pathkgg_utils.py
File metadata and controls
2355 lines (1858 loc) · 73.1 KB
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
# -*- coding: utf-8 -*-
import io
import json
import logging
import os
import pickle
import tempfile
import zipfile
from collections import Counter, defaultdict
import networkx as nx
import pandas as pd
import plotly
import plotly.express as px
import plotly.graph_objects as go
import pybel
import pybel.struct.mutation.induction as induction
import pybel_jupyter
import requests
import streamlit as st
from chembl_webresource_client.new_client import new_client
from pandasgwas import get_variants
from pandasgwas.get_variants import get_variants_by_efo_id
from plotly.subplots import make_subplots
from pybel import BELGraph
from pybel.dsl import Abundance, BiologicalProcess, Gene, Pathology, Protein
from rdkit import Chem
from rdkit.Chem import Descriptors
from stqdm import stqdm
logger = logging.getLogger("__name__")
DATA_DIR = "data/"
def load_kg(path):
infile = open(path, "rb")
kg = pickle.load(infile)
infile.close()
return kg
state = st.session_state
def disease_figures(disease_name, graph: BELGraph = None):
"""Function to generate figures for the disease overview."""
if graph is None:
disease_name = disease_name.lower()
data_files = os.listdir(DATA_DIR + f"{disease_name}_kgg")
graph_path = [file for file in data_files if file.endswith(".pkl")][0]
# Basic graph stats
graph = load_kg(DATA_DIR + f"{disease_name}_kgg/" + graph_path)
nodes_data = {}
for node in graph.nodes():
if type(node).__name__ not in nodes_data:
nodes_data[type(node).__name__] = 0
nodes_data[type(node).__name__] += 1
edge_dict = {}
for source, target in graph.edges(data=False):
s = type(source).__name__
t = type(target).__name__
if f"{s}-{t}" not in edge_dict and f"{t}-{s}" not in edge_dict:
edge_dict[f"{s}-{t}"] = 0
if f"{s}-{t}" in edge_dict:
edge_dict[f"{s}-{t}"] += 1
if f"{t}-{s}" in edge_dict:
edge_dict[f"{t}-{s}"] += 1
node_df = pd.DataFrame(nodes_data.items(), columns=["Node type", "Count"])
node_df = node_df.sort_values(by="Count", ascending=False)
edge_df = pd.DataFrame(edge_dict.items(), columns=["Edge type", "Count"])
edge_df = edge_df.sort_values(by="Count", ascending=False)
fig = make_subplots(rows=1, cols=2, subplot_titles=("Node summary", "Edge summary"))
fig.append_trace(
go.Bar(
x=node_df["Node type"],
y=node_df["Count"],
text=node_df["Count"],
),
row=1,
col=1,
)
fig.append_trace(
go.Bar(
x=edge_df["Edge type"],
y=edge_df["Count"],
text=edge_df["Count"],
),
row=1,
col=2,
)
fig.update_layout(title="Graph summary", showlegend=False)
# Update xaxis properties
fig.update_xaxes(title_text="Node types", row=1, col=1)
fig.update_xaxes(title_text="Edge types", row=1, col=2)
# Update yaxis properties
fig.update_yaxes(title_text="Count", row=1, col=1)
fig.update_yaxes(title_text="Count", row=1, col=2)
st.plotly_chart(fig, use_container_width=True)
# Namespace summary
namespace_data = {}
for node in graph.nodes():
if node.namespace not in namespace_data:
namespace_data[node.namespace] = 0
namespace_data[node.namespace] += 1
namespace_df = pd.DataFrame(namespace_data.items(), columns=["Namespace", "Count"])
namespace_df = namespace_df.sort_values(by="Count", ascending=False)
figure_ns = go.Figure()
figure_ns.add_trace(
go.Bar(
x=namespace_df["Namespace"],
y=namespace_df["Count"],
text=namespace_df["Count"],
marker_color="#ed872d",
)
)
figure_ns.update_layout(title="Namespace summary")
figure_ns.update_xaxes(title_text="Namespace")
figure_ns.update_yaxes(title_text="Count")
st.plotly_chart(figure_ns, use_container_width=True)
if "figures" not in state:
state["figures"] = {}
state["figures"]["graph_summary"] = fig
state["figures"]["namespace_summary"] = figure_ns
# TODO: Add drug specific information
def RetMech(chemblIds) -> list:
"""Function to retrieve mechanism of actions and target proteins from ChEMBL
:param chemblIds:
:return:
"""
# Create a placeholder for displaying current progress
getMech = new_client.mechanism
mechList = []
for chemblid in stqdm(chemblIds, desc="Fetching mechanims of actions"):
mechs = getMech.filter(molecule_chembl_id=chemblid).only(
["mechanism_of_action", "target_chembl_id", "action_type"]
)
mechList.append(list(mechs))
named_mechList = dict(zip(chemblIds, mechList))
named_mechList = {k: v for k, v in named_mechList.items() if v}
return named_mechList
def RetAct(chemblIds) -> dict:
"""Function to retrieve associated assays from ChEMBL
:param chemblIds:
:return:
"""
GetAct = new_client.activity
getTar = new_client.target
ActList = []
filtered_list = [
"assay_chembl_id",
"assay_type",
"pchembl_value",
"target_chembl_id",
"target_organism",
"bao_label",
"target_type",
]
for chembl in stqdm(chemblIds, desc="Fetching targets and associated assays"):
acts = GetAct.filter(
molecule_chembl_id=chembl,
pchembl_value__isnull=False,
assay_type_iregex="(B|F)",
target_organism="Homo sapiens",
).only(filtered_list)
data = []
for d in acts:
if float(d.get("pchembl_value")) < 6:
continue
if d.get("bao_label") != "single protein format":
continue
tar = d.get("target_chembl_id")
tar_dict = getTar.get(tar)
try:
if tar_dict["target_type"] in ("CELL-LINE", "UNCHECKED"):
continue
except KeyError:
continue
data.append(d)
ActList.append(list(data))
named_ActList = dict(zip(chemblIds, ActList))
named_ActList = {k: v for k, v in named_ActList.items() if v}
return named_ActList
def RetDrugInd(chemblIDs) -> dict:
"""Function to retrieve associated diseases from ChEMBL
:param chemblIDs:
:return:
"""
getDrugInd = new_client.drug_indication
drugIndList = []
for chemblid in chemblIDs:
drugInd = getDrugInd.filter(molecule_chembl_id=chemblid).only("mesh_heading")
drugIndList.append(list(drugInd))
named_drugIndList = dict(zip(chemblIDs, drugIndList))
named_drugIndList = {k: v for k, v in named_drugIndList.items() if v}
return named_drugIndList
def Ret_chembl_protein(sourceList) -> list:
"""Method to retrieve ChEMBL ids which are proteins/targets
:param sourceList:
:return:
"""
protein_List = []
for item in sourceList:
for j in range(len(sourceList[item])):
protein_List.append(sourceList[item][j]["target_chembl_id"])
protein_List = set(protein_List)
protein_List = list(filter(None, protein_List))
return protein_List
def chembl2uniprot(chemblIDs) -> dict:
"""Method to convert ChEMBL id to UNIPROT and get associated REACTOME pathways
:param chemblIDs:
:return:
"""
getTarget = new_client.target
chem2Gene2path = []
chemHasNoPath = set()
chemNotprotein = set()
chem2path = defaultdict(list)
# Loop to ensure it is a protein
for chemblid in chemblIDs:
chem = getTarget.filter(chembl_id=chemblid).only("target_components")
try:
uprot_id = chem[0]["target_components"][0]["accession"]
if not uprot_id:
chemHasNoPath.add(chemblid)
except IndexError:
chemHasNoPath.add(chemblid)
logger.info(f"No UniProt information available for {len(chemHasNoPath)} proteins.")
chemblIDs_filtered = [item for item in chemblIDs if item not in chemHasNoPath]
# Get gene symbol from ChEMBL and filtering the list for human proteins only
for chemblid in chemblIDs_filtered:
chem = getTarget.filter(chembl_id=chemblid).only("target_components")
getGene = chem[0]["target_components"][0]["target_component_synonyms"]
try:
getGene = [item for item in getGene if item["syn_type"] == "GENE_SYMBOL"][0]
if not getGene:
chemNotprotein.add(chemblid)
except IndexError:
chemNotprotein.add(chemblid)
chemblIDs_filtered = [
item for item in chemblIDs_filtered if item not in chemNotprotein
]
# Extracting data for valid proteins only
for chemblid in chemblIDs_filtered:
chem = getTarget.filter(chembl_id=chemblid).only("target_components")
# UniProt data
uprot_id = chem[0]["target_components"][0]["accession"]
# Gene symbol
getGene = chem[0]["target_components"][0]["target_component_synonyms"]
getGene = [item for item in getGene if item["syn_type"] == "GENE_SYMBOL"][0]
# Pathway data
chem2path = [
item
for item in chem[0]["target_components"][0]["target_component_xrefs"]
if item["xref_src_db"] == "Reactome"
]
uprot = {"accession": uprot_id}
chem2path.append(uprot)
chem2path.append(getGene)
chem2Gene2path.append(chem2path)
named_chem2Gene2path = dict(zip(chemblIDs_filtered, chem2Gene2path))
named_chem2Gene2path = {k: v for k, v in named_chem2Gene2path.items() if v}
return named_chem2Gene2path
def chembl2gene2path(chem2geneList, ActList):
"""Method for updating chembl protein nodes with gene symbol.
:param chem2geneList:
:param ActList:
:return:
"""
for item in chem2geneList:
sizeOfitem = len(chem2geneList[item])
gene = chem2geneList[item][sizeOfitem - 1]["component_synonym"]
# uniprot id is located in 2nd last pos
uprot = chem2geneList[item][-2]["accession"]
for jtem in ActList:
for i in range(len(ActList[jtem])):
if item == ActList.get(jtem)[i]["target_chembl_id"]:
newkey = {"Protein": gene, "Accession": uprot}
ActList[jtem][i].update(newkey)
return ActList
# def chembl2gene2path(chem2geneList, ActList):
# """Method for updating chembl protein nodes with gene symbol.
#
# :param chem2geneList:
# :param ActList:
# :return:
# """
# for item in chem2geneList:
# sizeOfitem = len(chem2geneList[item])
# gene = chem2geneList[item][sizeOfitem - 1]["component_synonym"]
# for jtem in ActList:
# for i in range(len(ActList[jtem])):
# if item == ActList.get(jtem)[i]["target_chembl_id"]:
# newkey = {"Protein": gene}
# ActList[jtem][i].update(newkey)
#
# return ActList
def chem2moa_rel(named_mechList, org, otp_prots, graph: BELGraph) -> BELGraph:
"""Method to create the monkeypox graph
:param named_mechList:
:param org:
:param graph: BEL graph of Monkeypox
:return:
"""
# identified types of chemical and protein action types
# ['INHIBITOR','NEGATIVE ALLOSTERIC MODULATOR','POSITIVE ALLOSTERIC MODULATOR','ANTAGONIST','AGONIST','MODULATOR','BLOCKER','ACTIVATOR','DISRUPTING AGENT', 'SUBSTRATE', 'OPENER','PARTIAL AGONIST','SEQUESTERING AGENT']
# following lists are used to determine type of edge relationships
pos = ["POSITIVE ALLOSTERIC MODULATOR", "AGONIST", "ACTIVATOR", "PARTIAL AGONIST"]
neg = ["INHIBITOR", "NEGATIVE ALLOSTERIC MODULATOR", "ANTAGONIST", "BLOCKER"]
misc = [
"MODULATOR",
"DISRUPTING AGENT",
"SUBSTRATE",
"OPENER",
"SEQUESTERING AGENT",
]
for chembl_name, chembl_entries in stqdm(
named_mechList.items(), desc="Populating Chemical-MoA edges"
):
for info in chembl_entries:
graph.add_qualified_edge(
Abundance(namespace="ChEMBL", name=chembl_name),
BiologicalProcess(namespace="MOA", name=info["mechanism_of_action"]),
relation="hasMechanismOfAction",
citation="ChEMBL database",
evidence="ChEMBL query",
)
if not info["target_chembl_id"]:
continue
if (
"Protein" in info
and "Accession" in info
and info["Accession"] in otp_prots
):
if info["action_type"] in pos and info["Accession"] in otp_prots:
graph.add_increases(
Abundance(namespace="ChEMBL", name=chembl_name),
Protein(namespace=org, name=info["Protein"]),
citation="ChEMBL database",
evidence="ChEMBL query",
)
if info["action_type"] in neg and info["Accession"] in otp_prots:
graph.add_decreases(
Abundance(namespace="ChEMBL", name=chembl_name),
Protein(namespace=org, name=info["Protein"]),
citation="ChEMBL database",
evidence="ChEMBL query",
)
if info["action_type"] in misc and info["Accession"] in otp_prots:
graph.add_qualified_edge(
Abundance(namespace="ChEMBL", name=chembl_name),
Protein(namespace=org, name=info["Protein"]),
relation="targets",
citation="ChEMBL database",
evidence="ChEMBL query",
)
# else:
# graph.add_association(
# Abundance(namespace='ChEMBL', name=chembl_name),
# Protein(namespace=org, name=info['target_chembl_id']),
# citation='ChEMBL database',
# evidence='ChEMBL query'
# )
return graph
def chem2act_rel(named_ActList, org, otp_prots, graph: BELGraph) -> BELGraph:
"""Method to add bioassay edges to the KG.
:param named_ActList:
:param org:
:param graph:
:return:
"""
for chemical, chem_entries in stqdm(
named_ActList.items(), desc="Adding bioassay edges to BEL"
):
for chem_data in chem_entries:
if chem_data["target_chembl_id"]:
if (
"Protein" in chem_data
and "Accession" in chem_data
and chem_data["Accession"] in otp_prots
):
graph.add_qualified_edge(
Abundance(
namespace="ChEMBLAssay", name=chem_data["assay_chembl_id"]
),
Protein(namespace=org, name=chem_data["Protein"]),
relation="hasTarget",
citation="ChEMBL database",
evidence="ChEMBL query",
)
# else:
# graph.add_association(
# Abundance(namespace='ChEMBLAssay', name=chem_data['assay_chembl_id']),
# Protein(namespace=org, name=chem_data['target_chembl_id']),
# citation='ChEMBL database',
# evidence='ChEMBL query'
# )
graph.add_qualified_edge(
Abundance(namespace="ChEMBL", name=chemical),
Abundance(namespace="ChEMBLAssay", name=chem_data["assay_chembl_id"]),
relation="hasAssay",
citation="ChEMBL database",
evidence="ChEMBL query",
annotation={
"assayType": chem_data["assay_type"],
"pChEMBL": chem_data["pchembl_value"],
},
)
return graph
def gene2path_rel(named_chem2geneList, org, otp_prots, graph) -> BELGraph:
"""Method to add protein and reactome data to KG
:param named_chem2geneList:
:param org:
:param graph:
:return:
"""
for item in named_chem2geneList:
itemLen = len(named_chem2geneList[item]) - 1
for j in range(itemLen - 1):
# checks if uprot id is in otp_proteins
if named_chem2geneList[item][itemLen - 1]["accession"] in otp_prots:
graph.add_qualified_edge(
Protein(
namespace=org,
name=named_chem2geneList[item][itemLen]["component_synonym"],
),
BiologicalProcess(
namespace="Reactome",
name=named_chem2geneList[item][j]["xref_name"],
),
relation="hasPathway",
citation="ChEMBL database",
evidence="ChEMBL query",
annotation={
"Reactome": "https://reactome.org/content/detail/"
+ named_chem2geneList[item][j]["xref_id"]
},
)
return graph
def uniprot_rel(named_uprotList, org, graph) -> BELGraph:
"""Method to add UniProt related edges
:param named_uprotList:
:param org:
:param graph:
:return:
"""
for item in stqdm(named_uprotList, desc="Populating Uniprot edges"):
fun = list(named_uprotList[item]["Function"].keys())
bp = list(named_uprotList[item]["BioProcess"].keys())
for f in fun:
if str(named_uprotList[item]["Gene"]) != "nan" and not isinstance(
named_uprotList[item]["Gene"], dict
):
graph.add_qualified_edge(
Protein(namespace=org, name=named_uprotList[item]["Gene"]),
BiologicalProcess(namespace="GOMF", name=f),
relation="hasMolecularFunction",
citation="UniProt database",
evidence="UniProt query",
)
else:
graph.add_qualified_edge(
Protein(namespace=org, name=item),
BiologicalProcess(namespace="GOMF", name=f),
relation="hasMolecularFunction",
citation="UniProt database",
evidence="UniProt query",
)
for b in bp:
if str(named_uprotList[item]["Gene"]) != "nan" and not isinstance(
named_uprotList[item]["Gene"], dict
):
graph.add_qualified_edge(
Protein(namespace=org, name=named_uprotList[item]["Gene"]),
BiologicalProcess(namespace="GOBP", name=b),
relation="hasBiologicalProcess",
citation="UniProt database",
evidence="UniProt query",
)
else:
graph.add_qualified_edge(
Protein(namespace=org, name=item),
BiologicalProcess(namespace="GOBP", name=b),
relation="hasBiologicalProcess",
citation="UniProt database",
evidence="UniProt query",
)
if str(named_uprotList[item]["Gene"]) != "nan" and not isinstance(
named_uprotList[item]["Gene"], dict
):
nx.set_node_attributes(
graph,
{
Protein(
namespace=org, name=named_uprotList[item]["Gene"]
): "https://3dbionotes.cnb.csic.es/?queryId=" + item
},
"3Dbio",
)
nx.set_node_attributes(
graph,
{
Protein(
namespace=org, name=named_uprotList[item]["Gene"]
): "https://www.uniprot.org/uniprotkb/" + item
},
"UniProt",
)
else:
nx.set_node_attributes(
graph,
{
Protein(
namespace=org, name=item
): "https://3dbionotes.cnb.csic.es/?queryId=" + item
},
"3Dbio",
)
nx.set_node_attributes(
graph,
{
Protein(
namespace=org, name=item
): "https://www.uniprot.org/uniprotkb/" + item
},
"UniProt",
)
return graph
def searchDisease(keyword):
"""Finding disease identifiers using OpenTargets API"""
disease_name = str(keyword)
if disease_name is None:
st.error("Please resubmit the disease.")
st.stop()
query_string = """
query searchAnything ($disname:String!){
search(queryString:$disname,entityNames:"disease",page:{size:20,index:0}){
total
hits {
id
entity
name
description
}
}
}
"""
variables = {"disname": disease_name}
# Set base URL of GraphQL API endpoint
base_url = "https://api.platform.opentargets.org/api/v4/graphql"
# Perform POST request and check status code of response
r = requests.post(base_url, json={"query": query_string, "variables": variables})
# Transform API response from JSON into Python dictionary and print in console
# if r is None:
# st.error("Please resubmit the disease.")
# st.stop()
api_response = json.loads(r.text)
df = pd.DataFrame(api_response["data"]["search"]["hits"])
if not df.empty:
df = df[df["entity"] == "disease"]
df.drop(columns=["entity"], inplace=True)
return df
else:
st.warning("Disease with given keyword is not found. Please try again!")
st.stop()
def getDrugCount(disease_id):
"""Finding the number of drugs associated with a disease using OpenTargets API"""
efo_id = disease_id
query_string = """
query associatedTargets($my_efo_id: String!){
disease(efoId: $my_efo_id){
id
name
knownDrugs{
uniqueTargets
uniqueDrugs
count
}
}
}
"""
# Set variables object of arguments to be passed to endpoint
variables = {"my_efo_id": efo_id}
# Set base URL of GraphQL API endpoint
base_url = "https://api.platform.opentargets.org/api/v4/graphql"
# Perform POST request and check status code of response
r = requests.post(base_url, json={"query": query_string, "variables": variables})
# Transform API response from JSON into Python dictionary and print in console
api_response = json.loads(r.text)
# get the count value from api_repsonse dict
api_response = api_response["data"]["disease"]["knownDrugs"]["count"]
return api_response
def GetDiseaseAssociatedDrugs(disease_id, CT_phase):
"""Finding drugs associated with a disease using OpenTargets API"""
efo_id = state.get("disease_id", "")
size = getDrugCount(efo_id)
query_string = """
query associatedTargets($my_efo_id: String!, $my_size: Int){
disease(efoId: $my_efo_id){
id
name
knownDrugs(size:$my_size){
uniqueTargets
uniqueDrugs
count
rows{
approvedSymbol
approvedName
prefName
drugType
drugId
phase
ctIds
}
}
}
}
"""
# Set variables object of arguments to be passed to endpoint
variables = {"my_efo_id": efo_id, "my_size": size}
# Set base URL of GraphQL API endpoint
base_url = "https://api.platform.opentargets.org/api/v4/graphql"
# Perform POST request and check status code of response
r = requests.post(base_url, json={"query": query_string, "variables": variables})
# Transform API response from JSON into Python dictionary and print in console
api_response = json.loads(r.text)
df = pd.DataFrame(api_response["data"]["disease"]["knownDrugs"]["rows"])
if df.empty:
st.write("No drugs found in clinical trials")
return df
df = df.loc[df["phase"] >= int(CT_phase), :]
df["id"] = efo_id
df["disease"] = api_response["data"]["disease"]["name"]
return df
@st.cache_data(ttl=3600, show_spinner="Fetching protein data...")
def GetDiseaseAssociatedProteins(efo_id):
"""Fixed version that properly handles cache invalidation"""
# st.write(f"🔄 Disease Lookup: {efo_id}")
if not efo_id:
st.error("No disease ID provided")
return pd.DataFrame()
base_url = "https://api.platform.opentargets.org/api/v4/graphql"
query = """
query associatedTargets($efoId: String!, $index: Int!) {
disease(efoId: $efoId) {
associatedTargets(page: {size: 3000, index: $index}) {
rows {
target {
id
approvedSymbol
proteinIds { id source }
}
score
}
}
}
}
"""
all_results = []
index = 0
while True:
response = requests.post(
base_url,
json={"query": query, "variables": {"efoId": efo_id, "index": index}},
)
response.raise_for_status()
data = response.json()
batch = data["data"]["disease"]["associatedTargets"]["rows"]
if not batch:
break
all_results.extend(batch)
index += 1
processed = []
for item in all_results:
target = item["target"]
for protein in target["proteinIds"]:
if protein["source"] == "uniprot_swissprot":
processed.append(
{
"Protein": target["approvedSymbol"],
"ENSG": target["id"],
"UniProt": protein["id"],
"Source": protein["source"],
"Score": item["score"],
"disease_id": efo_id,
}
)
df = pd.DataFrame(processed)
st.write(f"✅ Retrieved {len(df)} proteins for {efo_id}")
return df
# def GetDiseaseAssociatedProteins(disease_id):
# """Finding proteins associated with a disease using OpenTargets API"""
# efo_id = str(disease_id)
# query_string = """
# query associatedTargets{
# disease(efoId: $efo_id){
# id
# name
# associatedTargets(page:{size:15000,index:0}){
# count
# rows {
# target {
# id
# approvedSymbol
# proteinIds {
# id
# source
# }
# }
# score
# }
# }
# }
# }
# """
# # replace $efo_id with value from efo_id
# query_string = query_string.replace("$efo_id", f'"{efo_id}"')
# # Set base URL of GraphQL API endpoint
# base_url = "https://api.platform.opentargets.org/api/v4/graphql"
# # Perform POST request and check status code of response
# r = requests.post(base_url, json={"query": query_string})
# # Transform API response from JSON into Python dictionary and print in console
# api_response = json.loads(r.text)
# temp_list = []
# for item in api_response["data"]["disease"]["associatedTargets"]["rows"]:
# for obj in item["target"]["proteinIds"]:
# if obj["source"] == "uniprot_swissprot":
# # st.write(obj)
# uprot = obj["id"]
# source = obj["source"]
# score = item["score"]
# ensg = item["target"]["id"]
# name = item["target"]["approvedSymbol"]
# temp = {
# "Protein": name,
# "ENSG": ensg,
# "UniProt": uprot,
# "Source": source,
# "Score": score,
# }
# temp_list.append(temp)
# df = pd.DataFrame(temp_list)
# df["disease_id"] = efo_id
# return df
def GetDiseaseAssociatedProteinsPlot(df):
"""Plotting the protein confidence scores associated with a disease."""
if "figures" in st.session_state and "protein_score" in st.session_state.figures:
del st.session_state.figures["protein_score"]
st.markdown("**Protein-Disease Association summary**")
st.markdown(
f"""We have identified {len(df)} proteins (Swiss-Prot) associated with the disease.
Please note that the proteins identified may not be unique if you combined two or more diseases.
Following is a histogram that shows distribution of proteins based on scores provided by OpenTargets.
The scores are influenced by various factors such as genetic associations, expression,
mutations, known pathways, targeting drugs and so on."""
)
prot_fig = go.Figure()
prot_fig.add_trace(
go.Bar(
x=df["Protein"].head(20),
y=df["Score"].head(20),
marker=dict(color="#a4d3b3"),
name="Protein",
)
)
current_disease = st.session_state.get("user_disease", "Unknown Disease")
# st.write(f"The disease name is {current_disease}")
prot_fig.update_layout(
title=f"Distribution of top 20 proteins for {current_disease} based on OpenTargets score",
xaxis_title="Protein",
yaxis_title="Score",
)
st.plotly_chart(prot_fig, use_container_width=True)
st.caption(f"Top 20 proteins based on OpenTargets score")
if "figures" not in st.session_state:
st.session_state.figures = {}
st.session_state.figures["protein_score"] = prot_fig
def clearPlotsandGraphs():
"""
This function clears the plots and graphs from the session state.
"""
if "figures" in state:
del state["figures"]
if "graphs" in state:
del state["graphs"]
if "graph_summary" in state:
del state["graph_summary"]
if "namespace_summary" in state:
del state["namespace_summary"]
def ExtractFromUniProt(uniprot_id) -> dict:
"""Uniprot parser to retrieve information about OMIM disease, reactome pathway, biological process,
and molecular functions.
:param uniprot_id:
:return:
"""
Uniprot_Dict = []
mapped_uprot = []
for id in stqdm(uniprot_id, "Extracting data from UniProt"):
# Retrieve data for id in text format if found in uniprot
ret_uprot = requests.get(
"https://www.uniprot.org/uniprot/" + id + ".txt"
).text.split("\n")
if ret_uprot == [""]:
continue
id_copy = id
mapped_uprot.append(id_copy)
k = 0
id = {}
id["Disease"] = {}
id["Reactome"] = {}
id["Function"] = {}
id["BioProcess"] = {}
id["Gene"] = {}
# parse each line looking for info about disease, pathway, funcn, bp and so on
for line in ret_uprot:
# parse lines with disease and extract disease names and omim ids
if "-!- DISEASE:" in line:
if "[MIM:" in line:
dis = line.split(":")
id["Disease"].update({dis[1][1:-5]: dis[2][:-1]})
# extract reactome ids and names
if "Reactome;" in line:
ract = line.split(";")