-
Notifications
You must be signed in to change notification settings - Fork 1
/
poppy_create.py
executable file
·2188 lines (1854 loc) · 71.2 KB
/
poppy_create.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 python3
# Import modules
import networkx as nx
import re
import sys
import os
import argparse
import pickle
import time
import queue
import threading
import multiprocessing as mp
from requests import get as rget
from rdkit import Chem
from copy import deepcopy
from itertools import repeat, product, combinations
# Import scripts
import mineclient3 as mc
from poppy_helpers import *
from poppy_origin_helpers import *
from poppy_KEGG_helpers import *
from progress import Progress
# Specify path to repository
global repo_dir
repo_dir = os.path.dirname(__file__)
# Define functions
def allow_reaction_listing(kegg_comp, kegg_rxn):
"""Determine whether to allow the compound to list the reaction"""
# Is the compound inorganic?
inorganic_C = ["C00011","C00288","C01353","C00237"]
if 'Formula' in kegg_comp.keys():
if not limit_carbon(kegg_comp, 0) or kegg_comp['_id'] in inorganic_C:
return False
else:
# Does the compound have a formula?
return False
# Is the compound CoA, ACP or SAM?
if kegg_comp['_id'] in {"C00010", "C00229", "C00019"}:
return False
# Is the compound a cofactor?
cofactor_pairs = {
"C00004" : ("C00004", "C00003"), # NADH/NAD+
"C00003" : ("C00004", "C00003"), # NADH/NAD+
"C00005" : ("C00005", "C00006"), # NADPH/NADP+
"C00006" : ("C00005", "C00006"), # NADPH/NADP+
"C01352" : ("C01352", "C00016"), # FADH2/FAD
"C00016" : ("C01352", "C00016"), # FADH2/FAD
"C00113" : ("C00113", "C01359"), # PQQ/PQQH2
"C01359" : ("C00113", "C01359"), # PQQ/PQQH2
"C00019" : ("C00019", "C00021"), # SAM/S-Adenosyl-L-homocysteine
"C00021" : ("C00019", "C00021"), # SAM/S-Adenosyl-L-homocysteine
"C00342" : ("C00342", "C00343"), # Thioredoxin/Thiredoxin disulfide
"C00343" : ("C00342", "C00343"), # Thioredoxin/Thiredoxin disulfide
"C00399" : ("C00399", "C00390"), # Ubiquinone/Ubiquinol
"C00390" : ("C00399", "C00390"), # Ubiquinone/Ubiquinol
"C00138" : ("C00138", "C00139"), # Ferredoxin (red/ox)
"C00139" : ("C00138", "C00139") # Ferredoxin (red/ox)
}
try:
C = cofactor_pairs[kegg_comp['_id']]
R = [c[1] for c in kegg_rxn['Reactants']]
P = [c[1] for c in kegg_rxn['Products']]
if C[0] in R and C[1] in P:
return False
if C[0] in P and C[1] in R:
return False
except KeyError:
pass
# Is the compound a nucleotide involved in a reaction with nucleotides on
# both reactant and product sides?
nucleotides = [
'C00002','C00008','C00020', # ATP, ADP, AMP
'C00075','C00015','C00105', # UTP, UDP, UMP
'C00044','C00035','C00144', # GTP, GDP, GMP
'C00063','C00112','C00055', # CTP, CDP, CMP
'C00054','C03850','C18344' # AXP variants
]
if kegg_comp['_id'] in nucleotides:
R = [c[1] for c in kegg_rxn['Reactants']]
P = [c[1] for c in kegg_rxn['Products']]
r_nucs = [k for k in R if k in nucleotides]
p_nucs = [k for k in P if k in nucleotides]
if r_nucs and p_nucs:
return False
# If the compound passed all the tests, the reaction is free to be listed
return True
def sort_KEGG_reactions(kegg_comp_dict, kegg_rxn_dict, verbose=False):
"""
Re-organizes reactions of a KEGG compound into 'Reactant_in' and
'Product_of' categories based on the information contained in the reactions
dictionary.
"""
# Go through all compounds
for kegg_comp_id in kegg_comp_dict.keys():
kegg_comp = kegg_comp_dict[kegg_comp_id]
# Go through its reactions
if "Reactions" in kegg_comp.keys():
for rxn_id in kegg_comp["Reactions"]:
if rxn_id in kegg_rxn_dict.keys():
rxn = kegg_rxn_dict[rxn_id]
else:
if verbose:
s_err("Warning: '" + kegg_comp_id + \
"' lists missing reaction '" + rxn_id + "'.\n")
continue
# Check if a reaction listing is allowed
if not allow_reaction_listing(kegg_comp, rxn):
continue
# Add to Reactant_in list
if "Reactants" in rxn.keys():
if kegg_comp_id in [x[1] for x in rxn["Reactants"]]:
try:
kegg_comp_dict[kegg_comp_id]\
['Reactant_in'].append(rxn["_id"])
except KeyError:
kegg_comp_dict[kegg_comp_id]\
['Reactant_in'] = [rxn["_id"]]
# Add to Product_of list
if "Products" in rxn.keys():
if kegg_comp_id in [x[1] for x in rxn["Products"]]:
try:
kegg_comp_dict[kegg_comp_id]\
['Product_of'].append(rxn["_id"])
except KeyError:
kegg_comp_dict[kegg_comp_id]\
['Product_of'] = [rxn["_id"]]
def get_raw_KEGG(kegg_comp_ids=[], kegg_rxn_ids=[], krest="http://rest.kegg.jp",
n_threads=128, test_limit=0):
"""
Downloads all KEGG compound (C) and reaction (R) records and formats them
as MINE database compound or reaction entries. The final output is a tuple
containing a compound dictionary and a reaction dictionary.
Alternatively, downloads only a supplied list of compounds and reactions.
"""
s_out("\nDownloading KEGG data via %s/...\n" % krest)
# Acquire list of KEGG compound IDs
if not len(kegg_comp_ids):
s_out("Downloading KEGG compound list...")
r = rget("/".join([krest,"list","compound"]))
if r.status_code == 200:
for line in r.text.split("\n"):
if line == "": break # The end
kegg_comp_id = line.split()[0].split(":")[1]
kegg_comp_ids.append(kegg_comp_id)
else:
msg = "Error: Unable to download KEGG rest compound list.\n"
sys.exit(msg)
s_out(" Done.\n")
# Acquire list of KEGG reaction IDs
if not len(kegg_rxn_ids):
s_out("Downloading KEGG reaction list...")
r = rget("/".join([krest,"list","reaction"]))
if r.status_code == 200:
for line in r.text.split("\n"):
if line == "": break # The end
kegg_rxn_id = line.split()[0].split(":")[1]
kegg_rxn_ids.append(kegg_rxn_id)
else:
msg = "Error: Unable to download KEGG rest reaction list.\n"
sys.exit(msg)
s_out(" Done.\n")
# Limit download length, for testing only
if test_limit:
kegg_comp_ids = kegg_comp_ids[0:test_limit]
kegg_rxn_ids = kegg_rxn_ids[0:test_limit]
# Download compounds (threaded)
kegg_comp_dict = {}
print("Downloading KEGG compounds...")
for comp in get_KEGG_comps(kegg_comp_ids):
if comp == None:
continue
try:
kegg_comp_dict[comp['_id']] = comp
except KeyError:
s_err("Warning: '" + str(comp) + \
"' lacks an ID and will be discarded.\n")
continue
print("")
# Download reactions (threaded)
kegg_rxn_dict = {}
print("Downloading KEGG reactions...")
for rxn in get_KEGG_rxns(kegg_rxn_ids):
if rxn == None:
continue
try:
kegg_rxn_dict[rxn['_id']] = rxn
except KeyError:
s_err("Warning: '" + str(rxn) + \
"' lacks an ID and will be discarded.\n")
continue
print("")
# Re-organize compound reaction listing, taking cofactor role into account
s_out("Organizing reaction lists...")
sort_KEGG_reactions(kegg_comp_dict, kegg_rxn_dict)
s_out(" Done.\n")
s_out("KEGG download completed.\n")
return (kegg_comp_dict, kegg_rxn_dict)
def quicksearch(con, db, query):
"""Wrapper for MineClient3 quick_search() with reconnect functionality."""
n = 0
results = []
while True:
try:
results = con.quick_search(db, query)
return results
except mc.ServerError:
return results
except:
# Server not responding, try again
n += 1
if n % 5 == 0:
s_err("Warning: Server not responding after " + \
"%s attempts ('%s').\n" % (str(n), query))
if n >= 36:
s_err("Warning: Connection attempt limit reached for '" + \
query + "'.\n")
return results
if n <= 12:
time.sleep(10)
if n > 12:
time.sleep(30)
def threaded_quicksearch(con, db, query_list):
"""Threaded implementation of quicksearch."""
def worker():
while True:
query = work.get()
if query is None:
work.task_done()
break
output.put(quicksearch(con, db, query))
work.task_done()
work = queue.Queue()
output = queue.Queue()
threads = []
num_workers = 128
for i in range(num_workers):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
for query in query_list:
work.put(query)
# Report progress
M = len(query_list)
p = Progress(design='pbct', max_val=M)
while True:
if not work.qsize():
n = M - work.qsize()
p.write(n)
break
else:
n = M - work.qsize()
p.write(n)
time.sleep(1)
print("")
# Block until all work is done
work.join()
# Stop workers
for i in range(num_workers):
work.put(None)
for t in threads:
t.join()
# Get the results
results = []
while not output.empty():
results.extend(output.get())
return results
def getcomp(con, db, comp_id):
"""Wrapper for MineClient3 get_comps() with reconnect functionality."""
n = 0
while True:
try:
results = con.get_comps(db, [comp_id])
break
except mc.ServerError:
results = None
except:
# Server not responding, try again
n += 1
if n % 5 == 0:
s_err("Warning: Server not responding after " + \
"%s attempts ('%s').\n" % (str(n), comp_id))
if n >= 36:
s_err("Warning: Connection attempt limit reached for '" + \
comp_id + "'.\n")
results = None
if n <= 12:
time.sleep(10)
if n > 12:
time.sleep(30)
try:
results = results[0]
except IndexError or TypeError:
results = None
if results == None:
s_err("Warning: '" + comp_id + \
"' could not be retrieved from the database.\n")
# Fix missing KEGG IDs
mid_to_kegg = {
"X71306b6c4efe11bc7c485fbc71932f3deb14fa2c":"C00080",
"X08a914cde05039694ef0194d9ee79ff9a79dde33":"C00001"
}
if comp_id in mid_to_kegg.keys():
kegg_id = mid_to_kegg[comp_id]
try:
results['DB_links']['KEGG'] = [kegg_id]
except KeyError:
results['DB_links'] = {'KEGG':[kegg_id]}
# Return compound record
return results
def threaded_getcomps(con, db, comp_id_list):
"""Threaded implementation of getcomp."""
def worker():
while True:
comp_id = work.get()
if comp_id is None:
work.task_done()
break
output.put(getcomp(con, db, comp_id))
work.task_done()
work = queue.Queue()
output = queue.Queue()
threads = []
num_workers = 128
for i in range(num_workers):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
for comp_id in comp_id_list:
work.put(comp_id)
# Report progress
M = len(comp_id_list)
p = Progress(design='pbct', max_val=M)
while True:
if not work.qsize():
n = M - work.qsize()
p.write(n)
break
else:
n = M - work.qsize()
p.write(n)
time.sleep(1)
print("")
# Block until all work is done
work.join()
# Stop workers
for i in range(num_workers):
work.put(None)
for t in threads:
t.join()
# Get the results
comps = []
while not output.empty():
comps.append(output.get())
return comps
def getrxn(con, db, rxn_id):
"""Wrapper for MineClient3 get_rxns() with reconnect functionality."""
n = 0
while True:
try:
results = con.get_rxns(db, [rxn_id])
break
except mc.ServerError:
results = None
except:
# Server not responding, try again
n += 1
if n % 5 == 0:
s_err("Warning: Server not responding after " + \
"%s attempts ('%s').\n" % (str(n), rxn_id))
if n >= 36:
s_err("Warning: Connection attempt limit reached for '" + \
rxn_id + "'.\n")
results = None
if n <= 12:
time.sleep(10)
if n > 12:
time.sleep(30)
try:
results = results[0]
except IndexError or TypeError:
results = None
if results == None:
s_err("Warning: '" + rxn_id + \
"' could not be retrieved from the database.\n")
return results
def threaded_getrxn(con, db, rxn_id_list):
"""Threaded implementation of getrxn."""
def worker():
while True:
rxn_id = work.get()
if rxn_id is None:
work.task_done()
break
output.put(getrxn(con, db, rxn_id))
work.task_done()
work = queue.Queue()
output = queue.Queue()
threads = []
num_workers = 128
for i in range(num_workers):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
for rxn_id in rxn_id_list:
work.put(rxn_id)
# Report progress
M = len(rxn_id_list)
p = Progress(design='pbct', max_val=M)
while True:
if not work.qsize():
n = M - work.qsize()
p.write(n)
break
else:
n = M - work.qsize()
p.write(n)
time.sleep(1)
print("")
# Block until all work is done
work.join()
# Stop workers
for i in range(num_workers):
work.put(None)
for t in threads:
t.join()
# Get the results
rxns = []
while not output.empty():
rxns.append(output.get())
return rxns
def read_compounds(filename):
"""Read a file with KEGG compound IDs."""
s_out("\nReading compound ID file...")
compounds = [line.rstrip() for line in open(filename, 'r')]
for c in compounds:
if re.fullmatch("^C[0-9]{5}$", c) == None:
msg = "".join(["\nWarning: The supplied string '",
c,
"' is not a valid KEGG compound ID."])
sys.exit(msg)
s_out(" Done.")
return compounds
def KEGG_to_MINE_id(kegg_ids):
"""Translate KEGG IDs to MINE IDs."""
s_out("\nTranslating from KEGG IDs to MINE IDs...\n")
server_url = "http://modelseed.org/services/mine-database"
con = mc.mineDatabaseServices(server_url)
db = "KEGGexp2"
kegg_id_dict = {}
for kegg_comp in threaded_getcomps(con, db, [x['_id'] \
for x in threaded_quicksearch(con, db, kegg_ids)]):
for kegg_id in kegg_comp['DB_links']['KEGG']:
kegg_id_dict[kegg_id] = kegg_comp['_id']
for kegg_id in kegg_ids:
try:
kegg_comp = kegg_id_dict[kegg_id]
except KeyError:
s_err("Warning: '%s' is not present in the database.\n" % kegg_id)
continue
print("\nDone.\n")
return kegg_id_dict
def extract_reaction_comp_ids(rxn):
"""Extract reactant and product IDs from a MINE reaction object."""
rxn_comp_ids = []
# Get reaction ID and test if the reaction is valid
try:
rxn_id = rxn['_id']
except KeyError:
s_err("Warning: '%s' does not have a reaction ID.\n" % str(rxn))
rxn_id = 'UnknownReaction'
except TypeError:
s_err("Warning: '%s' is not a valid reaction.\n" % str(rxn))
return rxn_comp_ids
# Try to get the reactants
try:
rxn_p = rxn['Reactants']
try:
rxn_comp_ids.extend([x[1] for x in rxn_p])
except IndexError:
s_err("Warning: The reactant list of '%s' is not valid.\n" % rxn_id)
except KeyError:
s_err("Warning: '%s' does not list its reactants.\n" % rxn_id)
# Try to get the products
try:
rxn_p = rxn['Products']
try:
rxn_comp_ids.extend([x[1] for x in rxn_p])
except IndexError:
s_err("Warning: The product list of '%s' is not valid.\n" % rxn_id)
except KeyError:
s_err("Warning: '%s' does not list its products.\n" % rxn_id)
return rxn_comp_ids
def limit_carbon(comp, C_limit=25):
"""True if the compound exceeds the carbon atom limit, otherwise False."""
regex = re.compile('[A-Z]{1}[a-z]*[0-9]*')
try:
formula = comp['Formula']
except KeyError:
try:
comp_id = comp['_id']
except KeyError:
comp_id = 'UnknownCompound'
s_err("Warning: '%s' has no formula and passes the C-limit.\n" % (comp_id))
return False
# Find all elements in the formula
match = re.findall(regex, formula)
C_count = 0
for element in match:
# Check if the element is carbon
if re.search('C{1}[^a-z]*$', element):
# Determine carbon count
try:
C_count = int(element.split('C')[1])
except ValueError:
C_count = 1
# Assume that the first C encountered is carbon
# Later C's might be part of e.g. ACP
break
if C_count > C_limit:
return True
else:
return False
def extract_comp_reaction_ids(comp):
"""Extracts all reaction IDs from a MINE compound object."""
rxn_id_list = []
try:
rxn_id_list.extend(comp['Reactant_in'])
except KeyError:
pass
try:
rxn_id_list.extend(comp['Product_of'])
except KeyError:
pass
return rxn_id_list
def get_raw_MINE(comp_id_list, step_limit=10, comp_limit=100000, C_limit=25):
"""Download connected reactions and compounds up to the limits."""
# Set up connection
server_url = "http://modelseed.org/services/mine-database"
con = mc.mineDatabaseServices(server_url)
db = "KEGGexp2"
s_out("\nDownloading MINE data via %s/...\n\n" % server_url)
# Set up output dictionaries
comp_dict = {}
rxn_dict = {}
# Set up counters
steps = 0
comps = 0
# First add the starting compounds
for comp in threaded_getcomps(con, db, comp_id_list):
if comp == None:
continue
try:
comp_id = comp['_id']
except KeyError:
s_err("Warning: '%s' is not a valid compound.\n" % str(comp))
continue
if not limit_carbon(comp, C_limit):
comp_dict[comp_id] = comp # Add compound to dict
comps += 1
else:
s_err("Warning: Starting compound '" + comp_id + \
"' exceeds the C limit.\n")
s_out("\nStep %s finished at %s compounds.\n" % (str(steps), str(comps)))
extended_comp_ids = set()
rxn_exceeding_C_limit = set()
comp_exceeding_C_limit = set()
comp_cache = {}
# Perform stepwise expansion of downloaded data
while steps < step_limit:
# A new step begins
steps += 1
print("")
# Get the unexplored compounds by subtracting
# explored from all that are stored
unextended_comp_ids = set(comp_dict.keys()) - extended_comp_ids
# Go through each unexplored compound and get a list
# of the reactions that need to be downloaded
rxn_ids_to_download = set()
for comp_id in unextended_comp_ids:
# New compounds are always in the dictionary
comp = comp_dict[comp_id]
# Get a list of the reactions that the compound is involved in
rxn_id_list = extract_comp_reaction_ids(comp)
# Go through each reaction
for rxn_id in rxn_id_list:
# Reactions that are not in the reaction dictionary
# and do not exceed the C limit will be downloaded
# and further explored
req1 = rxn_id not in rxn_dict.keys()
req2 = rxn_id not in rxn_exceeding_C_limit
if req1 and req2:
rxn_ids_to_download.add(rxn_id)
# Download new rxns
new_rxns = threaded_getrxn(con, db, list(rxn_ids_to_download))
print("")
# Go through the downloaded reactions and get a list
# of compounds to download
comp_ids_to_download = set()
for rxn in new_rxns:
if rxn == None: continue
rxn_comp_ids = extract_reaction_comp_ids(rxn)
for rxn_comp_id in rxn_comp_ids:
# Compounds that are not in the reaction dictionary
# and do not exceed the C limit will be downloaded
# and further explored
req1 = rxn_comp_id not in comp_dict.keys()
req2 = rxn_comp_id not in comp_cache.keys()
req3 = rxn_comp_id not in comp_exceeding_C_limit
if req1 and req2 and req3:
comp_ids_to_download.add(rxn_comp_id)
# Download new compounds
new_comps = threaded_getcomps(con, db, list(comp_ids_to_download))
# Expand the comp_cache with the new compounds
for comp in new_comps:
if comp == None: continue
try:
comp_id = comp['_id']
except KeyError:
s_err("Warning: Compound '%s' lacks an ID " % str(comp) + \
"and will be skipped.\n")
continue
comp_cache[comp_id] = comp
# Go through each new reaction and its compounds
for rxn in new_rxns:
new_rxn_comp_ids = set()
if rxn == None: continue
try:
rxn_id = rxn['_id']
except KeyError:
s_err("Warning: Reaction '%s' lacks an ID " % str(rxn) + \
"and will be skipped.\n")
continue
rxn_comp_ids = extract_reaction_comp_ids(rxn)
for rxn_comp_id in rxn_comp_ids:
if rxn_comp_id not in comp_dict.keys():
# The compound has not been added to the compound dict
try:
rxn_comp = comp_cache[rxn_comp_id]
if limit_carbon(rxn_comp, C_limit):
# Both compound reaction exceed the C limit
comp_exceeding_C_limit.add(rxn_comp_id)
rxn_exceeding_C_limit.add(rxn_id)
# We don't want to explore this reaction further
break
# The compound passed the C limit
new_rxn_comp_ids.add(rxn_comp_id)
except KeyError:
# The compound was never downloaded
continue
# We've made it through the compounds of the reaction
if rxn_id in rxn_exceeding_C_limit:
continue
# The reaction did not exceed the C limit,
# so let's harvest the new compounds
# The reaction should also be placed in the reaction dictionary
rxn_dict[rxn_id] = rxn
for new_rxn_comp_id in new_rxn_comp_ids:
comp_dict[new_rxn_comp_id] = comp_cache[new_rxn_comp_id]
comps += 1
# Stop at compound limit here
if comps >= comp_limit:
s_out("".join([
"\nStep ", str(steps), " finished at ",
str(comps), " compounds.\n"
]))
print("\nDone.")
return (comp_dict, rxn_dict)
# All reactions in the current step have been explored
extended_comp_ids = extended_comp_ids.union(unextended_comp_ids)
s_out("".join([
"\nStep ", str(steps), " finished at ", str(comps), " compounds.\n"
]))
print("\nDone.")
return (comp_dict, rxn_dict)
def add_compound_node(graph, compound, start_comp_ids):
"""Adds a compound node to the graph."""
N = len(graph.nodes()) + 1
try:
mid = compound['_id']
except:
s_err("Warning: Compound '%s' is malformed.\n" % str(compound))
return graph
if mid in start_comp_ids:
start = True
elif 'C' + mid[1:] in start_comp_ids:
start = True
elif not limit_carbon(compound, 0):
# Make sure that inorganic compounds are treated as starting compounds
start = True
else:
start = False
graph.add_node(N, type='c', mid=mid, start=start)
# Also add a mid to node entry in the graph dictionary
try:
graph.graph['cmid2node'][mid] = N
except KeyError:
graph.graph['cmid2node'] = {mid : N}
return graph
def check_connection(network, c_node, r_node):
"""Checks that the compound-to-reaction node connection is valid."""
con_check = False
c_mid = network.node[c_node]['mid']
r_mid = network.node[r_node]['mid']
r_type = network.node[r_node]['type']
if r_type in {'rf','pr'}:
try:
if r_mid in network.graph['mine_data'][c_mid]['Reactant_in']:
con_check = True
except KeyError:
pass
if r_type in {'pf','rr'}:
try:
if r_mid in network.graph['mine_data'][c_mid]['Product_of']:
con_check = True
except KeyError:
pass
return con_check
def add_quad_reaction_node(graph, rxn):
"""
Adds a "Quad Reaction Node" (QRN) group of nodes to a graph, and connects
them to the correct compound nodes.
The QRN consists of two nodes constituting the intended forward direction
of the reaction and two nodes constituting the reverse direction. Each pair
of nodes is connected by an edge in the direction of the reaction. Each node
represents a group of compounds on one side of the reaction equation.
"""
# Make sure the reaction is in good shape
rxn_malformed = False
try:
rxn_id = rxn['_id']
except:
rxn_malformed = True
try:
reactants_f = set([x[1] for x in rxn['Reactants']])
products_f = set([x[1] for x in rxn['Products']])
reactants_r = products_f
products_r = reactants_f
except:
rxn_malformed = True
if rxn_malformed:
s_err("Warning: Reaction '%s' is malformed.\n" % str(rxn))
return graph
# Find the compound nodes of the reactants and the products
rf = set([])
pf = set([])
rr = set([])
pr = set([])
for c_mid in reactants_f:
try:
node = graph.graph['cmid2node'][c_mid]
rf.add(node)
pr.add(node)
except KeyError:
# If a reactant is missing, the reaction should not be added
s_err("Warning: Compound '" + c_mid + "' in reaction '" + rxn_id + \
"' is missing. Reaction nodes were not added to the network.\n")
return graph
for c_mid in products_f:
try:
node = graph.graph['cmid2node'][c_mid]
pf.add(node)
rr.add(node)
except KeyError:
# If a product is missing, the reaction should not be added
s_err("Warning: Compound '" + c_mid + "' in reaction '" + rxn_id + \
"' is missing. Reaction nodes were not added to the network.\n")
return graph
# Create the reaction nodes
N = len(graph.nodes()) + 1
graph.add_node(N, type='rf', mid=rxn_id, c=rf)
for c_node in rf:
if check_connection(graph, c_node, N):
graph.add_edge(c_node, N)
N += 1
graph.add_node(N, type='pf', mid=rxn_id, c=pf)
for c_node in pf:
if check_connection(graph, c_node, N):
graph.add_edge(N, c_node)
graph.add_edge(N-1, N) # Forward reaction edge
N += 1
graph.add_node(N, type='rr', mid=rxn_id, c=rr)
for c_node in rr:
if check_connection(graph, c_node, N):
graph.add_edge(c_node, N)
N += 1
graph.add_node(N, type='pr', mid=rxn_id, c=pr)
for c_node in pr:
if check_connection(graph, c_node, N):
graph.add_edge(N, c_node)
graph.add_edge(N-1, N) # Reverse reaction edge
return graph
def expand_start_comp_ids(comp_dict, start_comp_ids, extra_kegg_ids=[]):
"""
Expands a set of start compound IDs with those of compounds sharing
the same KEGG ID.
"""
start_kegg_ids = set(extra_kegg_ids)
for start_comp_id in start_comp_ids:
try:
start_comp = comp_dict[start_comp_id]
except KeyError:
# Missing start compound IDs missing is not optimal
# By-passing them here
continue
try:
kegg_ids = set(start_comp['DB_links']['KEGG'])
start_kegg_ids = start_kegg_ids.union(kegg_ids)
except KeyError:
pass
for comp_id in comp_dict.keys():
comp = comp_dict[comp_id]
try:
if len(set(comp['DB_links']['KEGG']).intersection(start_kegg_ids)):
start_comp_ids.add(comp_id)
except KeyError:
pass
return start_comp_ids
def construct_network(comp_dict, rxn_dict, start_comp_ids=[], extra_kegg_ids=[]):
"""
Constructs a directed graph (network) from the compound and reaction
dictionaries produced by get_raw_MINE and/or get_raw_KEGG.
"""
s_out("\nConstructing network...\n")
# expand_start_comp_ids catches "unlisted" compounds with the same KEGG ID
start_comp_ids = expand_start_comp_ids(comp_dict, set(start_comp_ids),
extra_kegg_ids=extra_kegg_ids)
# Initialise directed graph
network = nx.DiGraph(mine_data={**comp_dict, **rxn_dict})
# Add all compounds
p = Progress(max_val=len(comp_dict), design='pct')
n_done = 0
for comp_id in sorted(comp_dict.keys()):
comp = comp_dict[comp_id]
network = add_compound_node(network, comp, start_comp_ids)
progress = p.to_string(n_done)
s_out("\rAdding compounds... %s" % progress)
n_done += 1
# Add all reactions
print("")
p = Progress(max_val=len(rxn_dict), design='pct')
n_done = 0
for rxn_id in sorted(rxn_dict.keys()):
rxn = rxn_dict[rxn_id]
network = add_quad_reaction_node(network, rxn)
progress = p.to_string(n_done)
s_out("\rAdding reactions... %s" % progress)
n_done += 1
print("\nDone.")
return network
def is_connected_MINE_comp(comp_id, network):
"""Determines if the MINE compound is connected."""
try:
pred = network.successors(network.graph['cmid2node'][comp_id])
succ = network.predecessors(network.graph['cmid2node'][comp_id])
except KeyError:
return False
if len(pred) + len(succ) > 0:
return True