forked from Matteopaluh/KEMET
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kemet.py
executable file
·2632 lines (2322 loc) · 108 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
import re
from multiprocessing import Pool
from datetime import datetime
import argparse
import reframed
from reframed import load_cbmodel, save_cbmodel
###############
# extra specs #
###############
_ktest_formats = ["eggnog", "kaas", "kofamkoala"]
_hmm_modes = ["onebm", "modules", "kos"]
_def_thr = 0.43 # threshold optimized from test datasets
_gapfill_modes = ["existing", "denovo"]
_base_com_KEGGget = "curl --silent http://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")+"\t"
return timeinfo
# KMC-functions
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:
headers = g.readlines()[3].strip().split("\t")
koslice = 0
for field in headers:
if not field == "KEGG_ko":
koslice += 1
else:
break
g.seek(0)
for line in g.readlines():
if not line.startswith("#"): # skip header & info lines w/o genes
#fasta_id = line.strip().split("\t")[0]
egg_kos = line.strip().split("\t")[koslice].replace("ko:","")
if egg_kos != "":
egg_kos_hits = egg_kos.split(",")
for ko in egg_kos_hits:
KOs.setdefault(ko, 0)
KOs[ko] += 1
# POSSIBILITY: for each gene, correcting per diff. ortholog hits - if more KOs -> fraction of KO count
#if not ko in KOs:
#KOs[ko] = round(1/len(egg_kos_hits), 2)
#else:
#KOs[ko] += round(1/len(egg_kos_hits), 2)
else:
pass
try:
os.chdir(ktests_directory)
except:
os.mkdir(ktests_directory)
os.chdir(ktests_directory)
with open(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_s = line.strip().split("\t")
if len(line_s) == 2:
if not line_s[1] in KOs:
KOs.append(line_s[1])
elif len(line_s) == 1:
continue
try:
os.chdir(ktests_directory)
except:
os.mkdir(ktests_directory)
os.chdir(ktests_directory)
with open(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 = {}
with open(kofamkoala_file) as g:
# look for fasta_id & KO info based on gene calling IDs lenght
spacer = g.readlines()[1].strip()
fastaslice = spacer.index(" ", 1)+1
koslice = spacer.index(" ", fastaslice)+1
g.seek(0)
for line in g.readlines()[2:]: # skip header and spacer lines w/o genes
fasta_id = line[:fastaslice].strip().replace("* ","")
kofam_ko = line[fastaslice:koslice].strip()
if kofam_ko != "":
KOs.setdefault(kofam_ko, 0)
KOs[kofam_ko] += 1
try:
os.chdir(ktests_directory)
except:
os.mkdir(ktests_directory)
os.chdir(ktests_directory)
with open(converted_output, "w") as g:
for ko in KOs:
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)
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)
if "COMPLEXES_LIST\n" in v:
v_complex = v.index("COMPLEXES_LIST\n")
else:
v_complex = -1
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 != -1:
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 != -1:
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 = 0
submodule += 1
continue
if subOR_presence:
end_or = end-1
if line == "//\n" or count_lines == end_or:
linenumber = 0
check = 0
submodule += 1
if not count_lines == end_or:
subOR += 1
if subOR != 0:
if not 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 not count_lines == end_or:
continue
else:
pass
linenumber += 1
check = 0
ko_line = line.strip().split(", ")
if len(complexes) != 0:
while check == 0:
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 = 1
else:
continue
else:
for element in ko_line:
if not element in str(complexes):
if element in ko_list:
check = 1
break
else:
continue
else:
break
if check == 1:
present += 1
elif check == 0:
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 = 1
else:
if check == 1:
present += 1
pass
else:
missing += 1
control = str(linenumber)+"."+str(submodule)+"\t"+str(line)
report.append(control)
pass
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
if percentage_round == 100:
completeness = "COMPLETE"
else:
completeness = "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:
try:
os.chdir(report_txt_directory)
except:
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
#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 != -1:
#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 != -1:
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 = 0
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 not 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 not count_lines == end_or:
continue
else:
pass
ko_line = line.strip().split(", ")
if len(complexes) != 0:
while check == 0:
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 = 1
else:
continue
else:
for ko in ko_line:
if not ko in str(complexes):
if ko in ko_list:
check = 1
break
else:
continue
else:
break
if check == 1:
present += 1
elif check == 0:
missing += 1
pass
elif len(complexes) == 0:
for ko in ko_list:
if ko in line:
check = 1
else:
if check == 1:
present += 1
pass
else:
missing += 1
pass
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)
if as_kegg:
if present == total:
completeness_tsv = "COMPLETE"
elif present+2 < total or total < 3:
completeness_tsv = "INCOMPLETE"
elif present+2 == total:
completeness_tsv = "2 BLOCKS MISSING"
elif present+1 == total:
completeness_tsv = "1 BLOCK MISSING"
else:
if present == total:
completeness_tsv = "COMPLETE"
if present+2 < total:
completeness_tsv = "INCOMPLETE"
elif present+2 == total:
completeness_tsv = "2 BLOCKS MISSING"
elif present+1 == total:
completeness_tsv = "1 BLOCK MISSING"
report_tsv += [ completeness_tsv,
missing_blocks,
Kmissing,
Kpresent ]
# IO-files operations
try:
os.chdir(report_tsv_directory)
except:
os.mkdir(report_tsv_directory)
os.chdir(report_tsv_directory)
if percentage_round_tsv >= cutoff: # OPTIONAL
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")
# HMM-functions
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 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 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 not KO in klist:
klist.append(KO)
os.chdir(klists_directory)
with open(file[10:-4]+".klist", "w") as g:
for KO in klist:
g.write(KO+"\n")
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 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 not KO in KO_present:
klist.append(KO)
os.chdir(klists_directory)
with open(file[:-6] + ".klist", "w"):
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)
i = 0
for line in v:
i += 1
if line.startswith("C") and taxonomy+" " in line:
i_start = i-1
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")
os.chdir(taxa_dir)
taxa_allow = []
with open(taxa_file) as f:
for line in f.readlines():
taxa_allow.append(line.strip())
os.chdir(klists_directory)
with open(klist_file) as f:
os.chdir(dir_base_KO)
if not os.path.exists(dir_KO):
os.mkdir(dir_KO)
os.chdir(dir_KO)
for line in f.readlines():
line = line.strip()
flatfile = str(line)+".keg"
cmd_dir = "mkdir "+line
os.chdir(dir_KO)
if not os.path.exists(dir_KO+line):
os.system(cmd_dir)
else:
continue
os.chdir(line)
os.system(base_com_KEGGget+line+" > "+flatfile)
genes = parsekoflat(flatfile)
os.system("rm "+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)
print(_timeinfo()+"COMPLETE download nucleotidic sequences")
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()
n = 0
for line in v:
if not line.startswith("GENES"):
n += 1
else:
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
"""
gene_name = gene
stop = gene_name.find(":")
gene_taxa = gene_name[:stop]
if gene_taxa in taxa_allow:
cmd_get_ntseq = base_com_KEGGget+gene_name+"/ntseq"
os.system(cmd_get_ntseq+" > "+gene_name+".fna")
return 1
def filter_and_allign(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 allignment")
### filter for taxa of interest
os.chdir(taxa_dir)
taxa_allow = []
with open(taxa_file) as f:
for line in f.readlines():
taxa_allow.append(line.strip())
os.chdir(msa_dir)
if not fasta_id in os.listdir():
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 not KO in KO_to_align:
KO_to_align.append(KO)
os.chdir(dir_KO)
for K in os.listdir():
if not K 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 os.listdir():
code = nt_file.split(":")[0]
if not code 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 K in os.listdir():
os.mkdir(K)
os.chdir(msa_dir+fasta_id+"/"+K)
with open("MSA_"+K+".fna", "a") as f:
for key, value in sequniq.items():
f.write(">" + str(value[0][:-4]) + "\n")
f.write(key+"\n")
os.chdir(dir_KO)
print(_timeinfo()+"COMPLETE Filter and allign")
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")
os.chdir(msa_dir_comm)
for K in 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)
if log:
logging.info('COMPLETE MAFFT execution')
os.system(ch_com_hmmbuild)
if log:
logging.info('COMPLETE hmmbuild execution')
os.chdir(msa_dir_comm)
print(_timeinfo() + "COMPLETE MSA and HMM creation")
def nhmmer_for_genome(fasta_genome, msa_dir_comm, base_com_nhmmer):
"""
Runs a nHMMER search for newly generated HMM profiles against a given MAG/Genome.
Keeps results in a folder organized by the FASTA id of MAG/Genome.
Args:
fasta_genome (str): identificative FASTA name (including path) for a given MAG/Genome
msa_dir_comm (str): nt multi-fasta folder path, as modified for the MAG/Genome of interest