-
Notifications
You must be signed in to change notification settings - Fork 11
/
FeGenie.py
executable file
·3142 lines (2726 loc) · 166 KB
/
FeGenie.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
from collections import defaultdict
import re
import os
import textwrap
import argparse
import sys
import time
# TODO: ADD CYTOCHROME 579 HMM
# TODO: ADD COLUMN WITH ORF STRAND
def main():
def SUM(ls):
count = 0
for i in ls:
count += float(i)
return count
def firstNum(string):
outputNum = []
for i in string:
try:
int(i)
outputNum.append(i)
except ValueError:
break
Num = "".join(outputNum)
return Num
def Strip(ls):
outList = []
for i in ls:
gene = i.split("|")[0]
outList.append(gene)
return outList
def unique(ls, ls2):
unqlist = []
for i in ls:
if i not in unqlist and i in ls2:
unqlist.append(i)
return len(unqlist)
def Unique(ls):
unqList = []
for i in ls:
if i not in unqList:
unqList.append(i)
return unqList
def Unique2(ls):
unqList = []
for i in ls:
hmm = i.split("|")[0]
if hmm not in unqList:
unqList.append(hmm)
return unqList
def checkFe(ls):
count = 0
uniqueLS = []
for i in ls:
hmm = i.split("|")[0]
if hmm not in uniqueLS:
uniqueLS.append(hmm)
if geneToCatDict[hmm] in ["iron_reduction", "iron_oxidation"]:
count += 1
return count
def checkDFE1(ls):
count = 0
uniqueLS = []
for i in ls:
hmm = i.split("|")[0]
if hmm not in uniqueLS:
uniqueLS.append(hmm)
if hmm in ["DFE_0461", "DFE_0462", "DFE_0463", "DFE_0464", "DFE_0465"]:
count += 1
return count
def checkDFE2(ls):
count = 0
uniqueLS = []
for i in ls:
hmm = i.split("|")[0]
if hmm not in uniqueLS:
uniqueLS.append(hmm)
if hmm in ["DFE_0448", "DFE_0449", "DFE_0450", "DFE_0451"]:
count += 1
return count
def checkGACE(ls):
count = 0
uniqueLS = []
for i in ls:
hmm = i.split("|")[0]
if hmm not in uniqueLS:
uniqueLS.append(hmm)
if hmm in ["GACE_1843", "GACE_1844", "GACE_1845", "GACE_1846", "GACE_1847"]:
count += 1
return count
def check1(ls):
count = 0
uniqueLS = []
for i in ls:
hmm = i.split("|")[0]
if hmm not in uniqueLS:
uniqueLS.append(hmm)
if geneToCatDict[hmm] in ["iron_aquisition-siderophore_transport_potential", "iron_aquisition-heme_transport", "iron_aquisition-siderophore_transport"]:
count += 1
return count
def check1_2(ls):
count = 0
uniqueLS = []
for i in ls:
hmm = i.split("|")[0]
if hmm not in uniqueLS:
uniqueLS.append(hmm)
if geneToCatDict[hmm] in ["iron_aquisition-siderophore_synthesis"]:
count += 1
return count
def check2(ls):
count = 0
uniqueLS = []
for i in ls:
hmm = i.split("|")[0]
if hmm not in uniqueLS:
uniqueLS.append(hmm)
if geneToCatDict[hmm] in ["iron_aquisition-iron_transport", "iron_aquisition-heme_oxygenase"]:
count += 1
return count
def check3(ls):
count = 0
uniqueLS = []
for i in ls:
hmm = i.split("|")[0]
if hmm not in uniqueLS:
uniqueLS.append(hmm)
if geneToCatDict[hmm] in ["iron_aquisition-siderophore_synthesis"]:
count += 1
return count
def checkReg(ls):
count = 0
for i in ls:
hmm = i.split("|")[0]
if re.findall(r'regulation', geneToCatDict[hmm]):
count += 1
return count
def checkMam(ls):
count = 0
uniqueLS = []
for i in ls:
hmm = i.split("|")[0]
if hmm not in uniqueLS:
uniqueLS.append(hmm)
if geneToCatDict[hmm] == "magnetosome_formation":
count += 1
return count
def derep(ls):
outLS = []
for i in ls:
if i not in outLS:
outLS.append(i)
return outLS
def cluster(data, maxgap):
'''Arrange data into groups where successive elements
differ by no more than *maxgap*
#->>> cluster([1, 6, 9, 100, 102, 105, 109, 134, 139], maxgap=10)
[[1, 6, 9], [100, 102, 105, 109], [134, 139]]
#->>> cluster([1, 6, 9, 99, 100, 102, 105, 134, 139, 141], maxgap=10)
[[1, 6, 9], [99, 100, 102, 105], [134, 139, 141]]
'''
# data = sorted(data)
data.sort(key=int)
groups = [[data[0]]]
for x in data[1:]:
if abs(x - groups[-1][-1]) <= maxgap:
groups[-1].append(x)
else:
groups.append([x])
return groups
def lastItem(ls):
x = ''
for i in ls:
x = i
return x
def RemoveDuplicates(ls):
empLS = []
for i in ls:
if i not in empLS:
empLS.append(i)
else:
pass
return empLS
def allButTheLast(iterable, delim):
x = ''
length = len(iterable.split(delim))
for i in range(0, length - 1):
x += iterable.split(delim)[i]
x += delim
return x[0:len(x) - 1]
def secondToLastItem(ls):
x = ''
for i in ls[0:len(ls) - 1]:
x = i
return x
def pull(item, one, two):
ls = []
counter = 0
for i in item:
if counter == 0:
if i != one:
pass
else:
counter += 1
ls.append(i)
else:
if i != two:
ls.append(i)
else:
ls.append(i)
counter = 0
outstr = "".join(ls)
return outstr
def stabilityCounter(int):
if len(str(int)) == 1:
string = (str(0) + str(0) + str(0) + str(0) + str(int))
return (string)
if len(str(int)) == 2:
string = (str(0) + str(0) + str(0) + str(int))
return (string)
if len(str(int)) == 3:
string = (str(0) + str(0) + str(int))
return (string)
if len(str(int)) == 4:
string = (str(0) + str(int))
return (string)
def replace(stringOrlist, list, item):
emptyList = []
for i in stringOrlist:
if i not in list:
emptyList.append(i)
else:
emptyList.append(item)
outString = "".join(emptyList)
return outString
def remove(stringOrlist, list):
emptyList = []
for i in stringOrlist:
if i not in list:
emptyList.append(i)
else:
pass
outString = "".join(emptyList)
return outString
def remove2(stringOrlist, list):
emptyList = []
for i in stringOrlist:
if i not in list:
emptyList.append(i)
else:
pass
# outString = "".join(emptyList)
return emptyList
def removeLS(stringOrlist, list):
emptyList = []
for i in stringOrlist:
if i not in list:
emptyList.append(i)
else:
pass
return emptyList
def fasta(fasta_file):
seq = ''
header = ''
Dict = defaultdict(lambda: defaultdict(lambda: 'EMPTY'))
for i in fasta_file:
i = i.rstrip()
if re.match(r'^>', i):
if len(seq) > 0:
Dict[header] = seq
header = i[1:]
seq = ''
else:
header = i[1:]
seq = ''
else:
seq += i
Dict[header] = seq
# print(count)
return Dict
def fastaRename(fasta_file):
counter = 0
seq = ''
header = ''
Dict = defaultdict(lambda: defaultdict(lambda: 'EMPTY'))
for i in fasta_file:
i = i.rstrip()
if re.match(r'^>', i):
if len(seq) > 0:
Dict[header] = seq
header = i[1:]
header = header.split(" ")[0]
counter += 1
header = header + "_" + str(counter)
seq = ''
else:
header = i[1:]
header = header.split(" ")[0]
counter += 1
header = header + "_" + str(counter)
seq = ''
else:
seq += i
Dict[header] = seq
# print(count)
return Dict
def filter(list, items):
outLS = []
for i in list:
if i not in items:
outLS.append(i)
return outLS
def delim(line):
ls = []
string = ''
for i in line:
if i != " ":
string += i
else:
ls.append(string)
string = ''
ls = filter(ls, [""])
return ls
parser = argparse.ArgumentParser(
prog="FeGenie.py",
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''
*******************************************************
Developed by Arkadiy Garber and Nancy Merino;
University of Southern California, Earth Sciences
Please send comments and inquiries to [email protected]
)`-.--. )\.---. )\.-. )\.---. )\ )\ .'( )\.---.
) ,-._( ( ,-._( ,' ,-,_) ( ,-._( ( \, / \ ) ( ,-._(
\ `-._ \ '-, ( . __ \ '-, ) \ ( ) ( \ '-,
) ,_( ) ,-` ) '._\ _) ) ,-` ( ( \ \ \ ) ) ,-`
( \ ( ``-. ( , ( ( ``-. `.)/ ) ) \ ( ``-.
).' )..-.( )/'._.' )..-.( '.( )/ )..-.(
%(?/////////&//%
.,,. (%((&@@@#/*. .,,.
.,,. @(((/&@@@#///** ...
#&((///////////////*/@
#*@.
() * )//*
<^^> * (/* .
.-""-. *)
.---. ."-....-"-._ _...---''`/. '
( (`\ \ .' ``-'' _.-"'`
\ \ \ : :. .-'
`\`.\: `:. _.'
( .'`.` _.'
`` `-..______.-'
):. (
."-....-".
.':. `.
"-..______..-"
Image design: Nancy Merino (2018);
ASCII art: https://manytools.org/hacker-tools/convert-images-to-ascii-art/
https://ascii.co.uk/text
*******************************************************
'''))
parser.add_argument('-bin_dir', type=str, help="directory of bins", default="NA")
parser.add_argument('-bin_ext', type=str, help="extension for bins (do not include the period)", default="NA")
parser.add_argument('-d', type=int, help="maximum distance between genes to be considered in a genomic \'cluster\'."
"This number should be an integer and should reflect the maximum number of "
"genes in between putative iron-related genes identified by the HMM database "
"(default=5)", default=5)
parser.add_argument('-ref', type=str, help="path to a reference protein database, which must be in FASTA format",
default="NA")
parser.add_argument('-out', type=str, help="name output directory (default=fegenie_out)",
default="fegenie_out")
parser.add_argument('-inflation', type=int, help="inflation factor for final gene category counts (default=1000)",
default=1000)
parser.add_argument('-t', type=int, help="number of threads to use for DIAMOND BLAST and HMMSEARCH "
"(default=1, max=16)", default=1)
parser.add_argument('-bams', type=str, help="a tab-delimited file with two columns: first column has the genome or "
"metagenome file names; second column has the corresponding BAM file "
"(provide full path to the BAM file). Use this option if you have genomes "
"that each have different BAM files associated with them. If you have a set "
"of bins from a single metagenome sample and, thus, have only one BAM file, "
" then use the \'-bam\' option. BAM files are only required if you would like to create "
"a heatmap that summarizes the abundance of a certain gene that is based on "
"read coverage, rather than gene counts.", default="NA")
parser.add_argument('-which_bams', type=str, help="if you provided a tab-delimited file specifying multiple BAM files for "
"your metagenome assemblies or bins/genomes, FeGenie will, by default, "
"make the heatmap CSV and dotplot based on the average depth across all of BAM files. "
"However, with this argument, you can specify which bam in that file that you "
"want FeGenie to use for the generation of a heatmap/dotplot. "
"For example, if only coverage from the first BAM file is desired, "
"then you can specify \'-which_bams 1\'. "
"For the third BAM file in the provided tab-delimited file, \'-which_bams 3\ should be specified'", default="average")
parser.add_argument('-bam', type=str, help="BAM file. This option is only required if you would like to create "
"a heatmap that summarizes the abundance of a certain gene that is based on "
"read coverage, rather than gene counts. If you have more than one BAM file"
"corresponding to different genomes that you are providing, please use the \'-bams\' "
"argument to provide a tab-delimited file that denotes which BAM file (or files) belongs "
"with which genome", default="NA")
# parser.add_argument('-delim', type=str, help="delimiter that separates contig names from ORF names (provide this flag if you are "
# "providing your own ORFs. Default delimiter for Prodigal-predicted ORFs is \'_\'", default="_")
parser.add_argument('-contig_names', type=str, help="contig names in your provided FASTA files. Use this option"
"if you are providing gene calls in amino acid format (don't forget"
"to add the \'--orfs\' flag)", default="NA")
parser.add_argument('-cat', type=str, help="comma-separated list of iron gene categories you'd like FeGenie to look for (default = all categories)", default="NA")
parser.add_argument('--gbk', type=str, help="include this flag if your bins are in Genbank format", const=True,
nargs="?")
parser.add_argument('--orfs', type=str,
help="include this flag if you are providing bins as open-reading frames or genes in FASTA amino-acid format",
const=True,
nargs="?")
parser.add_argument('--skip', type=str,
help="skip the main part of the algorithm (ORF prediction and HMM searching) "
"and re-summarize previously produced results (for example, if you want to re-run using "
"the --norm flag, or providing a BAM file). All other flags/arguments need to "
"be provided (e.g. -bin_dir, -bin_ext, -out, etc.)", const=True, nargs="?")
parser.add_argument('--meta', type=str,
help="include this flag if the provided contigs are from metagenomic/metatranscriptomic assemblies",
const=True, nargs="?")
parser.add_argument('--norm', type=str,
help="include this flag if you would like the gene counts for each iron gene category to be normalized to "
"the number of predicted ORFs in each genome or metagenome. Without "
"normalization, FeGenie will create a heatmap-compatible "
"CSV output with raw gene counts. With normalization, FeGenie will create a "
"heatmap-compatible with \'normalized gene abundances\'", const=True, nargs="?")
parser.add_argument('--all_results', type=str,
help="report all results, regardless of clustering patterns and operon structure", const=True, nargs="?")
parser.add_argument('--heme', type=str,
help="find all genes with heme-binding motifs (CXXCH), and output them to a separate summary file", const=True, nargs="?")
parser.add_argument('--hematite', type=str,
help="find all genes with hematite-binding motifs, and output them to a separate summary file", const=True, nargs="?")
parser.add_argument('--makeplots', type=str,
help="include this flag if you would like FeGenie to make some figures from your data?. "
"To take advantage of this part of the pipeline, you will need to have Rscipt installed. It is a way for R to be called directly from the command line. "
"Please be sure to install all the required R packages as instrcuted in the FeGenie Wiki: "
"https://github.com/Arkadiy-Garber/FeGenie/wiki/Installation. "
"If you see error or warning messages associated with Rscript, you can still expect to "
"see the main output (CSV files) from FeGenie.", const=True, nargs="?")
parser.add_argument('--nohup', type=str, help="include this flag if you are running FeGenie under \'nohup\', and would like to re-write a currently existing directory.", const=True,
nargs="?")
# CHECKING FOR CONDA INSTALL
os.system("echo ${iron_hmms} > HMMlib.txt")
os.system("echo ${rscripts} > rscripts.txt")
file = open("HMMlib.txt")
HMMdir = ""
for i in file:
HMMdir = i.rstrip()
bits = HMMdir + "/" + "HMM-bitcutoffs.txt"
file = open("rscripts.txt")
rscriptDir = ""
for i in file:
rscriptDir = i.rstrip()
try:
test = open(bits)
except FileNotFoundError:
os.system("which FeGenie.py > mainDir.txt")
file = open("mainDir.txt")
for i in file:
location = i.rstrip()
location = allButTheLast(location, "/")
HMMdir = location + "/hmms/iron/"
bits = HMMdir + "/" + "HMM-bitcutoffs.txt"
rscriptDir = location + "/rscripts/"
try:
test = open(bits)
except FileNotFoundError:
print("FeGenie could not locate the required directories. Please run the setup.sh script if "
"you have Conda installed. Otherwise, please run the setupe-noconda.sh script and put FeGenie.py into your $PATH")
raise SystemExit
os.system("rm mainDir.txt")
os.system("rm -f HMMlib.txt rscripts.txt")
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(0)
args = parser.parse_known_args()[0]
# ************** Checking for the required arguments ******************* #
cwd = os.getcwd()
print("checking arguments")
if args.bin_dir != "NA":
binDir = args.bin_dir + "/"
binDirLS = os.listdir(args.bin_dir)
print(".")
else:
print("Looks like you did not provide a directory of genomes/bins or assemblies.")
print("Exiting")
raise SystemExit
if args.bam != "NA" and args.bams != "NA":
print("Please provide only one of the following flags: \'-bam\' or \'-bams\'.")
raise SystemExit
if args.bin_ext != "NA":
print(".")
else:
print(
'Looks like you did not provide an extension for your genomes/bins or assemblies, so FeGenie does not know'
' which files in the provided directory are fasta files that you would like analyzed.')
print("Exiting")
raise SystemExit
try:
os.listdir(args.out)
print("Looks like you already have a directory with the name: " + args.out)
if args.nohup:
answer = "y"
else:
answer = input("Would you like FeGenie to proceed and potentially overwrite files in this directory? (y/n): ")
if answer == "y":
print("Ok, proceeding with analysis!")
try:
os.listdir(args.out + "/ORF_calls")
except FileNotFoundError:
os.system("mkdir %s/ORF_calls" % args.out)
else:
print("Exiting")
raise SystemExit
except FileNotFoundError:
print(".")
os.system("mkdir %s" % args.out)
os.system("mkdir %s/ORF_calls" % args.out)
if lastItem(args.out) == "/":
outDirectory = "%s" % args.out[0:len(args.out)-1]
outDirectoryLS = os.listdir(outDirectory)
else:
outDirectory = "%s" % args.out
outDirectoryLS = os.listdir("%s" % args.out)
print("All required arguments provided!")
print("")
prodigal = 0
# *************** MAKE NR A DIAMOND DB AND READ THE FILE INTO HASH MEMORY ************************ #
if args.ref != "NA":
try:
testFile = open(args.ref + ".dmnd")
except FileNotFoundError:
print("Making diamond database out of provided reference file")
os.system("diamond makedb --in %s -d %s" % (args.ref, args.ref))
# *************** CALL ORFS FROM BINS AND READ THE ORFS INTO HASH MEMORY ************************ #
BinDict = defaultdict(lambda: defaultdict(lambda: 'EMPTY'))
binCounter = 0
for i in binDirLS:
if lastItem(i.split(".")) == args.bin_ext and not re.match(r'\.', i):
cell = i
binCounter += 1
if not args.gbk:
if args.orfs:
testFile = open("%s/%s" % (binDir, i), "r")
for line in testFile:
if re.match(r'>', line):
if re.findall(r'\|]', line):
print("Looks like one of your fasta files has a header containing the character: \|")
print(
"Unfortunately, this is a problem for FeGenie because it uses that character as delimiter to store important information.")
print("Please rename your FASTA file headers")
raise SystemExit
else:
try:
testFile = open("%s/ORF_calls/%s-proteins.faa" % (outDirectory, i), "r")
print("ORFS for %s found. Skipping Prodigal, and going with %s-proteins.faa" % (i, i))
for line in testFile:
if re.match(r'>', line):
if re.findall(r'\|]', line):
print(
"Looks like one of your fasta files has a header containing the character: \|")
print(
"Unfortunately, this is a problem for FeGenie because it uses that character as delimiter to store important information.")
print("Please rename your FASTA file headers")
raise SystemExit
except FileNotFoundError:
binFile = open("%s/%s" % (binDir, i), "r")
for line in binFile:
if re.match(r'>', line):
if re.findall(r'\|]', line):
print("Looks like one of your fasta files has a header containing the character: \|")
print(
"Unfortunately, this is a problem for FeGenie because it uses that character as delimiter to store important information.")
print("Please rename your FASTA file headers")
raise SystemExit
prodigal = 1
print("Finding ORFs for " + cell)
if args.meta:
os.system("prodigal -i %s/%s -a %s/ORF_calls/%s-proteins.faa -o %s/ORF_calls/%s-prodigal.out -p meta -q" % (
binDir, i, outDirectory, i, outDirectory, i))
else:
os.system(
"prodigal -i %s/%s -a %s/ORF_calls/%s-proteins.faa -o %s/ORF_calls/%s-prodigal.out -q" % (
binDir, i, outDirectory, i, outDirectory, i))
else:
os.system('gtt-genbank-to-AA-seqs -i %s/%s -o %s/%s.faa' % (binDir, i, outDirectory, i))
faa = open("%s/%s.faa" % (outDirectory, i))
faa = fasta(faa)
gbkDict = defaultdict(list)
counter = 0
count = 0
gbk = open("%s/%s" % (binDir, i))
for gbkline in gbk:
ls = gbkline.rstrip()
if re.findall(r'/locus_tag', ls):
count += 1
if count > 0:
gbk = open("%s/%s" % (binDir, i))
for gbkline in gbk:
ls = gbkline.rstrip()
if re.findall(r'LOCUS', ls):
locus = (ls)
locus = (locus.split(" ")[1])
locus = locus.split(" ")[0]
if re.findall(r'gene ', ls):
gene = (ls)
gene = (gene.split(" ")[1])
start = (gene.split("..")[0])
end = (gene.split("..")[1])
start = remove(start, ["c", "o", "m", "p", "l", "e", "m", "e", "n", "t", "(", ")"])
end = remove(end, ["c", "o", "m", "p", "l", "e", "m", "e", "n", "t", "(", ")"])
altContigName = (locus + "_" + start + "_" + end)
if re.findall(r'/locus_tag', ls):
locusTag = (ls)
locusTag = (locusTag.split("=")[1])
locusTag = remove(locusTag, ["\""])
counter += 1
if counter > 0:
gbkDict[locus].append(locusTag)
counter = 0
else:
# print(i)
gbk = open("%s/%s" % (binDir, i))
for gbkline in gbk:
ls = gbkline.rstrip()
if re.findall(r'LOCUS', ls):
locus = (ls)
locus = (locus.split(" ")[1])
locus = locus.split(" ")[0]
if re.findall(r'gene ', ls):
gene = (ls)
gene = (gene.split(" ")[1])
start = (gene.split("..")[0])
end = (gene.split("..")[1])
start = remove(start, ["c", "o", "m", "p", "l", "e", "m", "e", "n", "t", "(", ")"])
end = remove(end, ["c", "o", "m", "p", "l", "e", "m", "e", "n", "t", "(", ")"])
altContigName = (locus + "_" + start + "_" + end)
counter += 1
if re.findall(r'/locus_tag', ls):
locusTag = (ls)
locusTag = (locusTag.split("=")[1])
locusTag = remove(locusTag, ["\""])
if counter > 0:
gbkDict[locus].append(altContigName)
counter = 0
idxOut = open("%s/ORF_calls/%s-proteins.idx" % (outDirectory, i), "w")
faaOut = open("%s/ORF_calls/%s-proteins.faa" % (outDirectory, i), "w")
for gbkkey1 in gbkDict.keys():
counter = 0
for gbkey2 in gbkDict[gbkkey1]:
counter += 1
if len(faa[gbkey2]) > 0:
newOrf = gbkkey1 + "_" + str(counter)
idxOut.write(gbkey2 + "," + newOrf + "\n")
faaOut.write(">" + newOrf + "\n")
faaOut.write(str(faa[gbkey2]) + "\n")
idxOut.close()
faaOut.close()
if args.orfs:
file = open("%s/%s" % (binDir, i))
else:
file = open("%s/ORF_calls/%s-proteins.faa" % (outDirectory, i))
file = fasta(file)
for j in file.keys():
orf = j.split(" ")[0]
BinDict[cell][orf] = file[j]
if binCounter == 0:
print("Did not detect any files in the provided directory (%s) matching the provided filename extension (%s). "
"Please double-check the filenames and your command" % (args.bin_dir, args.bin_ext))
raise SystemExit
# ******************** READ BITSCORE CUT-OFFS INTO HASH MEMORY ****************************** #
meta = open(bits, "r")
metaDict = defaultdict(lambda: defaultdict(lambda: 'EMPTY'))
for i in meta:
ls = i.rstrip().split("\t")
metaDict[ls[0]] = ls[1]
# ******************* BEGINNING MAIN ALGORITHM **********************************))))
if not args.skip:
if args.cat == "NA":
catList = []
HMMdirLS = os.listdir(HMMdir)
for FeCategory in HMMdirLS:
if not re.match(r'\.', FeCategory) and FeCategory not in ["HMM-bitcutoffs.txt", "FeGenie-map.txt"]:
catList.append(FeCategory)
else:
categories = args.cat
catList = categories.split(",")
print("starting main pipeline...")
HMMdirLS = os.listdir(HMMdir)
for FeCategory in HMMdirLS:
if not re.match(r'\.', FeCategory) and FeCategory not in ["HMM-bitcutoffs.txt", "FeGenie-map.txt"] and FeCategory in catList:
print("")
print("Looking for following iron-related functional category: " + FeCategory)
hmmDir = "%s/%s/" % (HMMdir, FeCategory)
hmmDirLS2 = os.listdir("%s/%s" % (HMMdir, FeCategory))
HMMdict = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: "EMPTY")))
for i in binDirLS: # ITERATION THROUGH EACH BIN IN A GIVEN DIRECTORY OF BINS
if lastItem(i.split(".")) == args.bin_ext: # FILTERING OUT ANY NON-BIN-RELATED FILES
os.system(
"mkdir -p " + outDirectory + "/" + i + "-HMM") # CREATING DIRECTORY, FOR EACH BIN, TO WHICH HMMSEARCH RESULTS WILL BE WRITTEN
count = 0
for hmm in hmmDirLS2: # ITERATING THROUGH ALL THE HMM FILES IN THE HMM DIRECTORY
count += 1
perc = (count / len(hmmDirLS2)) * 100
sys.stdout.write("analyzing " + i + ": %d%% \r" % (perc))
sys.stdout.flush()
if len(metaDict[hmm.split(".")[0]]) == 0:
bit = 0
else:
bit = metaDict[hmm.split(".")[0]]
if args.orfs:
os.system(
"hmmsearch --cpu %d -T %d --tblout %s/%s-HMM/%s.tblout -o %s/%s-HMM/%s.txt %s/%s %s/%s"
% (int(args.t), float(bit), outDirectory, i, hmm, outDirectory, i, hmm, hmmDir, hmm, binDir, i)
)
else:
os.system(
"hmmsearch --cpu %d -T %d --tblout %s/%s-HMM/%s.tblout -o %s/%s-HMM/%s.txt %s/%s %s/ORF_calls/%s-proteins.faa"
% (int(args.t), float(bit), outDirectory, i, hmm, outDirectory, i, hmm, hmmDir, hmm, outDirectory, i)
)
# REMOVING THE STANDARD OUTPUT FILE
os.system(
"rm " + outDirectory + "/" + i + "-HMM/" + hmm + ".txt"
)
# READING IN THE HMMSEARCH RESULTS (TBLOUT) OUT FILE
try:
hmmout = open(outDirectory + "/" + i + "-HMM/" + hmm + ".tblout", "r")
except FileNotFoundError:
print("FeGenie cannot find the correct hmmsearch output files. "
"If you provided gene or ORF-call sequences, "
"please be sure to specify this in the command using the \'--orfs\' flag")
# COLLECTING SIGNIFICANT HMM HITS IN THE FILE
for line in hmmout:
if not re.match(r'#', line):
ls = delim(line)
evalue = float(ls[4])
bit = float(ls[5])
orf = ls[0]
if evalue < float(1E-1): # FILTERING OUT BACKGROUND NOISE
# LOADING HMM HIT INTO DICTIONARY, BUT ONLY IF THE ORF DID NOT HAVE ANY OTHER HMM HITS
if orf not in HMMdict[i]:
HMMdict[i][orf]["hmm"] = hmm
HMMdict[i][orf]["evalue"] = evalue
HMMdict[i][orf]["bit"] = bit
else:
# COMPARING HITS FROM DIFFERENT HMM FILES TO THE SAME ORF
if bit > HMMdict[i][orf]["bit"]:
HMMdict[i][orf]["hmm"] = hmm
HMMdict[i][orf]["evalue"] = evalue
HMMdict[i][orf]["bit"] = bit
print("")
out = open(outDirectory + "/%s-summary.csv" % (FeCategory), "w")
out.write("cell" + "," + "ORF" + "," + "HMM" + "," + "evalue" + "," + "bitscore" + "\n")
for key in HMMdict.keys():
for j in HMMdict[key]:
out.write(key + "," + j + "," + HMMdict[key][j]["hmm"] + "," +
str(HMMdict[key][j]["evalue"]) + "," + str(HMMdict[key][j]["bit"]) + "\n")
out.close()
time.sleep(5)
print("\n")
print("Consolidating summary files into one master summary file")
out = open(outDirectory + "/FinalSummary.csv", "w")
out.write("category" + "," + "cell" + "," + "orf" + "," + "related_hmm" + "," + "HMM-bitscore" + "\n")
resultsDir = os.listdir(outDirectory)
for i in resultsDir:
if lastItem(i.split("-")) == "summary.csv":
result = open(outDirectory + "/" + i, "r")
for j in result:
ls = j.rstrip().split(",")
cell = ls[0]
orf = ls[1]
hmm = ls[2]
bit = ls[4]
if cell != "cell":
out.write(i.split("-summary")[0] + "," + cell + "," + orf + "," + hmm + "," + str(bit) + "\n")
out.close()
time.sleep(5)
# ****************************************** DEREPLICATION *********************************************************
summary = open(outDirectory + "/FinalSummary.csv", "r")
SummaryDict = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: 'EMPTY')))
for i in summary:
ls = i.rstrip().split(",")
if ls[0] != "category" and ls[0] != "FeGenie":
if len(ls) > 0:
category = ls[0]
cell = ls[1]
orf = ls[2]
hmm = ls[3]
hmmBit = ls[4]
if cell not in SummaryDict.keys():
SummaryDict[cell][orf]["hmm"] = hmm
SummaryDict[cell][orf]["hmmBit"] = hmmBit
SummaryDict[cell][orf]["category"] = category
else:
if orf not in SummaryDict[cell]:
SummaryDict[cell][orf]["hmm"] = hmm
SummaryDict[cell][orf]["hmmBit"] = hmmBit
SummaryDict[cell][orf]["category"] = category
else:
if float(hmmBit) > float(SummaryDict[cell][orf]["hmmBit"]):
SummaryDict[cell][orf]["hmm"] = hmm
SummaryDict[cell][orf]["hmmBit"] = hmmBit
SummaryDict[cell][orf]["category"] = category
# ************************** CLUSTERING OF ORFS BASED ON GENOMIC PROXIMITY *********************************
if not args.orfs:
print("Identifying genomic proximities and putative operons")
CoordDict = defaultdict(lambda: defaultdict(list))
orfNameDict = defaultdict(lambda: defaultdict(list))
for i in SummaryDict.keys():
if i != "category":
for j in SummaryDict[i]:
contig = allButTheLast(j, "_")
numOrf = lastItem(j.split("_"))
CoordDict[i][contig].append(int(numOrf))
counter = 0
print("Clustering ORFs...")
print("")
out = open(outDirectory + "/FinalSummary-dereplicated-clustered.csv", "w")
for i in CoordDict.keys():
print(".")
for j in CoordDict[i]:
LS = (CoordDict[i][j])
clusters = (cluster(LS, args.d))
unknown = [[759,762,763,764,765], [5079,5080,5081]]
for k in clusters:
if len(RemoveDuplicates(k)) == 1:
orf = j + "_" + str(k[0])
out.write(SummaryDict[i][orf]["category"] + "," + i + "," + orf + "," + SummaryDict[i][orf]["hmm"] +
"," + str(SummaryDict[i][orf]["hmmBit"]) + "," + str(counter) + "\n")
out.write("#" + "," + "#" + "," + "#" + "," + "#" + "," + "#" + "," + "#" + "," + "#" + "," + "#" + "\n")
counter += 1
else:
for l in RemoveDuplicates(k):
orf = j + "_" + str(l)
out.write(SummaryDict[i][orf]["category"] + "," + i + "," + orf + "," + SummaryDict[i][orf][
"hmm"] + "," + str(SummaryDict[i][orf]["hmmBit"]) + "," + str(counter) + "\n")
out.write(
"#" + "," + "#" + "," + "#" + "," + "#" + "," + "#" + "," + "#" + "," + "#" + "," + "#" + "\n")
counter += 1
out.close()
else:
if args.contig_names != "NA":
contigNameDict = defaultdict(lambda: defaultdict(lambda: 'EMPTY'))
contigNames = open(args.contig_names)
for orfname in contigNames:
orfnameLS = orfname.rstrip().split("\t")
contigNameDict[orfnameLS[0]]["contig"] = ls[1]
contigNameDict[orfnameLS[0]]["position"] = ls[2]
CoordDict = defaultdict(lambda: defaultdict(list))
orfNameDict = defaultdict(lambda: defaultdict(list))
for i in SummaryDict.keys():
if i != "category":
for j in SummaryDict[i]:
# contigLS = contig.split(args.contig_names + args.delim)
numOrf = contigNameDict[j]["position"]
contig = contigNameDict[j]["contig"]
CoordDict[i][contig].append(int(numOrf))
orfNameDict[contig + "_" + numOrf] = j
CoordDict[i][contig].append(int(numOrf))