-
Notifications
You must be signed in to change notification settings - Fork 6
/
kemet.py
executable file
·2628 lines (2259 loc) · 106 KB
/
kemet.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 python
# coding: utf-8
# Imports
import os
from os import path
import re
import sys
from multiprocessing import Pool
from datetime import datetime
import argparse
from reframed import load_cbmodel, save_cbmodel
###############
# extra specs #
###############
_ktest_formats = ["eggnog", "kaas", "kofamkoala"]
_hmm_modes = ["onebm", "modules", "kos"]
_def_thr = 0.43
_gapfill_modes = ["existing", "denovo"]
_base_com_KEGGget = "curl --silent https://rest.kegg.jp/get/"
# External dependencies base commands
# experienced users can edit variables with proper parameters e.g. to modify threads etc.
_base_com_mafft = "mafft --quiet --auto --thread -1 MSA_K_NUMBER.fna > K_NUMBER.msa"
_base_com_hmmbuild = "hmmbuild --informat afa K_NUMBER.hmm K_NUMBER.msa > /dev/null"
_base_com_nhmmer = "nhmmer --tblout K_NUMBER.hits K_NUMBER.hmm PATHFILE > /dev/null"
def _timeinfo():
"""
Helper function for generating time indications on the console,
to keep track of script process.
Returns:
timeinfo (str): present date and time, up to seconds
"""
timeinfo = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
return timeinfo
def eggnogXktest(eggnog_file, converted_output, KAnnotation_directory, ktests_directory):
"""
Starting from eggNOG pre-annotations (".emapper.annotations"),
(1 gene - many annotations), keeps only KOs in a converted ".ktest" file.
Args:
eggnog_file (str): eggnog mapper output file name
converted_output (str): resulting intermediate .ktest file name
KAnnotation_directory (str): eggnog mapper output folder path
ktests_directory (str): output .ktest file folder path
Returns:
converted_output (str): output .ktest file name
KOs (dict): (not used in current version)
"""
os.chdir(KAnnotation_directory)
KOs = {}
with open(eggnog_file) as g:
for linum, line in enumerate(g, -1):
if not line.startswith("#"):
break
g.seek(0)
fields = g.readlines()[linum].strip().split("\t")
koslice = fields.index("KEGG_ko")
g.seek(0)
for line in g:
if line.startswith("#"):
continue
egg_kos = line.strip().split("\t")[koslice].replace("ko:", "")
if egg_kos == "" or egg_kos == "-":
continue
for ko in egg_kos.split(","):
KOs.setdefault(ko, 0)
KOs[ko] += 1
# POSSIBILITY:
# for each gene, correct per diff. ortholog hits
# i.e. if more than one KO -> fraction of KO count
#if not ko in KOs:
#KOs[ko] = round(1/len(egg_kos_hits), 2)0
#else:
#KOs[ko] += round(1/len(egg_kos_hits), 2)
if not path.isdir(ktests_directory):
os.mkdir(ktests_directory)
with open(path.join(ktests_directory, converted_output), "w") as g:
for ko in KOs:
print(ko, file=g)
return converted_output, KOs
def KAASXktest(file_kaas, converted_output, KAnnotation_directory, ktests_directory):
"""
Starting from KAAS output (1 gene - 1 KO),
keeps only KOs in a converted ".ktest" file.
Args:
file_kaas (str): KAAS output file name
converted_output (str): resulting intermediate .ktest file name
KAnnotation_directory (str): KAAS output folder path
ktests_directory (str): output .ktest file folder path
Returns:
converted_output (str): output .ktest file name
KOs (dict): (not used in this version)
"""
os.chdir(KAnnotation_directory)
KOs = []
with open(file_kaas) as f:
for line in f:
line = line.strip().split("\t")
if len(line) == 2:
if line[1] not in KOs:
KOs.append(line[1])
if not path.isdir(ktests_directory):
os.mkdir(ktests_directory)
with open(path.join(ktests_directory, converted_output), "w") as g:
for ko in KOs:
print(ko, file=g)
return converted_output, KOs
def kofamXktest(kofamkoala_file, converted_output, KAnnotation_directory, ktests_directory):
"""
Starting from KofamKOALA output (1 gene - many annotations),
keeps only KOs in a converted ".ktest" file.
Args:
kofamkoala_file (str): KofamKOALA output file name
converted_output (str): resulting intermediate .ktest file name
KAnnotation_directory (str): KofamKOALA output folder path
ktests_directory (str): output .ktest file folder path
Returns:
converted_output (str): output .ktest file name
KOs (dict): (not used)
"""
os.chdir(KAnnotation_directory)
KOs = {}
tsvflag = False
with open(kofamkoala_file) as g:
spacer = g.readlines()[1].strip()
if "\t" in spacer:
tsvflag = True
else:
fastaslice = spacer.index(" ", 5) + 1 # account for longer gene IDs
koslice = spacer.index(" ", fastaslice) + 1
g.seek(0)
for line in g.readlines()[2:]:
# skip header, spacer line & gene hits under threshold
if not line.startswith("*"):
continue
if tsvflag:
kofam_ko = line.split("\t")[2]
else:
kofam_ko = line[koslice:koslice+6].strip()
if not kofam_ko.startswith("K"):
continue
KOs.setdefault(kofam_ko, 0)
KOs[kofam_ko] += 1
if not path.isdir(ktests_directory):
os.mkdir(ktests_directory)
with open(path.join(ktests_directory, converted_output), "w") as g:
for ko in KOs.keys():
print(ko, file=g)
return converted_output, KOs
def create_KO_list(file_ko_list, ktests_directory):
"""
Returns a Python list-object from KOs file as recovered in pre-annotations (".ktest" file).
Args:
file_ko_list (str): KO list file name (".ktest")
ktests_directory (str): ".ktest" input file folder path
Returns:
ko_list (list): list of single KOs present in the input pre-annotation
"""
os.chdir(ktests_directory)
ko_list = []
with open(file_ko_list) as f:
ko_list = [ line.strip() for line in f ]
return ko_list
def testcompleteness(ko_list, kk_file, kkfiles_directory, report_txt_directory, file_output, cutoff=0):
"""
Computes KEGG Modules completeness from KO pre-annotation.
Reports that in a flat-file,
including single missing KOs and their position, relative to KEGG Modules blocks
Args:
ko_list (list): output from previous "create_KO_list" function
kk_file (str): .kk file, which includes a KEGG Module definition properly parsed and organized in blocks
kkfiles_directory (str): input .kk files folder
report_txt_directory (str): output folder
file_output (str): output file name
cutoff (int, optional): Minimum obtained KEGG Module completeness percentage to be included in report file.
Defaults to 0.
"""
os.chdir(kkfiles_directory)
report = []
with open(kk_file) as f:
count_lines = 0
linenumber = 0
missing = 0
present = 0
complexes = []
optional = []
submodules = False
submodule = ""
subOR_presence = False
subOR_dict = {}
to_remove = []
ko_list_optional = ko_list
extended_name = f.readline().strip().replace(".txt", "")
f.seek(0)
report.append(kk_file + "\t" + extended_name + "\n")
v = f.readlines()
end = len(v)
# search presence-absence complexes//optional//list-type
f.seek(0)
#COMPLEXES
v_complex = v.index("COMPLEXES_LIST\n") if "COMPLEXES_LIST\n" in v else None
v_optional = v.index("OPTIONAL_LIST\n") if "OPTIONAL_LIST\n" in v else None
# if "COMPLEXES_LIST\n" in v:
# v_complex = v.index("COMPLEXES_LIST\n")
# else:
# v_complex = -1
#
# #OPTIONALS
# if "OPTIONAL_LIST\n" in v:
# v_optional = v.index("OPTIONAL_LIST\n")
# else:
# v_optional = -1
if "/\n" in v:
submodules = True
submodule = 0
if "//\n" in v:
submodules = True
submodule = 0
subOR_presence = True
subOR = -1
# search complexes
if v_complex is not None:
end = v_complex
c_list = v[v_complex+1].replace("\n", "").replace("\t", "").split(", ")
for el in c_list:
complexes.append(el)
# search optionals
if v_optional is not None:
o_list = v[v_optional + 1].replace("\n", "").replace("\t", "").split(", ")
for el in o_list:
optional.append(el)
ko_list_optional = [ el for el in ko_list ]
for el in optional:
ko_list_optional.append(el)
for line in v[1:end]:
count_lines += 1
if submodules:
if line == "/\n":
linenumber = 0
check = False
submodule += 1
continue
if subOR_presence:
end_or = end - 1
if line == "//\n" or count_lines == end_or:
linenumber = 0
check = False
submodule += 1
if count_lines != end_or:
subOR += 1
if subOR != 0:
if count_lines != end_or:
tmp = str(present) + "__" + str(present+missing)
subOR_infos += tmp
subOR_dict.update({subOR:subOR_infos})
present = 0
missing = 0
subOR_infos = ""
if count_lines != end_or:
continue
else:
pass
linenumber += 1
check = False
ko_line = line.strip().split(", ")
if len(complexes) != 0:
while check is False:
for singlecomplex in complexes:
k_singlecomplex = re.split("[+-]", singlecomplex.strip())
if all(el in ko_line for el in k_singlecomplex):
if all(el in ko_list_optional for el in k_singlecomplex):
check = True
else:
continue
else:
for element in ko_line:
if element not in str(complexes):
if element in ko_list:
check = True
break
else:
continue
else:
break
if check:
present += 1
else:
missing += 1
control = str(linenumber) + "." + str(submodule) + "\t" + str(line)
report.append(control)
elif len(complexes) == 0:
for element in ko_list:
if element in line:
check = True
else:
if check:
present += 1
else:
missing += 1
control = str(linenumber) + "." + str(submodule) + "\t" + str(line)
report.append(control)
total = present + missing
percentage_round = round((present/(total))*100, 2)
else:
if subOR_presence and count_lines == end_or:
subOR += 1
tmp = str(present)+"__"+str(present+missing)
subOR_infos += tmp
subOR_dict.update({subOR:subOR_infos})
percentage_round = -1
for subOR, value in subOR_dict.items():
tmp_present = int(value.split("__")[0])
tmp_total = int(value.split("__")[1])
tmp_percentage_round = round((tmp_present/(tmp_total))*100, 2)
if tmp_percentage_round > percentage_round:
present = tmp_present
total = tmp_total
percentage_round = round((present/(total))*100, 2)
subOR_most = subOR
completeness = "COMPLETE" if percentage_round == 100 else "INCOMPLETE"
report.insert(1, "%\t" + str(percentage_round) + "\t" + str(present) + "__" + str(total) + "\t" + completeness + "\n")
if subOR_presence:
for info in report[2:]:
info = info.strip()
sub = int(info.split(".")[1].split("\t")[0].strip())
if sub != subOR_most:
to_remove.append(info)
for el in to_remove:
report.remove(el+"\n")
if percentage_round >= cutoff:
if not path.isdir(report_txt_directory):
os.mkdir(report_txt_directory)
os.chdir(report_txt_directory)
with open(file_output, "a") as g:
for el in report:
g.write(el)
g.write("\n")
def testcompleteness_tsv(ko_list, kk_file, kkfiles_directory, report_tsv_directory, file_report_tsv, as_kegg=False, cutoff=0):
"""
Computes KEGG Modules completeness from KO pre-annotation.
Reports that in a tab-separated file,
including single missing KOs and their position, relative to KEGG Modules blocks.
Args:
ko_list (list): output from previous "create_KO_list" function
kk_file (str): .kk file, which includes a KEGG Module definition properly parsed and organized in blocks
kkfiles_directory (str): input .kk files folder
report_tsv_directory (str): output folder path
file_report_tsv (str): output file name
as_kegg (bool): option to report KEGG Modules completeness as KEGG mapper (see README for details)
cutoff (int, optional): Minimum obtained KEGG Module completeness percentage to be included in report file.
Defaults to 0.
"""
os.chdir(kkfiles_directory)
report = []
report_tsv = []
with open(kk_file) as f:
linenumber = 0
count_lines = 0
missing = 0
present = 0
KOmodule = []
Kmissing = []
Kpresent = []
complexes = []
optional = []
submodules = False
subAND_presence = False
subOR_presence = False
subOR_dict = {}
ko_list_optional = ko_list
extended_name = f.readline().strip().replace(".txt", "")
f.seek(0)
report.append(kk_file + "\t" + extended_name + "\t")
report_tsv.append(kk_file[:-3])
report_tsv.append(extended_name[7:])
v = f.readlines()
end = len(v)
f.seek(0)
# flags complexes/optionals/list-indications presence or absence
v_complex = v.index("COMPLEXES_LIST\n") if "COMPLEXES_LIST\n" in v else None
v_optional = v.index("OPTIONAL_LIST\n") if "OPTIONAL_LIST\n" in v else None
#COMPLEXES
# if "COMPLEXES_LIST\n" in v:
# v_complex = v.index("COMPLEXES_LIST\n")
# else:
# v_complex = -1
#
# #OPTIONALS
# if "OPTIONAL_LIST\n" in v:
# v_optional = v.index("OPTIONAL_LIST\n")
# else:
# v_optional = -1
#LIST-INDICATIONS
if "/\n" in v:
submodules = True
subAND_presence = True
submodule = 0
subAND = 0
if "//\n" in v:
submodules = True
subOR_presence = True
submodule = 0
subOR = -1
# list complexes
if v_complex is not None:
#KOs search stops at complex line
end = v_complex
c_list = v[v_complex+1].replace("\n", "").replace("\t", "").split(", ")
for el in c_list:
complexes.append(el)
# list optionals
if v_optional is not None:
o_list = v[v_optional+1].replace("\n", "").replace("\t", "").split(", ")
for el in o_list:
optional.append(el)
ko_list_optional = [ el for el in ko_list ]
for el in optional:
ko_list_optional.append(el)
# KOs presence/absence
for line in v[1:end]:
ko_line = line.strip().split(", ")
for single_ko in ko_line:
if single_ko == "/" or single_ko == "//":
continue
KOmodule.append(single_ko)
for KO in KOmodule:
if KO in ko_list:
if KO not in Kpresent:
Kpresent.append(KO)
else:
Kmissing.append(KO)
# CHECKS for each line in .kk file: KOs, complexes, optionals and list-indication
for line in v[1:end]:
count_lines += 1
check = False
linenumber += 1
if submodules:
if line == "/\n":
submodule += 1
subAND += 1
linenumber = 0
continue
if subOR_presence:
end_or = end - 1
if line == "//\n" or count_lines == end_or:
submodule += 1
subOR += 1
linenumber = 0
if subOR != 0:
if count_lines != end_or:
tmp = str(present) + "__" + str(present + missing)
subOR_infos += tmp
subOR_dict.update({subOR:subOR_infos})
present = 0
missing = 0
subOR_infos = ""
if count_lines != end_or:
continue
else:
pass
ko_line = line.strip().split(", ")
if len(complexes) != 0:
while check is False:
for singlecomplex in complexes:
k_singlecomplex = re.split("[+-]", singlecomplex.strip())
if all(el in ko_line for el in k_singlecomplex):
if all(el in ko_list_optional for el in k_singlecomplex):
# this way: if EACH KO of complex is present in genome KOs, CHECK positive!
check = True
continue
else:
for ko in ko_line:
if ko not in str(complexes):
if ko in ko_list:
check = True
else:
continue
else:
break
if check:
present += 1
else:
missing += 1
elif len(complexes) == 0:
for ko in ko_list:
if ko in line:
check = True
else:
if check:
present += 1
else:
missing += 1
total = present+missing
missing_blocks = str(present) + "__" + str(total)
percentage_round_tsv = round((present/(total))*100, 2)
else:
if subOR_presence and count_lines == end_or:
tmp = str(present) + "__" + str(present+missing)
subOR_infos += tmp
subOR_dict.update({subOR:subOR_infos})
# check better completeness from alternative sub-modules
if subOR_presence:
for value in subOR_dict.values():
tmp_present = int(value.split("__")[0])
tmp_total = int(value.split("__")[1])
tmp_percentage_round_tsv = round((tmp_present/(tmp_total))*100, 2)
if tmp_percentage_round_tsv > percentage_round_tsv:
present = tmp_present
total = tmp_total
missing_blocks=str(present) + "__" + str(total)
percentage_round_tsv = round((present/(total))*100, 2)
difference = total - present
if as_kegg:
if difference == 0:
completeness_tsv = "COMPLETE"
elif difference > 2 or total < 3:
completeness_tsv = "INCOMPLETE"
elif difference == 2:
completeness_tsv = "2 BLOCKS MISSING"
elif difference == 1:
completeness_tsv = "1 BLOCK MISSING"
else:
if difference == 0:
completeness_tsv = "COMPLETE"
elif difference > 2:
completeness_tsv = "INCOMPLETE"
elif difference == 2:
completeness_tsv = "2 BLOCKS MISSING"
elif difference == 1:
completeness_tsv = "1 BLOCK MISSING"
report_tsv.append(completeness_tsv)
report_tsv.append(missing_blocks)
report_tsv.append(Kmissing)
report_tsv.append(Kpresent)
# IO-files operations
if not path.isdir(report_tsv_directory):
os.mkdir(report_tsv_directory)
os.chdir(report_tsv_directory)
if percentage_round_tsv >= cutoff:
with open(file_report_tsv, "a") as h:
for el in report_tsv:
if type(el) == str:
h.write(el + "\t")
if type(el) == list:
knums = ",".join(el)
h.write(knums + "\t")
h.write("\n")
def create_tuple_modules(fixed_module_file):
"""
Generates a tuple from the indication of Modules in which to look for incompleteness, for further use.
Args:
fixed_module_file (str): file name of a ".instruction" file with indication of KEGG Modules of interest
Returns:
tuple_modules (tuple): Python tuple-object including all KEGG Modules of interest
"""
with open(fixed_module_file) as f:
tuple_modules = tuple([ line.strip() for line in f ])
return tuple_modules
def create_tuple_modules_1BM(fasta_id, fixed_module_file, oneBM_modules_dir, report_tsv_directory):
"""
Generates a tuple including Modules missing 1 orthologs block, for further use.
Args:
fasta_id (str): identificative FASTA name for a given MAG/Genome
fixed_module_file (str): generic file name of a ".instruction" file with indication of KEGG Modules of interest
oneBM_modules_dir (str): output folder of MAG/Genome specific ".instruction" file with KEGG Modules of interest
report_tsv_directory (str): testcompleteness_tsv() output folder, to identify 1 block missing modules
Returns:
tuple_modules (tuple): Python tuple-object including all KEGG Modules of interest
"""
os.chdir(report_tsv_directory)
list_modules = []
for file in sorted(os.listdir()):
if file.endswith(".tsv") and fasta_id in file:
with open(file) as f:
for line in f.readlines():
line = line.strip().split("\t")
MOD = line[0]
COMPLETENESS = line[2]
if COMPLETENESS == "1 BLOCK MISSING":
list_modules.append(MOD)
os.chdir(oneBM_modules_dir)
with open(fasta_id + "_" + fixed_module_file, "w") as m:
for module in list_modules:
print(module, file=m)
tuple_modules = tuple(list_modules)
return tuple_modules
def write_KOs_from_modules(fasta_id, tuple_modules, report_txt_directory, klists_directory):
"""
Generates a non-redundant list of KOs to be checked via HMM for Modules of interest,
either fixed or related to missing annotated genomic content.
Args:
fasta_id (str): identificative FASTA name for a given MAG/Genome
tuple_modules (tuple): output of "create_tuple_modules()" or "create_tuple_modules_1BM()"
report_txt_directory (str): testcompleteness() output folder, to identify KOs missing from Modules of interest
klists_directory (str): output ".klist" files folder path - in which to save MAG/Genome missing KOs of interest
"""
os.chdir(report_txt_directory)
for file in sorted(os.listdir()):
if fasta_id in file:
with open(file) as f:
klist = []
v = f.readlines()
f.seek(0)
i = 0
for line in v:
i += 1
if line.startswith(tuple_modules):
start = i
j = i
for line in v[j:]:
j += 1
if line.startswith("M0"):
end = j
break
for l in v[start+1:end-2]:
l = l.strip().split("\t")[1].split(", ")
for KO in l:
if KO not in klist:
klist.append(KO)
os.chdir(klists_directory)
with open(file[10:-4]+".klist", "w") as g:
for KO in klist:
print(KO, file=g)
os.chdir(report_txt_directory)
def write_KOs_from_fixed_list(fasta_id, fixed_ko_file, ktests_directory, klists_directory):
"""
Generates a non-redundant list of KOs to be checked via HMM starting from a fixed list.
Args:
fasta_id (str): identificative FASTA name for a given MAG/Genome
fixed_ko_file (str): ".instruction" file generated by "setup.py" to be compiled manually with KOs of interest
ktests_directory (str): ".ktest" files (KOs file as recovered in pre-annotations) folder path
klists_directory (str): output ".klist" files folder path - in which to save MAG/Genome missing KOs of interest
"""
os.chdir(dir_base)
with open(fixed_ko_file) as h:
KO_to_check = [ line.strip() for line in h ]
os.chdir(ktests_directory)
for file in sorted(os.listdir()):
if fasta_id in file:
with open(file) as f:
KO_present = []
klist = []
for line in f.readlines():
KO = line.strip()
KO_present.append(KO)
for KO in KO_to_check:
if KO not in KO_present:
klist.append(KO)
os.chdir(klists_directory)
with open(file[:-6]+".klist", "w") as g:
for KO in klist:
print(KO, file=g)
os.chdir(report_txt_directory)
def taxonomy_filter(taxonomy, dir_base, taxa_file, taxa_dir, update=False):
"""
Generates a file that includes KEGG Brite species codes (E-level)
for a given C-level (phylum, most of the times) taxonomy indication.
Args:
taxonomy (str): KEGG Brite taxonomy for MAG/Genome of interest
as indicated in the "genomes.instruction" file.
dir_base (str): folder path in which "kemet.py" was executed
taxa_file (str): ".keg" output file, that contains each codes of species allowed for subsequent GENES download
taxa_dir (str): output folder path
update (bool, optional): flag to update KEGG Brite taxonomy - necessary e.g. for the first KEMET execution. Defaults to False.
Returns:
taxa_allow (list): Python-list object including each codes of species allowed for subsequent GENES download
"""
os.chdir(dir_base)
taxa_allow = []
with open("br08601.keg") as f:
v = f.readlines()
f.seek(0)
for i, line in enumerate(v):
if line.startswith("C") and taxonomy+" " in line:
i_start = i
break
for line in v[i_start+1:]:
i += 1
if line.startswith("C"):
i_stop = i-1
break
for line in v[i_start:i_stop]:
if line.startswith("E"):
taxa_allow.append(line.strip().replace("E ", "").split(" ")[0])
if update:
os.chdir(taxa_dir)
with open(taxa_file, "w") as g:
for el in taxa_allow:
print(el, file=g)
return taxa_allow
def download_ntseq_of_KO(klist_file, dir_base_KO, dir_KO, klists_directory, taxa_dir, taxa_file, base_com_KEGGget):
"""
Using KEGG API, downloads KEGG flat-files with nt sequences of KOs of interest
from the allowed species (E-level), following filering of "taxonomy_filter()".
IF KEGG ACCESS IS AVAILABLE, it is possible to modify "Pool(processes=3)" with processes=N
and it is possible to download multiple files via API, in full compliance to KEGG license.
Args:
klist_file (str): ".klist" input file name, indicating missing KOs of interest from MAG/Genome
dir_base_KO (str): base KEGG KO GENES sequences folder path
dir_KO (str): KEGG KO GENES sequences folder path, with taxonomic scope indicated in the command-line input
klists_directory (str): ".klist" input files folder path
taxa_dir (str): "taxa_file" input file folder path
taxa_file (str): ".keg" output file, that contains each codes of species allowed for subsequent GENES download
base_com_KEGGget (str): base command of KEGG API "GET" function - which is modified for each entry of GENES
"""
print(_timeinfo(), "START download nucleotidic sequences", sep="\t")
os.chdir(taxa_dir)
with open(taxa_file) as f:
taxa_allow = [ line.strip() for line in f ]
os.chdir(klists_directory)
with open(klist_file) as f:
os.chdir(dir_base_KO)
if not path.isdir(dir_KO):
os.mkdir(dir_KO)
os.chdir(dir_KO)
for line in f:
line = line.strip()
flatfile = line+".keg"
os.chdir(dir_KO)
if not path.isdir(dir_KO+line):
os.mkdir(dir_KO+line)
else:
continue
os.chdir(line)
os.system(base_com_KEGGget+line+" > "+flatfile)
genes = parsekoflat(flatfile)
os.remove(flatfile)
if __name__ == '__main__':
# requests to KEGG API without a granted access are limited (check KEGG LICENCE)
# POSSIBILITY: modify next line "(processes= n)" if access to KEGG is available
with Pool(processes=3) as p:
p.map(getntseq, genes)
p.close()
print(_timeinfo(), "COMPLETE download nucleotidic sequences", sep="\t")
def parsekoflat(file):
"""
Parses KO flatfiles obtained from KEGG API,
in order to generate the filtered list of sequences for a bulk download.
(Called within the "download_ntseq_of_KO()" function).
Args:
file (str): KEGG API KO flat-file file name
Returns:
genes (list): Python-list object with genes connected to the KO,
for each appropriate species within the specified BRITE taxonomy
"""
genes = []
with open(file) as f:
v = f.readlines()
for n, line in enumerate(v):
if line.startswith("GENES"):
break
f.seek(0)
for line in v[n:]:
if line.startswith("REFERENCE") or line.startswith("///"):
break
line = line.replace("GENES ", "").strip()
m = line.index(":")
species = line[:m+1].casefold()
line_s = line.split()
for g_name in line_s[1:]:
gene = (species+g_name).casefold()
if "(" in gene:
p = gene.index("(")
gene = gene[:p]
if "draft" in gene:
continue
genes.append(gene)
return genes
def getntseq(gene):
"""
Downloads nt sequence of a given gene, from the list of KO-related genes list.
(Called within the "download_ntseq_of_KO()" function).
Args:
gene (str): element of "genes" input list, generated via "parsekoflat()"
Returns:
True (bool): only necessary for script continuation
"""
stop = gene.find(":")
gene_taxa = gene[:stop]
if gene_taxa in taxa_allow:
cmd_get_ntseq = base_com_KEGGget+gene+"/ntseq"
os.system(cmd_get_ntseq+" > "+gene+".fna")
return 1
def filter_and_align(taxa_dir, taxa_file, fasta_id, klist_file, klists_directory, msa_dir, dir_KO):
"""
Generates a nucleotidic multifasta with sequences from the given taxonomy range.
The output does NOT contain redundant sequences.
Keeps results in a folder organized by the FASTA id of MAG/Genome.
Args:
taxa_dir (str): "taxa_file" input file folder path
taxa_file (str): ".keg" file, contains each codes of species allowed for subsequent GENES download
fasta_id (str): identificative FASTA name for a given MAG/Genome
klist_file (str): ".klist" file name, indicating missing KOs of interest from MAG/Genome
klists_directory (str): ".klist" input files folder path
msa_dir (str): ".fna" nt multifasta (single representative sequences) output folder path
dir_KO (str): KEGG KO GENES sequences folder path, with taxonomic scope indicated in the command-line input
"""
print(_timeinfo(), "START sequences filtering and alignment", sep="\t")
### filter for taxa of interest
os.chdir(taxa_dir)
with open(taxa_file) as f:
taxa_allow = [ line.strip() for line in f ]
os.chdir(msa_dir)
if not path.isdir(fasta_id):
os.mkdir(fasta_id)
os.chdir(klists_directory)
KO_to_align = []
with open(klist_file) as f:
for line in f.readlines():
KO = line.strip()
if KO not in KO_to_align:
KO_to_align.append(KO)
os.chdir(dir_KO)
for K in sorted(os.listdir()):
if K not in KO_to_align:
continue
# dictionary of non-redundant nt sequences (100% identity)
# in order not to overvalue species with different strains in KEGG taxonomy
# but only focusing on SEQUENCE DIVERSITY
os.chdir("./" + K)
sequniq = {} # {sequence : tax_code_of_identical_seqs}
for nt_file in sorted(os.listdir()):
code = nt_file.split(":")[0]
if code not in taxa_allow:
continue
### exclude redundant nt sequences
with open(nt_file) as f:
seq = f.readlines()[1:]
seq1 = "".join(seq).replace("\n", "")
if not seq1 in sequniq.keys():
vett = [nt_file]
sequniq.update({seq1:vett})
else:
vett = sequniq[seq1]
vett.append(nt_file)
sequniq.update({seq1:vett})
### Write a multiple sequence fasta
os.chdir(msa_dir + fasta_id)
if not path.isdir(K):
os.mkdir(K)
os.chdir(msa_dir + fasta_id + "/" + K)
with open(f"MSA_{K}.fna", "a") as f:
for key, value in sequniq.items():
print(">" + str(value[0][:-4]), file=f)
print(key, file=f)
os.chdir(dir_KO)
print(_timeinfo(), "COMPLETE Filter and align", sep="\t")
def MSA_and_HMM(msa_dir_comm, base_com_mafft, base_com_hmmbuild, log=False):
"""
Runs MAFFT alignment and then build nt profile HMM from it.
Keeps results in a folder organized by the FASTA-header of MAG/Genome.
Args:
msa_dir_comm (str): nt multi-fasta folder path, as modified for the MAG/Genome of interest
base_com_mafft (str): base command for MAFFT execution - modified for each entry of GENES (KO)
base_com_hmmbuild (str): base command for "hmmbuild" execution - modified for each entry of GENES (KO)
log (bool, optional): keep execution times in a log file (if specified in command-line args). Defaults to False.
"""
print(_timeinfo(), "START MSA and HMMs creation", sep="\t")
if log:
logging.info('START MAFFT & hmmbuild execution')
os.chdir(msa_dir_comm)
for K in sorted(os.listdir()):
os.chdir(K)
ch_com_mafft = base_com_mafft.replace("K_NUMBER", K)
ch_com_hmmbuild = base_com_hmmbuild.replace("K_NUMBER", K)
os.system(ch_com_mafft)
os.system(ch_com_hmmbuild)
os.chdir(msa_dir_comm)