-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathKEGGChem.py
1540 lines (1340 loc) · 67.9 KB
/
KEGGChem.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
#version 0.9.3
import requests
import re
import sys
import os
from collections import Counter
import argparse
import statistics as stat
import datetime
import pubchempy as pcp
import csv
import signal
#import logging
github = "https://github.com/Lachiemckbioinfo/KEGGChem"
citation = "XXXXX"
#KEGGcitation = (f"KEGG citation goes here")
appname = 'KEGGChem'
version = 'KEGGChem 0.9.2'
#Initiate argparse
parser = argparse.ArgumentParser(
prog = f'{appname}',
description = f'{appname} is a simple web scraper of the KEGG API, that extracts information from the KEGG compound database using either KEGG orthologues or modules as input.',
epilog = f'Thank you for using {appname}.\nMore details can be found at {github}.\nThis program is neither endorsed by or affiliated with KEGG. Please cite the relevant KEGG literature when using this program.'
)
parser.add_argument("-m", "--mode",
choices=["ko", "module", "compound", "reaction", "mdata"],
required = True,
#help = "The mode to run in. Select either 'ko', 'module', to search for compounds using the relevant data. Use 'compound', or 'reaction' to download data for items from those databases. Use 'download'"
help = f"""
The mode to run {appname} in. Select either 'ko' or 'module' to search for compounds using either ko or module codes as input.
Use 'compound' or 'reaction' mode to download related data from listed data entries.
""")
parser.add_argument("-i", "--input",
required = True,
help = "The search input. Either select a file, or input a searchterm or KEGG entry code.",
#type = argparse.FileType('r'),
#Blank metavar argument to make help output read a bit better
metavar='',
dest = 'infile')
parser.add_argument("-o", "--out",
required = False,
help = """
The output directory to be used. If this argument is not used, then a default directory will be created using
the input filename + '_output'.
""",
dest = 'outdir',
metavar = '')
parser.add_argument("-d", "--download",
required = False,
help = f"Download directory. If none is given, a new one will be made if not present already. Default = {appname}_downloads",
metavar = '')
parser.add_argument("-s", "--structure",
required = False,
help = "Download structural data for compounds, such as weight and mass, and .mol and .kcf files. Default = False",
action = "store_true")
#PubChem search argument using PubChemyPy
parser.add_argument("--pubchem",
required = False,
help = "Search PubChem database using SID codes retrieved from compounds. Default = False",
action = "store_true")
parser.add_argument("--sdf",
required = False,
help = "Download sdf file from PubChem. Requires --pubchem argument. Default = False",
action = "store_true")
#Retrieve genes
parser.add_argument("--homolog",
required = False,
help = "Find genes on the KEGG database with the same KO codes. Requires --mode=ko. Default = False",
action = "store_true")
parser.add_argument("--homolog-organism",
required = False,
help = """
Restrict the genes to be downloaded with the --homolog command. This can be done with one of the following options:
-Input a KEGG organism code (e.g., hsa, ggo, ptr).
-Input a file containing a list of KEGG organism codes.
-Input a search keyword, which corresponds to a premade list of organism codes for all KEGG organisms in a given clade. E.g., animals, mammals, bacteria.
""",
#type = argparse.FileType('r'),
metavar = '',
dest = "homologorg")
parser.add_argument("-w", "--overwrite",
required = False,
help = "Download and overwrite stored files. Default = False.",
action = "store_true")
#Mutually exlclusive arguments --quite and --verbose, for printing less or more output, respectively
group = parser.add_mutually_exclusive_group()
group.add_argument("--quiet",
required = False,
help = "Run program quietly and reduce data printed to screen. Default = False",
action = "store_true")
group.add_argument("--verbose",
required = False,
help = "Print extra program details to screen. Default = False",
action = "store_true")
#Parse argparse parser parse
args = parser.parse_args()
mode = args.mode
structure = args.structure
infile = args.infile
quiet = args.quiet
verbose = args.verbose
pubchemarg = args.pubchem
sdfarg = args.sdf
homolog = args.homolog
homologorg = args.homologorg
overwrite = args.overwrite
download = args.download
linebreak = f"\n{'-'*100}\n"
#Set start and finish times with datetime
starttime = datetime.datetime.now()
timestamp = starttime.strftime("%b-%d %H:%M:%S")
filedatestamp = starttime.strftime("%b-%d")
#Function to set endtime and calculate runtime
def timetaken():
endtime = datetime.datetime.now()
timestamp_end = endtime.strftime("%b-%d %H:%M:%S")
runtime = endtime - starttime
return runtime, timestamp_end
#Set output directory. If none given, use input file as output directory name
def set_outdir():
#Function to check if outdir of same name exists. If so, add a date, and if still exists, add a number (starting at one, goes up with repeats)
def check_outdir(outdir):
if os.path.exists(outdir) == True:
#Set filename of default name + date
date_outdir = f"{outdir}_{filedatestamp}"
if os.path.exists(date_outdir) == False:
outdir = date_outdir
else:
outnum = 1
while os.path.exists(f"{date_outdir}_{outnum}") == True:
outnum += 1
outdir = f"{date_outdir}_{outnum}"
return outdir
#If args.outdir is a value, use that value as outdir
#If directory does not exist, proceed as normal
if args.outdir is not None:
if os.path.exists(args.outdir) == False:
outdir = str(args.outdir)
#If outdir does exist, create another directory inside it with the same name
else:
outdir_internal = os.path.join(str(args.outdir), str(args.outdir))
outdir = check_outdir(outdir_internal)
#raise SystemError("Error: Result directory already exists")
else:
outdir = str(infile + "_output")
outdir = check_outdir(outdir)
return outdir
outdir = set_outdir()
#Set downloads directory
if args.download is not None:
dir_download = str(args.download)
else:
dir_download = "keggchem_downloads"
dirs = ["KEGG_entries/compounds", "KEGG_entries/orthologues", "KEGG_entries/reactions", "KEGG_entries/genes", "KEGG_lists",
"KEGG_entries/modules", "Structure_files/Downloaded", "Structure_files/nullfiles", "SDFfiles", "KEGG_links/genes"]
dir_download = os.path.abspath(dir_download)
if verbose == True:
print(f"{linebreak}Checking if download subdirectories exist{linebreak}")
#Create each subdirectory in download directory (ok is exists already)
for item in dirs:
path = os.path.join(dir_download, item)
os.makedirs(path, exist_ok = True)
#Set separator (aka ignore everything after separator to avoid false positives)
if mode == "ko" or mode == "module":
separator = "GENES"
input = []
input_invalid = {}
#Extract input codes and appent to input list
def openfile(x):
if os.path.exists(infile) == True:
with open(infile, "r") as file:
line_number = 0
while (line := file.readline().strip()):
line = line.upper()
line_number += 1
if "KO:k" in line:
line = line.replace("KO:k", "K")
if 'ko' in line:
line = line.replace('ko', "K")
#If search == [LETTER] or RC + 5 digits, proceed
if mode != "download":
if re.search(rf"{x}\d{{5}}\b", line):
#if re.search(r"\b([MKTCGRNHD]|RC)\d{5}\b", line):
input.append(line)
else:
input_invalid[line_number] = line
if verbose == True:
print(f"Invalid search term: {line}\n")
else:
if re.search(r"\b([MKTCGRNHD]|RC)\d{5}\b", line):
input.append(line)
else:
input_invalid[line_number] = line
if verbose == True:
print(f"Invalid search term {line}")
input_mode = "file"
else:
if infile.lower() == 'all':
#Search KEGG list
input_dict = {}
def request_input(mode):
if mode == "mdata":
modeterm = "module"
else:
modeterm = mode
url = f"https://rest.kegg.jp/list/{modeterm}"
input_list_file = os.path.join(dir_download, "KEGG_lists", f"{modeterm}.txt")
return url, input_list_file
#Return url and input_list_file
url, input_list_file = request_input(mode)
#Process input
if os.path.exists(input_list_file) == False or overwrite == True:
req = requests.get(url).text
#Write request to file
with open(input_list_file, "w") as filehandle:
filehandle.write(req)
inputdata = req.splitlines()
else:
with open (input_list_file, "r") as filehandle:
inputdata = filehandle.readlines()
#Process ko
for item in inputdata:
data = item.split("\t")
input_code = data[0]
input_searchterm = data[1].lower()
input_dict[input_code] = input_searchterm
#Search ko_dict for KO number or search term
for input_code, input_searchterm in input_dict.items():
infile_list = infile.split(",")
#Lowercase infile_list
infile_list = [item.lower().strip() for item in infile_list]
if input_code.lower() in infile_list:
input.append(input_code)
if verbose == True:
print(f"Selecting {mode} entry {input_code}")
else:
for infile_term in infile_list:
if infile_term.lower() in input_searchterm:
input.append(input_code)
if len(input) == 0:
raise SystemExit(f"No {mode} results or files were found for the searchterm {infile}")
else:
if quiet == False:
print(f"Error: Searching {mode} list for {infile} returned {len(input)} KEGG entries")
input_mode = "search"
else:
inputname = infile
if 'KO:k' in inputname or "KO:K" in inputname:
inputname = inputname.replace("KO:k", "K")
inputname = inputname.replace("KO:K", "K")
if "KO" in inputname or "ko" in inputname or 'Ko' in inputname:
inputname = inputname.replace("KO", "K")
inputname = inputname.replace("ko", "K")
inputname = inputname.replace('Ko', "K")
input.append(inputname)
input_mode = "search"
return input_mode
#----------------------------------------Process input----------------------------------------#
#openfile()
if mode == "ko":
input_mode = openfile("K")
elif mode == "compound":
input_mode = openfile("C")
elif mode == "reaction":
input_mode = openfile("R")
elif mode == "module":
input_mode = openfile("M")
elif mode == "mdata":
input_mode = openfile("M")
elif mode == "homolog":
input_mode = openfile("K")
input_unique = sorted([*set(input)])
input_total = len(input)
input_unique_total =len(input_unique)
total_reactions_list = []
total_modules_list = []
total_compounds_list = []
total_glycans_list = []
dict_pathways = {}
orgdict = {}
homolog_orglist = []
#----------------------------------------Process orglist for homolog arguments----------------------------------------#
def get_orglist():
orgfile = os.path.join(dir_download, "KEGG_lists", "organisms.txt")
if os.path.exists(orgfile) == False or overwrite == True:
#Retrieve the KEGG organisms list from API and save to downloads folder
url = "https://rest.kegg.jp/list/organism"
if verbose == True:
print(f"Downloading KEGG organisms list from {url}")
req = requests.get(url).text
with open(orgfile, "w") as handle:
handle.write(req)
if verbose == True:
print(f"Wrote KEGG organisms list to {orgfile}")
orgdata = req.splitlines()
else:
#Retrieve the KEGG organisms list from the downloads folder
with open(orgfile, "r") as req:
if verbose == True:
print(f"Reading KEGG organisms list from {orgfile}")
orgdata = req.readlines()
#Process organism list data
for item in orgdata:
data = item.split("\t")
orgcode = data[1]
orgstring = f"{data[0]};{data[2]};{data[3]}"
orgdict[orgcode] = orgstring
def open_homologfile(homologfile):
with open(homologfile, "r") as file:
while (line := file.readline().strip()):
homolog_orglist.append(line)
if homolog == True:
if homologorg is not None:
get_orglist()
if os.path.isfile(homologorg) == True:
homologfile = homologorg
open_homologfile(homologfile)
elif os.path.isfile(homologorg) == False:
homologfile = None
homologorg_list = homologorg.split(",")
#Strip whitespace
homologorg_list = [homologitem.strip() for homologitem in homologorg_list]
#Search descriptions of organism codes and append organism codes to homolog_orglist
for homologorgitem in homologorg_list:
for orgcode, orgstring in orgdict.items():
if homologorgitem.lower() == orgcode:
homolog_orglist.append(orgcode)
elif homologorgitem.lower() in orgstring.lower():
homolog_orglist.append(orgcode)
#Raise error and exit if search term found no results
if len(homolog_orglist) == 0:
raise SystemExit(f"Error: No organism codes or descriptions matched the keyword {homologorg}")
#No directories. Only files or keywords
elif os.path.isdir(homologorg):
raise SystemExit(f"Error: --homolog-organism command unable to process {homologorg} as it is a directory. Please select a file or enter a keyword search.")
#Create output directory structure
def create_outdirs(dir_list):
for item in dir_list:
path = os.path.join(outdir, item)
os.makedirs(path, exist_ok = True)
if verbose == True:
print(f"Create output directories {dir_list} in {outdir}")
#Pathway summary writer
#Write KEGG pathway summary
def write_pathway_summary(filename):
pathway_writer = csv.writer(filename, delimiter='\t')
pathway_writer.writerow(["Pathway", "Name", "Count"])
pathway_data = []
for key, value in dict_pathways.items():
pathway_data.append([key, value[0], value[1]])
pathway_writer.writerows(pathway_data)
#----------------------------------------Print Header----------------------------------------#
if quiet == False:
print(f"{linebreak}KEGGChem{linebreak}")
print("Arguments given:")
print(f"Mode: {mode}, Input mode: '{input_mode}', Input: {infile}, Output directory: {outdir}, Download directory: {dir_download}",
f"Quiet: {quiet}, Verbose: {verbose}, Structure: {structure}",
f"Pubchem: {pubchemarg}, SDF: {sdfarg}, Homolog: {homolog}, Homolog organism: {homologorg}",
sep="\n")
if homologorg is not None:
if homologfile is None:
print(f"Filtering homolog genes using the keyword {homologorg}")
else:
print(f"Filtering homolog genes by entries in file {homologfile}")
#----------------------------------------Specific mode functions----------------------------------------#
#--------------------KEGG KO/Module to compound--------------------
# Function to extract reaction codes from KEGG orthologue pages
def get_reaction_codes(KO):
ko_file = os.path.join(dir_download, "KEGG_entries/orthologues", KO)
#Check if file exists in download folder
if os.path.exists(ko_file) == False or overwrite == True:
url = f"https://rest.kegg.jp/get/{KO}"
req = requests.get(url).text
#Strip everything in req from "GENES" onwards
r = req.split(separator, 1)[0]
with open(ko_file, "w") as file:
file.write(req)
else:
with open(ko_file, "r") as file:
r = file.read().split(separator, 1)[0]
if verbose == True:
print(f"Extracted {KO} from file\n")
# Extract reaction codes using regular expressions
reaction_codes = [*set(re.findall(r"R\d{5}", r))]
module_codes = [*set(re.findall(r"M\d{5}", r))]
return reaction_codes, module_codes
#Function to retrieve genes from the list function of the KEGG API using KO codes
def retrieve_genes_from_ko(KO):
url = f"https://rest.kegg.jp/link/genes/{KO}"
linktext = os.path.join(dir_download, "KEGG_links/genes", KO)
try:
if os.path.exists(linktext) == False or overwrite == True:
req = requests.get(url).text
with open(linktext, "w") as filehandle:
filehandle.write(req)
if quiet == False:
print(f"Writing KO and gene links to file {linktext}")
else:
with open(linktext, "r") as filehandle:
req = filehandle.read()
if quiet == False:
print(f"Reading KO and gene links from file {linktext}")
except:
print("Error: File handling in recording KO-Gene links.")
req = req.replace(f"ko:{KO}\t", "")
gene_dict = {}
#Set up counter and length for showing progress
length = len(req.splitlines())
genecount = 1
#Function to retrieve genes. Functioned so that it can be modified for homologfile command
def retrieve_gene(genename):
geneurl = f"https://rest.kegg.jp/get/{genename}"
genefile = os.path.join(dir_download, "KEGG_entries/genes", genename)
#Collect gene data
def collect_gene_data(gene):
AASEQ_pattern = re.compile(r'^AASEQ\s+(\d+)', re.MULTILINE)
AASEQ_match = AASEQ_pattern.search(gene)
NTSEQ_pattern = re.compile(r'^NTSEQ\s+(\d+)', re.MULTILINE)
NTSEQ_match = NTSEQ_pattern.search(gene)
NTSEQ_length = int(NTSEQ_match.group(1))
AASEQ_length = int(AASEQ_match.group(1))
return NTSEQ_length, AASEQ_length
if os.path.exists(genefile) == False:
gene = requests.get(geneurl).text
NTSEQ_length, AASEQ_length = collect_gene_data(gene)
with open(genefile, "w") as handle:
if verbose == True:
print(f"Writing gene {genename} to file {genefile}")
handle.write(gene)
gene_dict[genename] = [gene, NTSEQ_length, AASEQ_length]
else:
with open(genefile, "r") as handle:
gene = handle.read()
NTSEQ_length, AASEQ_length = collect_gene_data(gene)
if verbose == True:
print(f"Retrieving gene file {genename} from download directory")
gene_dict[genename] = [gene, NTSEQ_length, AASEQ_length]
if quiet == False:
print(f"Retrieved gene {genename} ({genecount}/{length})")
#Parse lines using the retrieve_gene function
genenames = []
for line in req.splitlines():
genename = line
if homologorg is None:
retrieve_gene(genename)
genenames.append(genename)
else:
#Find organism code
org = line.split(":", 1)[0]
if org in homolog_orglist:
retrieve_gene(genename)
genenames.append(line)
else:
if verbose == True:
print(f"{genename} ignored as it was not in the organism list")
#retrieve_gene(genename)
genecount += 1
return gene_dict, genenames
#Homolog extraction
def extract_homolog(homolog_dict):
if quiet == False:
print(f"{linebreak}Extracting homolog data from orthologues{linebreak}")
count_current = 1
ko_genecount = {}
for orthologue_id in input_unique:
if quiet == False:
print(f"{linebreak}Retrieving genes for {orthologue_id} ({count_current}/{input_unique_total})")
gene_out = os.path.join(outdir, "Results/Genes", orthologue_id)
try:
gene_dict, genenames = retrieve_genes_from_ko(orthologue_id)
ko_genecount[orthologue_id] = genenames
homolog_dict[orthologue_id] = gene_dict
if len(gene_dict) > 0:
#Make output folder for orthologue
os.makedirs(gene_out)
#Write gene results to results folder for orthologue
if verbose == True:
print(f"\nWriting genes to results folder {gene_out}\n")
for genename, generesult in gene_dict.items():
#genefile = genename + ".txt"
with open(os.path.join(gene_out, genename + ".txt"), "w") as handle:
handle.write(generesult[0])
else:
with open(os.path.join(outdir, "Results/Genes", "KOs_without_genes.txt"), "a") as filehandle:
filehandle.write(f"{orthologue_id}\n")
except:
print(f"Error: Failed to retrieve genes for {orthologue_id}\n")
if quiet == False:
print(f"\nRetrieved genes for {orthologue_id} ({count_current}/{input_unique_total})\n")
count_current += 1
#End homolog extraction step
return ko_genecount
# Function to retrieve compound/glycan codes associated with a reaction or module code
def get_compound_codes(query_code):
#Ensure that queries are saved to/loaded from the correct directory
if re.search(rf"R\d{{5}}\b", query_code):
query_file = os.path.join(dir_download, "KEGG_entries/reactions", query_code)
elif re.search(rf"M\d{{5}}\b", query_code):
query_file = os.path.join(dir_download, "KEGG_entries/modules", query_code)
if os.path.exists(query_file) == False or overwrite == True:
url = f"http://rest.kegg.jp/get/{query_code}"
req = requests.get(url).text
#Strip everything in req from "GENES" onwards
if mode == "ko":
r = req.split(separator, 1)[0]
else:
if "COMPOUND" in req:
r = req.split("COMPOUND", 1)[1]
else:
r = req
with open(query_file, "w") as file:
file.write(req)
if verbose == True:
print(f"Wrote {query_code} to file\n")
else:
with open(query_file, "r") as file:
if mode == "ko":
r = file.read().split(separator, 1)[0]
else:
req = file.read()
if "COMPOUND" in req:
r = req.split("COMPOUND", 1)[1]
else:
r = req
if verbose == True:
print(f"Extracted {query_code} from file\n")
#Extract compound codes from page
compound_codes = [*set(re.findall(r"\b[CG]\d{5}\b", r))]
return compound_codes
#Function to retrieve compound data from compound codes
def get_compound_data(compound_code):
compound_file = os.path.join(dir_download, "KEGG_entries/compounds", compound_code)
if os.path.exists(compound_file) == False or overwrite == True:
url = f"http://rest.kegg.jp/get/{compound_code}"
req = requests.get(url).text
#r = req.split(separator, 1)[0]
with open(compound_file, "w") as file:
file.write(req)
if verbose == True:
print(f"Wrote {compound_code} to file\n")
else:
with open(compound_file, "r") as file:
req = file.read()#.split(separator, 1)[0]
if verbose == True:
print(f"Extracting {compound_code} from file")
#Retrieve compound formula
formula_string = re.findall(r"FORMULA .*", req)
if len(formula_string) > 0:
compound_formula = formula_string[0].replace("FORMULA ", "")
else:
compound_formula = "NULL"
#Retrieve exact mass
exact_mass_string = re.findall(r"EXACT_MASS .*", req)
if len (exact_mass_string) > 0:
exact_mass = float(exact_mass_string[0].replace("EXACT_MASS ", ""))
else:
exact_mass = "NULL"
#Retrieve mol. weight
mol_weight_string = re.findall(r"MOL_WEIGHT .*", req)
if len(mol_weight_string) > 0:
mol_weight = float(mol_weight_string[0].replace("MOL_WEIGHT ", ""))
else:
mol_weight = "NULL"
#Retrieve pathway data
map_string = re.findall(r"map\d{5} .*", req)
map_codes = []
if len(map_string) > 0:
#Split pathway map names and append to dictionary
for map in map_string:
split_map = map.split(" ")
map_code = split_map[0]
map_name = split_map[1]
if map_code not in dict_pathways:
dict_pathways[map_code] = [map_name, 1]
else:
dict_pathways[map_code][1] += 1
map_codes.append(map_code)
#Append map codes only to list and return
pathway_map = map_codes
else:
pathway_map = "NULL"
#Retrieve database data (ChEBI, PubChem)
def find_database_data(database):
database_string = re.findall(rf"{database}: .*", req)
#print(database_string)
if len(database_string) > 0:
#Remove leading header (eg. ChEBI:)
database = database_string[0].replace(f"{database}: ", "")
database = database.split(" ")
#database = [i for i in database]
#Split codes into list, remove leading and trailing spaces
#database = database.strip()
return database
else:
return "NULL"
ChEBI = find_database_data("ChEBI")
PubChem = find_database_data("PubChem")
return compound_formula, exact_mass, mol_weight, ChEBI, PubChem, pathway_map
def get_glycan_data(glycan_code):
compound_file = os.path.join(dir_download, "KEGG_entries/compounds", glycan_code)
if os.path.exists(compound_file) == False or overwrite == True:
url = f"http://rest.kegg.jp/get/{glycan_code}"
req = requests.get(url).text
#r = req.split(separator, 1)[0]
with open(compound_file, "w") as file:
file.write(req)
if verbose == True:
print(f"Wrote {glycan_code} to file\n")
else:
with open(compound_file, "r") as file:
req = file.read()#.split(separator, 1)[0]
if verbose == True:
print(f"Extracting {glycan_code} from file\n")
#Retrieve glycan composition
composition_string = re.findall(r"COMPOSITION .*", req)
if len(composition_string) > 0:
composition = composition_string[0].replace("COMPOSITION ", "")
else:
composition = "NULL"
#Retrieve exact mass
exact_mass_string = re.findall(r"EXACT_MASS .*", req)
if len (exact_mass_string) > 0:
exact_mass = float(exact_mass_string[0].replace("EXACT_MASS ", ""))
else:
exact_mass = "NULL"
#Function to retrieve reaction data from reaction codes
def get_reaction_data(reaction_code):
reaction_file = os.path.join(dir_download, "KEGG_entries/reactions", reaction_code)
if os.path.exists(reaction_file) == False or overwrite == True:
url = f"http://rest.kegg.jp/get/{reaction_code}"
req = requests.get(url).text
with open(reaction_file, "w") as file:
file.write(req)
if verbose == True:
print(f"Wrote {reaction_code} to file\n")
else:
with open (reaction_file, "r") as file:
req = file.read()
if verbose == True:
print(f"Extracted {reaction_code} from file\n")
#Check if data present
if len(req) > 0:
reaction_result = True
else:
reaction_result = False
#Extract name
name_string = re.findall(r"NAME .*", req)
if len(name_string) > 0:
r_name = name_string[0].replace("NAME ", "")
else:
r_name = "NULL"
#Extract equation
equation_string = re.findall(r"EQUATION .*", req)
if len(equation_string) > 0:
equation = equation_string[0].replace("EQUATION ", "")
else:
equation = "NULL"
#Extract definition
definition_string = re.findall(r"DEFINITION .*", req)
if len(definition_string) > 0:
definition = definition_string[0].replace("DEFINITION ", "")
else:
definition = "NULL"
rclass = [*set(re.findall(r"RC\d{5} .*", req))]
ko_codes = [*set(re.findall(r"K\d{5}", req))]
pathways = [*set(re.findall(r"rn\d{5} .*", req))]
return reaction_result, r_name, equation, definition, rclass, ko_codes, pathways
#---------------------Structure download functions----------------------#
def download_structure_files(compound_code, mode):
filename = f"{compound_code}.{mode}"
filedir = os.path.join(dir_download, "Structure_files/Downloaded", filename)
nulldir = os.path.join(dir_download, "Structure_files/nullfiles", filename)
if mode == "mol":
urlcode = "-f+m+"
elif mode == "kcf":
urlcode = "-f+k+"
if (os.path.exists(filedir) == False and os.path.exists(nulldir) == False) or overwrite == True:
url = f"https://www.kegg.jp/entry/{urlcode}{compound_code}"
req = requests.get(url).text
if len(req) > 0:
with open(filedir, "w") as file:
file.write(req)
mol_status = "Saved"
mol_output = req
if verbose == True:
print(f"Saved {compound_code} to {filedir}\n")
else:
with open(nulldir, "w"):
pass
mol_status = "NULL"
mol_output = "NULL"
if verbose == True:
print(f"Saved null result for {compound_code} to {nulldir}")
elif os.path.exists(filedir) == True:
with open(filedir, "r") as file:
req = file.read()
mol_output = req
mol_status = "Loaded"
if verbose == True:
print(f"Read {compound_code} from {filedir}\n")
elif os.path.exists(nulldir) == True:
mol_status = "NULL"
mol_output = "NULL"
if verbose == True:
print(f"Read null result for {compound_code} from {nulldir}")
return mol_status, mol_output, filename
#Download structure files
def structure_download(compound):
path = os.path.join(outdir, "Results", "Structure_files")
os.makedirs(path, exist_ok=True)
molstatus, moldata, molfile = download_structure_files(compound, "mol")
if molstatus != "NULL":
with open(os.path.join(path, molfile), "w") as file:
file.write(moldata)
kcfdata, kcfdata, kcffile = download_structure_files(compound, "kcf")
if molstatus != "NULL":
with open(os.path.join(path, kcffile), "w") as file:
file.write(kcfdata)
def structure_file_download(totallist):
#Download structure files
if structure == True:
structurecount = 1
structuretotal = len(totallist)
if quiet == False:
print(f"{linebreak}Downloading compound structure data for {structuretotal} structures{linebreak}")
for compound in totallist:
if quiet == False:
print(f"Retrieving compound structure data for: {compound} ({structurecount}/{structuretotal})")
structure_download(compound)
structurecount += 1
if quiet == False:
print(f"{linebreak}Finished downloading compound structure data{linebreak}")
#----------------------------------------Function - Retrieve homologs from KO----------------------------------------#
def ko_to_homolog():
#Create outdir structure
dir_list = ["Results/Genes"]
create_outdirs(dir_list)
#----------------------------------------Function - Run KO to compound----------------------------------------#
def ko_to_compound():
#Create outdir structure
dir_list = ["Results/Individual_results", "Summaries"]
if homolog == True:
dir_list.append("Results/Genes")
create_outdirs(dir_list)
count_current = 1
dict_reaction_codes = {}
dict_module_codes = {}
module_compounds_list = []
reaction_compounds_list = []
module_glycan_list = []
reaction_glycan_list = []
homolog_dict = {}
if quiet == False:
print(f"{linebreak}Analysing {input_unique_total} unique KEGG orthologues from ",\
f"{input_mode} {infile} ({input_total} given){linebreak}", sep="")
#Iterate over all orthologues and extract reaction codes and associated compound codes
for orthologue_id in input_unique:
#Print output header
if quiet == False:
print(f"Extracting reaction and compound codes from {orthologue_id}")
reaction_codes, module_codes = get_reaction_codes(orthologue_id)
if verbose == True:
print(f"Extracted reaction and module codes from {orthologue_id}")
outfile = orthologue_id + ".txt"
with open(os.path.join(outdir, "Results/Individual_results", outfile), "a") as out_all,\
open(os.path.join(outdir, "Results", "all_reaction_results.txt"), "a") as all_reaction_results,\
open(os.path.join(outdir, "Results", "all_module_results.txt"), "a") as all_module_results:
out_all.write(f"{orthologue_id}\n")
all_reaction_results.write(f"{orthologue_id}\n")
all_module_results.write(f"{orthologue_id}\n")
#Iterate through reaction/module codes and retrieve compound codes before writing to file
def extract_code(codetype, listname, dictionary, filename, totalcompounds, totalglycans):
for itemcode in codetype:
#If reaction alrady stored, use previously searched results
if itemcode in dictionary:
listname.append(itemcode)
compound_codes = dictionary[itemcode]
else:
compound_codes = get_compound_codes(itemcode)
listname.append(itemcode)
#Add to dictionary of reactions so as to not repeat reaction page search
dictionary[itemcode] = compound_codes
#Add compound codes to set
for compound_code in compound_codes:
if compound_code[0] == "C":
#Append compound to total list for both types
total_compounds_list.append(compound_code)
totalcompounds.append(compound_code)
#Append compound to total list for individual mode
#totalcompounds.append(compound_code)
elif compound_code[0] == "G":
total_glycans_list.append(compound_code)
totalglycans.append(compound_code)
if verbose == True:
print(f"Extracted compound codes from {itemcode}")
out_all.write(f"{itemcode}:{','.join(compound_codes)}\n")
#all_reaction_results.write(f"{itemcode}:{','.join(compound_codes)}\n")
filename.write(f"{itemcode}:{','.join(compound_codes)}\n")
#return compound_codes
extract_code(reaction_codes, total_reactions_list, dict_reaction_codes, all_reaction_results, reaction_compounds_list, reaction_glycan_list)
extract_code(module_codes, total_compounds_list, dict_module_codes, all_module_results, module_compounds_list, module_glycan_list)
#Print current count in order to show progress
if quiet == False:
print(f"\nWrote {orthologue_id} to file ({count_current}/{input_unique_total}){linebreak}")
count_current += 1
#Set unique lists of total compounds/glycans, as well as those sourced through modules or reactions
compounds_unique = sorted([*set(total_compounds_list)])
glycans_unique = sorted([*set(total_glycans_list)])
reactions_unique = sorted([*set(total_reactions_list)])
reaction_compounds_unique = sorted([*set(reaction_compounds_list)])
module_compounds_unique = sorted([*set(module_compounds_list)])
reaction_glycans_unique = sorted([*set(reaction_glycan_list)])
module_glycans_unique = sorted([*set(module_glycan_list)])
#Write unique compounds to list
with open(os.path.join(outdir, "Results", "compounds.txt"), "w") as result,\
open(os.path.join(outdir, "Results", "glycans.txt"), "w") as glycans,\
open(os.path.join(outdir,"Results","reactions.txt"), "w") as reactions,\
open(os.path.join(outdir, "Results", "compounds_from_reactions.txt"), "w") as reaction_compounds,\
open(os.path.join(outdir, "Results", "compounds_from_modules.txt"), "w") as module_compounds,\
open(os.path.join(outdir, "Results", "glycans_from_reactions.txt"), "w") as reaction_glycans,\
open(os.path.join(outdir, "Results", "glycans_from_modules.txt"), "w") as module_glycans:
for compound in compounds_unique:
result.write(f"{compound}\n")
for glycan in glycans_unique:
glycans.write(f"{glycan}\n")
for reaction in reactions_unique:
reactions.write(f"{reaction}\n")
for compound in reaction_compounds_unique:
reaction_compounds.write(f"{compound}\n")
for compound in module_compounds_unique:
module_compounds.write(f"{compound}\n")
for glycan in reaction_glycans_unique:
reaction_glycans.write(f"{glycan}\n")
for glycan in module_glycans_unique:
module_glycans.write(f"{glycan}\n")
total_compounds_dict = dict(Counter(total_compounds_list))
compounds_count = len(total_compounds_dict)
total_reactions_dict = dict(Counter(total_reactions_list))
reactions_count = len(total_reactions_dict)
total_glycans_dict = dict(Counter(total_glycans_list))
glycans_count = len(total_glycans_dict)
#Maths! (Intersection of module/reaction lists)
def intersection(lst1, lst2):
lst3 = [value for value in lst1 if value in lst2]
lst3_count = len(lst3)
lst1_unique = len(lst1) - lst3_count
lst2_unique = len(lst2) - lst3_count
return lst3_count, lst1_unique, lst2_unique
compound_common_count, compound_module_count, compound_reaction_count = intersection(module_compounds_unique, reaction_compounds_unique)
glycan_common_count, glycan_module_count, glycan_reaction_count = intersection(module_glycans_unique, reaction_glycans_unique)
#Download structure files
structure_file_download(compounds_unique)
#Write out summary text
with open(os.path.join(outdir, "Summaries", "compound_summary.txt"), "a") as sum_compounds,\
open(os.path.join(outdir, "Summaries", "reaction_summary.txt"), "a") as sum_reactions,\
open(os.path.join(outdir, "Summaries", "glycan_summary.txt"), "w") as sum_glycans:
#Write reaction summary results to file
sum_reactions.write(f"{linebreak}Reactions summary:{linebreak}")
sum_reactions.write(f"Total unique reactions: {reactions_count}\n\n")
sum_reactions.write("Reaction: count\n")
for key, value in total_reactions_dict.items():