-
Notifications
You must be signed in to change notification settings - Fork 15
/
mitofinder
executable file
·1639 lines (1448 loc) · 93.3 KB
/
mitofinder
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/python2.7
#Version: 1.4.2
#Authors: Allio Remi & Schomaker-Bastos Alex
#CBGP - INRAe - ISEM - CNRS - LAMPADA - IBQM - UFRJ
'''
Copyright (c) 2024 Remi Allio - CBGP/INRAe/ISEM/CNRS & Alex Schomaker-Bastos - LAMPADA/UFRJ
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
import argparse, os, shlex, shutil, sys
import os.path
from argparse import RawTextHelpFormatter
import geneChecker, genbankOutput, runMegahit, circularizationCheck, runIDBA, runMetaspades
import subprocess
from subprocess import Popen
from Bio import SeqIO, SeqFeature, SeqUtils
from Bio.Alphabet import generic_dna, generic_protein
import glob
from shutil import copyfile
from datetime import datetime
import time
import operator
import collections
def read_fasta(fp):
name, seq = None, []
for line in fp:
line = line.rstrip()
if line.startswith(">"):
if name: yield (name, ''.join(seq))
name, seq = line, []
else:
seq.append(line)
if name: yield (name, ''.join(seq))
class SmartFormatter(argparse.HelpFormatter):
def _split_lines(self, text, width):
if text.startswith('R|'):
return text[2:].splitlines()
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._split_lines(self, text, width)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Mitofinder is a pipeline to assemble and annotate mitochondrial DNA from trimmed sequencing reads.', formatter_class=SmartFormatter)
parser.add_argument('--megahit', help='Use Megahit for assembly. (Default)',
default=True, dest='megahit', action='store_true')
parser.add_argument('--idba', help='Use IDBA-UD for assembly. ',
default=False, dest='idba', action='store_true')
parser.add_argument('--metaspades', help='Use MetaSPAdes for assembly. ',
default=False, dest='metaspades', action='store_true')
parser.add_argument('-t', '--tRNA-annotation', help = '\"arwen\"/\"mitfi\"/\"trnascan\" tRNA annotater to use. Default = mitfi', default="mitfi", dest='tRNAannotation')
parser.add_argument('-j', '--seqid', help = 'Sequence ID to be used throughout the process', default="", dest='processName')
parser.add_argument('-1', '--Paired-end1', help='File with forward paired-end reads', default="", dest='PE1')
parser.add_argument('-2', '--Paired-end2', help='File with reverse paired-end reads', default="", dest='PE2')
parser.add_argument('-s', '--Single-end', help='File with single-end reads', default="", dest='SE')
parser.add_argument('-c', '--config', help='Use this option to specify another Mitofinder.config file.', default="", dest='config')
parser.add_argument('-a', '--assembly', help='File with your own assembly', default="", dest='Assembly')
parser.add_argument('-m', '--max-memory', help='max memory to use in Go (MEGAHIT or MetaSPAdes)',
default="", dest='mem')
parser.add_argument('-l', '--length', help='Shortest contig length to be used (MEGAHIT). Default = 100', type=int,
default=100, dest='shortestContig')
parser.add_argument('-p', '--processors', help='Number of threads Mitofinder will use at most.', type=int,
default=4, dest='processorsToUse')
parser.add_argument('-r', '--refseq', help='Reference mitochondrial genome in GenBank format (.gb).',
default="", dest='refSeqFile')
parser.add_argument('-e', '--blast-eval', help='e-value of blast program used for contig identification and annotation. Default = 0.00001', type=float,
default=0.00001, dest='blasteVal')
parser.add_argument('-n', '--nwalk', help='Maximum number of codon steps to be tested on each size of the gene to find the start and stop codon during the annotation step. Default = 5 (30 bases)', type=int,
default=5, dest='nWalk')
parser.add_argument('--override', help='This option forces MitoFinder to override the previous output directory for the selected assembler.', default=False, dest='override', action='store_true')
parser.add_argument('--adjust-direction', help='This option tells MitoFinder to adjust the direction of selected contig(s) (given the reference).', default=False, dest='direction', action='store_true')
parser.add_argument('--ignore', help='This option tells MitoFinder to ignore the non-standart mitochondrial genes.', default=False, dest='ignore', action='store_true')
parser.add_argument('--new-genes', help='This option tells MitoFinder to try to annotate the non-standard animal mitochondrial genes (e.g. rps3 in fungi). If several references are used, make sure the non-standard genes have the same names in the several references', default=False, dest='newG', action='store_true')
parser.add_argument('--allow-intron', help='This option tells MitoFinder to search for genes with introns. Recommendation : Use it on mitochondrial contigs previously found with MitoFinder without this option.', default=False, dest='gap', action='store_true')
parser.add_argument('--numt', help='This option tells MitoFinder to search for both mitochondrial genes and NUMTs. Recommendation : Use it on nuclear contigs previously found with MitoFinder without this option. ', default=False, dest='numt', action='store_true')
parser.add_argument('--intron-size', help='Size of intron allowed. Default = 5000 bp',
default=5000, type=float, dest='intronsize')
parser.add_argument('--max-contig', help='Maximum number of contigs matching to the reference to keep. Default = 0 (unlimited)',
default=0, type=int, dest='maxContig')
parser.add_argument('--cds-merge', help='This option tells MitoFinder to not merge the exons in the NT and AA fasta files. ', default=True, dest='merge', action='store_false')
parser.add_argument('--out-gb', help='Do not create annotation output file in GenBank format.', default=True, dest='genbk', action='store_false')
parser.add_argument('--min-contig-size', help='Minimum size of a contig to be considered. Default = 1000',
default=1000, type=float, dest='MinContigSize')
parser.add_argument('--max-contig-size', help='Maximum size of a contig to be considered. Default = 25000',
default=25000, type=float, dest='MaxContigSize')
parser.add_argument('--rename-contig', help='\"yes/no\" If \"yes\", the contigs matching the reference(s) are renamed. Default is \"yes\" for de novo assembly and \"no\" for existing assembly (-a option)', default="default", dest='rename')
parser.add_argument('--blast-identity-nucl', help='Nucleotide identity percentage for a hit to be retained. Default = 50',
default=50, type=float, dest='blastIdentityNucl')
parser.add_argument('--blast-identity-prot', help='Amino acid identity percentage for a hit to be retained. Default = 40',
default=40, type=float, dest='blastIdentityProt')
parser.add_argument('--blast-size', help='Percentage of overlap in blast best hit to be retained. Default = 30',
default=30, type=float, dest='aligncutoff')
parser.add_argument('--circular-size', help='Size to consider when checking for circularization. Default = 45',
default=45, type=int, dest='circularSize')
parser.add_argument('--circular-offset', help='Offset from start and finish to consider when looking for circularization. Default = 200',
default=200, type=int, dest='circularOffSet')
parser.add_argument('-o', '--organism', help="Organism genetic code following NCBI table (integer):\n\
1. The Standard Code \
2. The Vertebrate Mitochondrial Code\
3. The Yeast Mitochondrial Code\
4. The Mold, Protozoan, and Coelenterate Mitochondrial Code and the Mycoplasma/Spiroplasma Code\
5. The Invertebrate Mitochondrial Code\
6. The Ciliate, Dasycladacean and Hexamita Nuclear Code\
9. The Echinoderm and Flatworm Mitochondrial Code\
10. The Euplotid Nuclear Code\
11. The Bacterial, Archaeal and Plant Plastid Code\
12. The Alternative Yeast Nuclear Code\
13. The Ascidian Mitochondrial Code\
14. The Alternative Flatworm Mitochondrial Code\
16. Chlorophycean Mitochondrial Code\
21. Trematode Mitochondrial Code\
22. Scenedesmus obliquus Mitochondrial Code\
23. Thraustochytrium Mitochondrial Code\
24. Pterobranchia Mitochondrial Code\
25. Candidate Division SR1 and Gracilibacteria Code", default="", dest='organismType')
parser.add_argument('-v', '--version', help="Version 1.4.2", default=False, dest='versionCheck', action='store_true')
parser.add_argument('--example', help="Print getting started examples", default=False, dest='example', action='store_true')
parser.add_argument('--citation', help="How to cite MitoFinder", default=False, dest='citation', action='store_true')
args = parser.parse_args()
module_dir = os.path.dirname(__file__)
module_dir = os.path.abspath(module_dir)
blasteVal = args.blasteVal
usingOwnGenBankReference = False
initial_path = os.getcwd()+"/"
if args.example == True:
print "\n # For trimmed paired-end reads:\nmitofinder --megahit -j [seqid] \\\n\t-1 [left_reads.fastq.gz] \\\n\t-2 [right_reads.fastq.gz] \\\n\t-r [genbank_reference.gb] \\\n\t-o [genetic_code] \\\n\t-p [threads] \\\n\t-m [memory]\n\n # For trimmed single-end reads:\nmitofinder --megahit -j [seqid] \\\n\t-s [SE_reads.fastq.gz] \\\n\t-r [genbank_reference.gb] \\\n\t-o [genetic_code] \\\n\t-p [threads] \\\n\t-m [memory]\n\n # For one assembly (one or more contig(s))\nmitofinder -j [seqid] \\\n\t-a [assembly.fasta] \\\n\t-r [genbank_reference.gb] \\\n\t-o [genetic_code] \\\n\t-p [threads] \\\n\t-m [memory]\n"
exit()
if args.citation == True:
txt="\n\nIf you use MitoFinder, please cite:\n- Allio, R., Schomaker Bastos, A., Romiguier, J., Prosdocimi, F., Nabholz, B. & Delsuc, F. (2020). MitoFinder: Efficient automated large-scale extraction of mitogenomic data in target enrichment phylogenomics. Mol Ecol Resour. 20, 892-905. https://doi.org/10.1111/1755-0998.13160\n\nPlease also cite the following references depending on the option chosen for the assembly step in MitoFinder:\n- Li, D., Luo, R., Liu, C. M., Leung, C. M., Ting, H. F., Sadakane, K., Yamashita, H. & Lam, T. W. (2016). MEGAHIT v1.0: a fast and scalable metagenome assembler driven by advanced methodologies and community practices. Methods, 102(6), 3-11.\n- Nurk, S., Meleshko, D., Korobeynikov, A., & Pevzner, P. A. (2017). metaSPAdes: a new versatile metagenomic assembler. Genome research, 27(5), 824-834.\n- Peng, Y., Leung, H. C., Yiu, S. M., & Chin, F. Y. (2012). IDBA-UD: a de novo assembler for single-cell and metagenomic sequencing data with highly uneven depth. Bioinformatics, 28(11), 1420-1428.\n\nFor tRNAs annotation, depending on the option chosen:\n- MiTFi: Juhling, F., Putz, J., Bernt, M., Donath, A., Middendorf, M., Florentz, C., & Stadler, P. F. (2012). Improved systematic tRNA gene annotation allows new insights into the evolution of mitochondrial tRNA structures and into the mechanisms of mitochondrial genome rearrangements. Nucleic acids research, 40(7), 2833-2845.\n- Laslett, D., & Canback, B. (2008). ARWEN: a program to detect tRNA genes in metazoan mitochondrial nucleotide sequences. Bioinformatics, 24(2), 172-175.\n- Chan, P. P., & Lowe, T. M. (2019). tRNAscan-SE: searching for tRNA genes in genomic sequences. In Gene Prediction (pp. 1-14). Humana, New York, NY. \n\n"
txt=txt.replace(u"\u2013","-")
print txt
exit()
if args.versionCheck == True:
print "MitoFinder version 1.4.2"
exit()
if args.organismType != "":
args.organismType=int(args.organismType)
if args.processName == "":
print "\nERROR: SeqID is required (-j option)"
exit()
Logfile=args.processName+"_MitoFinder.log"
Logfile=os.path.join(initial_path,Logfile)
logfile=open(Logfile,"w")
logfile.write('Command line: %s' % ' '.join(sys.argv)+"\n")
logfile.write("\nStart time : "+datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"\n")
logfile.write("\nJob name = "+args.processName+"\n")
start_time=datetime.now()
print ''
print 'Command line: %s' % ' '.join(sys.argv)
print ''
print 'Now running MitoFinder ...\n'
print "Start time : "+datetime.now().strftime("%Y-%m-%d %H:%M:%S")+'\n'
print "Job name = "+args.processName
if not os.path.exists(module_dir+"/install.sh.ok"):
print "\nERROR: MitoFinder is not installed.\nNo such file or directory: "+module_dir+"/install.sh.ok\nPlease run ./install.sh in the MitoFinder directory.\nAborting."
logfile.write("\nERROR: MitoFinder is not installed.\nNo such file or directory: "+module_dir+"/install.sh.ok\nPlease run ./install.sh in the MitoFinder directory.\nAborting.\n")
exit()
if args.tRNAannotation.lower() == "mitfi":
try:
command = "java"
args1 = shlex.split(command)
java_test = Popen(args1, stdout=open("test_java.ok","w"),stderr=open("test_java.ok","w"))
java_test.wait()
if os.path.exists("test_java.ok"):
os.remove("test_java.ok")
except:
print "\nERROR: java is not installed/loaded.\nPlease install/load java to run MitoFinder with MiTFi."
logfile.write("\nERROR: java is not installed/loaded.\nPlease install/load java to run MitoFinder with MiTFi.")
exit()
if args.PE1 == "" and args.PE2 == "" and args.SE == "" and args.Assembly == "" :
print "\nERROR: Read or assembly files are not specified.\n Please, use -1 -2 -s or -a option to specify input data."
logfile.write("\nERROR: Read or assembly files are not specified.\n Please, use -1 -2 -s or -a option to specify input data.\n")
exit()
if args.refSeqFile == "":
print "\nERROR: Reference file is required (-r option)"
logfile.write("\nERROR: Reference file is required (-r option).\n")
exit()
args.refSeqFile=os.path.join(initial_path,args.refSeqFile)
if args.organismType == "":
print "\nERROR: Genetic code is required (-o option) \n\
1. The Standard Code \n\
2. The Vertebrate Mitochondrial Code\n\
3. The Yeast Mitochondrial Code\n\
4. The Mold, Protozoan, and Coelenterate Mitochondrial Code \n\
and the Mycoplasma/Spiroplasma Code\n\
5. The Invertebrate Mitochondrial Code\n\
6. The Ciliate, Dasycladacean and Hexamita Nuclear Code\n\
9. The Echinoderm and Flatworm Mitochondrial Code\n\
10. The Euplotid Nuclear Code\n\
11. The Bacterial, Archaeal and Plant Plastid Code\n\
12. The Alternative Yeast Nuclear Code\n\
13. The Ascidian Mitochondrial Code\n\
14. The Alternative Flatworm Mitochondrial Code\n\
16. Chlorophycean Mitochondrial Code\n\
21. Trematode Mitochondrial Code\n\
22. Scenedesmus obliquus Mitochondrial Code\n\
23. Thraustochytrium Mitochondrial Code\n\
24. Pterobranchia Mitochondrial Code\n\
25. Candidate Division SR1 and Gracilibacteria Code\n"
logfile.write("\nERROR: Genetic code is required (-o option) \n\
1. The Standard Code \n\
2. The Vertebrate Mitochondrial Code\n\
3. The Yeast Mitochondrial Code\n\
4. The Mold, Protozoan, and Coelenterate Mitochondrial Code \n\
and the Mycoplasma/Spiroplasma Code\n\
5. The Invertebrate Mitochondrial Code\n\
6. The Ciliate, Dasycladacean and Hexamita Nuclear Code\n\
9. The Echinoderm and Flatworm Mitochondrial Code\n\
10. The Euplotid Nuclear Code\n\
11. The Bacterial, Archaeal and Plant Plastid Code\n\
12. The Alternative Yeast Nuclear Code\n\
13. The Ascidian Mitochondrial Code\n\
14. The Alternative Flatworm Mitochondrial Code\n\
16. Chlorophycean Mitochondrial Code\n\
21. Trematode Mitochondrial Code\n\
22. Scenedesmus obliquus Mitochondrial Code\n\
23. Thraustochytrium Mitochondrial Code\n\
24. Pterobranchia Mitochondrial Code\n\
25. Candidate Division SR1 and Gracilibacteria Code\n\n")
exit()
args.rename=args.rename.lower()
if args.rename == "y":
args.rename = "yes"
if args.rename == "n":
args.rename = "no"
if args.Assembly != "" and args.rename == "default": #changing default in that case
args.rename = "no"
if args.Assembly == "" and args.rename == "default":
args.rename = "yes"
if args.rename.lower() != "yes" and args.rename != "no":
print "\nERROR: unrecognized value \""+args.rename+"\" for argument: --rename-contig. Please use \"yes\" or \"no\"."
logfile.write("\nERROR: unrecognized value \""+args.rename+"\" for argument: --rename-contig. Please use \"yes\" or \"no\".\n")
exit()
if args.tRNAannotation.lower() == "trnascan":
tRNA="trnascan"
elif args.tRNAannotation.lower() == "arwen":
tRNA="arwen"
elif args.tRNAannotation.lower() == "mitfi":
tRNA="mitfi"
else:
print "ERROR: Option \""+str(args.tRNAannotation) + "\" not recognized for -t/--tRNA-annotation.\nPlease use \"arwen\", \"mitfi\" ot \"trnascan\".\nAborting."
logfile.write("ERROR: Option \""+str(args.tRNAannotation) + "\" not recognized for -t/--tRNA-annotation.\nPlease use \"arwen\", \"mitfi\" ot \"trnascan\".\nAborting.\n")
exit()
if args.PE1 != "":
args.PE1=os.path.join(initial_path,args.PE1)
q1="q1="+args.PE1
if args.PE2 != "":
args.PE2=os.path.join(initial_path,args.PE2)
q2="q2="+args.PE2
if args.SE != "":
args.SE=os.path.join(initial_path,args.SE)
q1="q1="+args.SE
if args.PE1 != "":
if args.PE2 != "":
T="PE"
else:
print "\nERROR: Only a file with forward paired-end reads was specified.\nPlease specify the file with reverse paired-end reads with -2 option.\nIf you want to use single-end reads, please, use -s option."
logfile.write("\nERROR: Only a file with forward paired-end reads was specified.\nPlease specify the file with reverse paired-end reads with -2 option.\nIf you want to use single-end reads, please, use -s option.\n")
exit()
if args.PE2 != "":
if args.PE1 != "":
T="PE"
else:
print "\nERROR: Only a file with reverse paired-end reads was specified.\nPlease specify the file with forward paired-end reads with -1 option.\nIf you want to use single reads, please, use -s option."
logfile.write("\nERROR: Only a file with reverse paired-end reads was specified.\nPlease specify the file with forward paired-end reads with -1 option.\nIf you want to use single reads, please, use -s option.\n")
exit()
if args.SE != "":
T="SE"
if args.metaspades == True :
print "\nERROR: MetaSPAdes cannot be used for assembly from single-end reads. \nUse Megahit or IDBA-UD.\n"
logfile.write("\nERROR: MetaSPAdes cannot for assembly from single-end reads. \nUse Megahit or IDBA-UD.\n")
exit()
if args.PE1 != "" and not os.path.isfile(args.PE1):
print "\nERROR: "+args.PE1+" does not exist"
logfile.write("\nERROR: "+args.PE1+" does not exist")
exit()
if args.PE2 != "" and not os.path.isfile(args.PE2):
print "\nERROR: "+args.PE2+" does not exist"
logfile.write("\nERROR: "+args.PE2+" does not exist")
exit()
if args.SE != "" and not os.path.isfile(args.SE):
print "\nERROR: "+args.SE+" does not exist"
logfile.write("\nERROR: "+args.SE+" does not exist")
exit()
if args.refSeqFile != "" and not os.path.isfile(args.refSeqFile):
print "\nERROR: "+args.refSeqFile+" does not exist"
logfile.write("\nERROR: "+args.refSeqFile+" does not exist")
exit()
if args.Assembly != "":
args.Assembly=os.path.join(initial_path,args.Assembly)
if not os.path.isfile(args.Assembly):
print "\nERROR: "+args.Assembly+" does not exist"
logfile.write("\nERROR: "+args.Assembly+"does not exist")
exit()
if args.PE1 != "" and args.PE2 != "":
inputfile=open(args.processName+".input","w")
inputfile.write("type="+T+"\n"+q1+"\n"+q2)
inputfile.close()
args.inputFile= initial_path+args.processName+".input"
if args.SE != "":
inputfile=open(args.processName+".input","w")
inputfile.write("type="+T+"\n"+q1)
inputfile.close()
args.inputFile= initial_path+args.processName+".input"
args.coveCutOff=7
if args.numt == True:
args.numt = 1
else:
args.numt = 0
if args.gap == True:
args.gap = 1
else:
args.gap = 0
if args.numt == 1 and args.gap == 1:
args.nWalk=0
'''
Read config file and import information.
'''
module_dir = os.path.dirname(__file__)
module_dir = os.path.abspath(module_dir)
if args.config == "":
cfg_full_path = os.path.join(module_dir, 'Mitofinder.config')
else:
cfg_full_path = args.config
initial_path = os.getcwd()
#create output directory
pathtowork=initial_path+"/"+args.processName
logfile.write("\nCreating Output directory : "+pathtowork+"\nAll results will be written here\n")
print ""
print "Creating Output directory : "+pathtowork
print "All results will be written here"
print ""
if not os.path.exists(pathtowork): os.makedirs(pathtowork)
with open(cfg_full_path,'r') as configFile:
for line in configFile:
if '#' != line[0] and line != '\n':
configPart = line.lower().replace('\n','').replace(' ','').split('=')[0]
if configPart == 'megahitfolder':
pathToMegahitFolder = line.replace('\n','').replace(' ','').split('=')[-1]
elif configPart == 'blastfolder':
blastFolder = line.replace('\n','').replace(' ','').split('=')[-1]
elif configPart == 'idbafolder':
pathToIdbaFolder = line.replace('\n','').replace(' ','').split('=')[-1]
elif configPart == 'metaspadesfolder':
pathToMetaspadesFolder = line.replace('\n','').replace(' ','').split('=')[-1]
elif configPart == 'arwenfolder':
pathToArwenFolder = line.replace('\n','').replace(' ','').split('=')[-1]
elif configPart == 'trnascanfolder':
pathTotRNAscanFolder = line.replace('\n','').replace(' ','').split('=')[-1]
elif configPart == 'mitfifolder':
pathToMitfiFolder = line.replace('\n','').replace(' ','').split('=')[-1]
if pathToMegahitFolder.lower() == 'default':
pathToMegahitFolder = os.path.join(module_dir, 'megahit/')
if blastFolder.lower() == 'default':
blastFolder = os.path.join(module_dir, 'blast/bin/')
if pathToIdbaFolder.lower() == 'default':
pathToIdbaFolder = os.path.join(module_dir, 'idba/bin/')
if pathToMetaspadesFolder.lower() == 'default':
pathToMetaspadesFolder = os.path.join(module_dir, 'metaspades/bin/')
if pathToArwenFolder.lower() == 'default':
pathToArwenFolder = os.path.join(module_dir, 'arwen/')
if pathTotRNAscanFolder.lower() == 'default':
pathTotRNAscanFolder = os.path.join(module_dir, 'trnascanSE/tRNAscan-SE-2.0/')
if pathToMitfiFolder.lower() == 'default':
pathToMitfiFolder = os.path.join(module_dir, 'mitfi/')
print 'Program folders:'
print 'MEGAHIT = %s' % pathToMegahitFolder
print 'MetaSPAdes folder = %s' % pathToMetaspadesFolder
print 'IDBA-UD folder = %s' % pathToIdbaFolder
print 'Blast folder = %s' % blastFolder
print 'ARWEN folder = %s' % pathToArwenFolder
print 'MiTFi folder = %s' % pathToMitfiFolder
print 'tRNAscan-SE folder = %s' % pathTotRNAscanFolder
print ''
logfile.write("Program folders:\n"+'MEGAHIT = %s' % pathToMegahitFolder+"\n"+'Blast folder = %s' % blastFolder+"\n"+'IDBA-UD folder = %s' % pathToIdbaFolder+"\n"+'MetaSPAdes folder = %s' % pathToMetaspadesFolder+"\n"+'ARWEN folder = %s' % pathToArwenFolder+"\n"+'MiTFi folder = %s' % pathToMitfiFolder+"\n"+'tRNAscan-SE folder = %s' % pathTotRNAscanFolder+"\n\n")
try :
command = blastFolder + "makeblastdb -h "
args1 = shlex.split(command)
formatDB = Popen(args1, stdout=open(os.devnull, 'wb'))
formatDB.wait()
except:
print blastFolder + "makeblastdb is not executable"
print "Please check the installation and the path indicated above and restart MitoFinder."
print "Aborting"
logfile.write(blastFolder + "makeblastdb is not executable\n"+"Please check the installation and the path indicated above and restart MitoFinder.\n"+"Aborting\n")
exit()
try :
command = blastFolder + "blastn -h "
args1 = shlex.split(command)
formatDB = Popen(args1, stdout=open(os.devnull, 'wb'))
formatDB.wait()
except:
print blastFolder + "blastn is not executable"
print "Please check the installation and the path indicated above and restart Mitofinder."
print "Aborting"
logfile.write(blastFolder + "blastn is not executable\n"+"Please check the installation and the path indicated above and restart Mitofinder.\n"+"Aborting\n")
exit()
try :
command = blastFolder + "blastx -h "
args1 = shlex.split(command)
formatDB = Popen(args1, stdout=open(os.devnull, 'wb'))
formatDB.wait()
except:
print blastFolder + "blastx is not executable"
print "Please check the installation and the path indicated above and restart Mitofinder."
print "Aborting"
logfile.write(blastFolder + "blastx is not executable\n"+"Please check the installation and the path indicated above and restart Mitofinder.\n"+"Aborting\n")
exit()
if args.refSeqFile == None:
print "Reference file is not specified."
print "Aborting"
logfile.write("Reference file is not specified.\n"+"Aborting\n")
#just start the variables for future checking
firstStep = None #Megahit
fourthStep = None #circularization check
fifthStep = None #tRNAscan
# read the refseq and makeblastdb
if args.refSeqFile != None:
if args.refSeqFile[-8:] != '.genbank' and args.refSeqFile[-3:] != '.gb':
print "Reference mitochondrial genome is not in the expected format"
print "Provide a file in GenBank format (.gb)"
print "Aborting"
logfile.write("Reference mitochondrial genome is not in the expected format\n"+"Provide a file in GenBank format (.gb)\n"+"Aborting\n")
exit()
else:
gbk_filename = args.refSeqFile
faa_filename = args.refSeqFile.split("/")[-1].split(".")[0]+".fasta"
input_handle = open(gbk_filename, "r").read()
output_handle = open(pathtowork+"/"+faa_filename, "w")
translatedGene = open(pathtowork+"/translated_genes_for_database.fasta", "w")
contigdatabase = open(pathtowork+"/contig_id_database.fasta", "w")
record = input_handle
importantFeaturesFile = output_handle
listOfImportantFeatures = {}
recordCount=record.count("LOCUS ")
s=0
if record.count("LOCUS ") > 1:
c=0
for line in range(1,record.count("LOCUS ")+1):
c+=1
refSeq=open(gbk_filename).read()
x=refSeq.split("LOCUS ")[c]
tmp=open(args.processName+"_tmp.gb","w")
tmp.write("LOCUS "+x)
tmp.close()
record = SeqIO.read(open(args.processName+"_tmp.gb"), "genbank", generic_dna)
for feature in record.features:
if feature.type.lower() == 'cds':
if 'gene' in feature.qualifiers:
featureName = feature.qualifiers['gene'][0]
elif 'product' in feature.qualifiers:
featureName = feature.qualifiers['product'][0]
featureName = ''.join(featureName.split())
featureName = featureName.replace("/","-")
if not "A" in feature.extract(record).seq.upper() and not "C" in feature.extract(record).seq.upper() and not "G" in feature.extract(record).seq.upper() and not "T" in feature.extract(record).seq.upper():
print "WARNING: no nucleotide sequence have been found for the gene "+str(featureName)+" for the reference "+str(record.id)+"."
logfile.write("WARNING: no nucleotide sequence have been found for the gene "+str(featureName)+" for the reference "+str(record.id)+".")
else:
importantFeaturesFile.write('>' + record.id + "@" + featureName + '\n')
importantFeaturesFile.write(str(feature.extract(record).seq)+'\n')
s=1
translatedGene.write('>' + record.id + "@" + featureName + '\n')
if 'translation' in feature.qualifiers:
translatedGene.write(str(feature.qualifiers['translation'][0]) + '\n')
else:
translatedGene.write(str(feature.extract(record).seq.translate(table=args.organismType,to_stop=True))+'\n')
print ' WARNING: Reference did not specify a CDS translation for %s. MitoFinder is creating its own from refSeq' % featureName
logfile.write(' WARNING: Reference did not specify a CDS translation for %s. MitoFinder is creating its from refSeq' % featureName + "\n")
if feature.type.lower() == 'rrna' :
if 'gene' in feature.qualifiers:
featureName = feature.qualifiers['gene'][0]
featureName = ''.join(featureName.split())
if not "A" in feature.extract(record).seq.upper() and not "C" in feature.extract(record).seq.upper() and not "G" in feature.extract(record).seq.upper() and not "T" in feature.extract(record).seq.upper():
print "WARNING: no nucleotides sequence have been found for the gene "+str(featureName)+" for the reference "+str(record.id)+"."
else:
importantFeaturesFile.write('>' + record.id + "@" + featureName + '\n')
importantFeaturesFile.write(str(feature.extract(record).seq) + '\n')
listOfImportantFeatures[featureName] = feature
s=1
elif 'product' in feature.qualifiers:
featureName = feature.qualifiers['product'][0]
featureName = ''.join(featureName.split())
if not "A" in feature.extract(record).seq.upper() and not "C" in feature.extract(record).seq.upper() and not "G" in feature.extract(record).seq.upper() and not "T" in feature.extract(record).seq.upper():
print "WARNING: no nucleotide sequence have been found for the gene "+str(featureName)+" for the reference "+str(record.id)+"."
logfile.write("WARNING: no nucleotide sequence have been found for the gene "+str(featureName)+" for the reference "+str(record.id)+".")
else:
importantFeaturesFile.write('>' + record.id + "@" + featureName + '\n')
importantFeaturesFile.write(str(feature.extract(record).seq) + '\n')
listOfImportantFeatures[featureName] = feature
s=1
os.remove(args.processName+"_tmp.gb")
else:
record = SeqIO.read(open(gbk_filename), "genbank", generic_dna)
for feature in record.features:
if feature.type.lower() == 'cds':
if 'gene' in feature.qualifiers:
featureName = feature.qualifiers['gene'][0]
elif 'product' in feature.qualifiers:
featureName = feature.qualifiers['product'][0]
featureName = ''.join(featureName.split())
featureName = featureName.replace("/","-")
if not "A" in feature.extract(record).seq.upper() and not "C" in feature.extract(record).seq.upper() and not "G" in feature.extract(record).seq.upper() and not "T" in feature.extract(record).seq.upper():
print "WARNING: no nucleotide sequence have been found for the gene "+str(featureName)+" for the reference "+str(record.id)+"."
logfile.write("WARNING: no nucleotide sequence have been found for the gene "+str(featureName)+" for the reference "+str(record.id)+".")
else:
importantFeaturesFile.write('>' + record.id + "@" + featureName + '\n')
importantFeaturesFile.write(str(feature.extract(record).seq)+'\n')
s=1
translatedGene.write('>' + record.id + "@" + featureName + '\n')
if 'translation' in feature.qualifiers:
translatedGene.write(str(feature.qualifiers['translation'][0]) + '\n')
else:
translatedGene.write(str(feature.extract(record).seq.translate(table=args.organismType,to_stop=True))+'\n')
print ' WARNING: Reference did not specify a CDS translation for %s. MitoFinder is creating its from refSeq' % featureName
logfile.write(' WARNING: Reference did not specify a CDS translation for %s. MitoFinder is creating its from refSeq' % featureName +"\n")
if feature.type.lower() == 'rrna' :
if 'gene' in feature.qualifiers:
featureName = feature.qualifiers['gene'][0]
featureName = ''.join(featureName.split())
if not "A" in feature.extract(record).seq.upper() and not "C" in feature.extract(record).seq.upper() and not "G" in feature.extract(record).seq.upper() and not "T" in feature.extract(record).seq.upper():
print "WARNING: no nucleotide sequence have been found for the gene "+str(featureName)+" for the reference "+str(record.id)+"."
logfile.write("WARNING: no nucleotide sequence have been found for the gene "+str(featureName)+" for the reference "+str(record.id)+".")
else:
importantFeaturesFile.write('>' + record.id + "@" + featureName + '\n')
importantFeaturesFile.write(str(feature.extract(record).seq) + '\n')
s=1
listOfImportantFeatures[featureName] = feature
elif 'product' in feature.qualifiers:
featureName = feature.qualifiers['product'][0]
featureName = ''.join(featureName.split())
if not "A" in feature.extract(record).seq.upper() and not "C" in feature.extract(record).seq.upper() and not "G" in feature.extract(record).seq.upper() and not "T" in feature.extract(record).seq.upper():
print "WARNING: no nucleotide sequence have been found for the gene "+str(featureName)+" for the reference "+str(record.id)+"."
logfile.write("WARNING: no nucleotide sequence have been found for the gene "+str(featureName)+" for the reference "+str(record.id)+".")
else:
importantFeaturesFile.write('>' + record.id + "@" + featureName + '\n')
importantFeaturesFile.write(str(feature.extract(record).seq) + '\n')
s=1
listOfImportantFeatures[featureName] = feature
output_handle.close()
translatedGene.close()
contigdatabase.close()
if s == 0:
print "\nERROR: MitoFinder didn't found any nucleotide sequence in the reference(s) file(s).\nAborting"
logfile.write("ERROR: MitoFinder didn't found any nucleotide sequence in the reference(s) file(s).\nAborting")
exit()
#create a gene database
os.chdir(pathtowork)
dico_genes={}
dico_unknown={}
for f in glob.glob("ref*database.fasta*"):
os.remove(f)
for f in glob.glob("./*tmp/ref*database.fasta*"):
os.remove(f)
for name, seq in read_fasta(open("translated_genes_for_database.fasta")):
namesp=name
name=name.split("@")[1]
if name.lower() == "coi" or name.lower() == "coxi" or name.lower() == "co1" or name.lower() == "cox1" or name.lower().replace(" ","").replace("-","") == "cytochromecoxidasesubunit1" or name.lower().replace(" ","").replace("-","") == "cytochromecoxidasesubuniti" or name.lower().replace(" ","").replace("-","") == "cytochromeoxidasesubunit1" or name.lower().replace(" ","").replace("-","") == "cytochromeoxidasesubuniti":
name="COX1"
elif name.lower() == "coii" or name.lower() == "coxii" or name.lower() == "co2" or name.lower() == "cox2" or name.lower().replace(" ","").replace("-","") == "cytochromecoxidasesubunit2" or name.lower().replace(" ","").replace("-","") == "cytochromecoxidasesubunitii" or name.lower().replace(" ","").replace("-","") == "cytochromeoxidasesubunit2" or name.lower().replace(" ","").replace("-","") == "cytochromeoxidasesubunitii":
name="COX2"
elif name.lower() == "coiii" or name.lower() == "coxiii" or name.lower() == "co3" or name.lower() == "cox3" or name.lower().replace(" ","").replace("-","") == "cytochromecoxidasesubunit3" or name.lower().replace(" ","").replace("-","") == "cytochromecoxidasesubunitiii" or name.lower().replace(" ","").replace("-","") == "cytochromeoxidasesubunit3" or name.lower().replace(" ","").replace("-","") == "cytochromeoxidasesubunitiii":
name="COX3"
elif name.lower() == "cytb" or name.lower() == "cob" or name.lower().replace(" ","").replace("-","") == "cytochromeb":
name="CYTB"
elif name.lower() == "nd1" or name.lower() == "nad1" or name.lower() == "ndh1" or name.lower() == "nadh1" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunit1" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubuniti":
name="ND1"
elif name.lower() == "nd2" or name.lower() == "nad2" or name.lower() == "ndh2" or name.lower() == "nadh2" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunit2" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunitii":
name="ND2"
elif name.lower() == "nd3" or name.lower() == "nad3" or name.lower() == "ndh3" or name.lower() == "nadh3" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunit3" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunitiii":
name="ND3"
elif name.lower() == "nd4" or name.lower() == "nad4" or name.lower() == "ndh4" or name.lower() == "nadh4" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunit4" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunitiv":
name="ND4"
elif name.lower() == "nd4l" or name.lower() == "nad4l" or name.lower() == "ndh4l" or name.lower() == "nadh4l" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunit4l" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunitivl":
name="ND4L"
elif name.lower() == "nd5" or name.lower() == "nad5" or name.lower() == "ndh5" or name.lower() == "nadh5" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunit5" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunitv":
name="ND5"
elif name.lower() == "nd6" or name.lower() == "nad6" or name.lower() == "ndh6" or name.lower() == "nadh6" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunit6" or name.lower().replace(" ","").replace("-","") == "nadhdehydrogenasesubunitvi":
name="ND6"
elif name.lower() == "atp8" or name.lower().replace(" ","").replace("-","") == "atpsynthasef0subunit8" or name.lower().replace(" ","").replace("-","") == "atpase8":
name="ATP8"
elif name.lower() == "atp6" or name.lower().replace(" ","").replace("-","") == "atpsynthasef0subunit6" or name.lower().replace(" ","").replace("-","") == "atpase6":
name="ATP6"
elif name.lower().replace(" ","").replace("-","") == "rrnl" or name.lower().replace(" ","").replace("-","") == "16sribosomalrna" or name.lower().replace(" ","").replace("-","") == "largesubunitribosomalrna" or name.lower().replace(" ","").replace("-","") == "lrrna" or name.lower().replace(" ","").replace("-","") == "16sribosomalrna" or name.lower().replace(" ","").replace("-","") == "16srrna" or name.lower().replace(" ","").replace("-","") == "rnr2" or name.lower().replace(" ","").replace("-","") == "mtrnr2" or name.lower().replace(" ","").replace("-","") == "rrn16" or name.lower().replace(" ","").replace("-","") == "rnl" or name.lower().replace(" ","").replace("-","") == "lsu":
name="rrnL"
elif name.lower().replace(" ","").replace("-","") == "rrns" or name.lower().replace(" ","").replace("-","") == "12sribosomalrna" or name.lower().replace(" ","").replace("-","") == "smallsubunitribosomalrna" or name.lower().replace(" ","").replace("-","") == "srrna" or name.lower().replace(" ","").replace("-","") == "12sribosomalrna" or name.lower().replace(" ","").replace("-","") == "12srrna" or name.lower().replace(" ","").replace("-","") == "rnr1" or name.lower().replace(" ","").replace("-","") == "mtrnr1" or name.lower().replace(" ","").replace("-","") == "rrn12" or name.lower().replace(" ","").replace("-","") == "rns" or name.lower().replace(" ","").replace("-","") == "ssu":
name="rrnS"
else:
if args.ignore == False and args.newG == False:
dico_unknown[name]=name
elif args.newG == True and not dico_genes.has_key(name):
print "Gene named \""+name+"\" in the reference file is not recognized by MitoFinder."
print "MitoFinder will try to annotate it."
logfile.write("Gene named \""+name+"\" in the reference file is not recognized by MitoFinder."+"\n"+"MitoFinder will try to annotate it."+"\n\n")
elif args.newG == True and dico_genes.has_key(name):
pass
elif args.ignore == True and args.newG == False:
if not dico_unknown.has_key(name):
print "WARNING: Gene named \""+name+"\" in the reference file is not recognized by MitoFinder."
print "This gene will not be annotated by MitoFinder"
logfile.write("WARNING: Gene named \""+name+"\" in the reference file is not recognized by MitoFinder.\n"+"This gene will not be annotated by MitoFinder\n\n")
dico_unknown[name]=name
name="no"
if name != "rrnL" and name != "rrnS" and name != "no":
geneOut=open("ref_"+name+"_database.fasta",'a')
geneOut.write(namesp.split("@")[0]+"@"+name+"\n"+seq+"\n")
dico_genes[name]=name
for name, seq in read_fasta(open(faa_filename)):
namesp=name
name=name.split("@")[1]
if name.lower().replace(" ","").replace("-","") == "rrnl" or name.lower().replace(" ","").replace("-","") == "16sribosomalrna" or name.lower().replace(" ","").replace("-","") == "largesubunitribosomalrna" or name.lower().replace(" ","").replace("-","") == "lrrna" or name.lower().replace(" ","").replace("-","") == "16sribosomalrna" or name.lower().replace(" ","").replace("-","") == "16srrna" or name.lower().replace(" ","").replace("-","") == "rnr2" or name.lower().replace(" ","").replace("-","") == "mtrnr2" or name.lower().replace(" ","").replace("-","") == "rrn16" or name.lower().replace(" ","").replace("-","") == "rnl" or name.lower().replace(" ","").replace("-","") == "lsu":
name="rrnL"
elif name.lower().replace(" ","").replace("-","") == "rrns" or name.lower().replace(" ","").replace("-","") == "12sribosomalrna" or name.lower().replace(" ","").replace("-","") == "smallsubunitribosomalrna" or name.lower().replace(" ","").replace("-","") == "srrna" or name.lower().replace(" ","").replace("-","") == "12sribosomalrna" or name.lower().replace(" ","").replace("-","") == "12srrna" or name.lower().replace(" ","").replace("-","") == "rnr1" or name.lower().replace(" ","").replace("-","") == "mtrnr1" or name.lower().replace(" ","").replace("-","") == "rrn12" or name.lower().replace(" ","").replace("-","") == "rns" or name.lower().replace(" ","").replace("-","") == "ssu":
name="rrnS"
else:
pass
if name == "rrnL" or name == "rrnS":
geneOut=open("ref_"+name+"_database.fasta",'a')
geneOut.write(namesp.split("@")[0]+"@"+name+"\n"+seq+"\n")
dico_genes[name]=name
geneOut=open("contig_id_database.fasta",'a')
geneOut.write(namesp.split("@")[0]+"@"+name+"\n"+seq+"\n")
geneOut.close()
if len(dico_unknown) > 0 and args.ignore == False and args.newG == False:
if len(dico_unknown) == 1:
print "ERROR: Gene named \""+next(iter(dico_unknown))+"\" in the reference file(s) is not recognized by MitoFinder."
print "This gene is not a standard mitochondrial gene (use --ignore or --new-genes options) or please change it to one of the following gene names:"
print "COX1; COX2; COX3; CYTB; ND1; ND2; ND3; ND4; ND4L; ND5; ND6; ATP8; ATP6; rrnL; rrnS"
print " "
print "If you decide to use the new-genes option, please be aware that the names of the new genes in your reference(s) should be homogenized to be considered as unique by MitoFinder (example : Gene1 is not equal to gene1 or gene-1 , use one unique name for all equivalent genes in the different references) "
print " "
print "Aborting"
print " "
logfile.write("ERROR: Gene named \""+name+"\" in the reference file(s) are not recognized by MitoFinder\n"+"This gene is not a standard mitochondrial gene (use --ignore or --new-genes options) or please change it to one of the following gene names:\n"+"COX1; COX2; COX3; CYTB; ND1; ND2; ND3; ND4; ND4L; ND5; ND6; ATP8; ATP6; rrnL; rrnS\n\nIf you decide to use the new-genes option, please be aware that the names of the new genes in your reference(s) should be homogenized to be considered as unique by MitoFinder (example : Gene1 is not equal to gene1 or gene-1 , use one unique name for all equivalent genes in the different references)\n"+"Aborting\n\n")
else:
print "ERROR: The following genes in the reference file(s) are not recognized by MitoFinder."
for k, v in dico_unknown.items():
print " -" + k
logfile.write(" -"+k+"\n")
print "These genes are not standard mitochondrial genes (use --ignore or --new-genes options) or please change them to one of the following gene names:"
print "COX1; COX2; COX3; CYTB; ND1; ND2; ND3; ND4; ND4L; ND5; ND6; ATP8; ATP6; rrnL; rrnS"
print " "
print "If you decide to use the new-genes option, please be aware that the names of the new genes in your reference(s) should be homogenized to be considered as unique by MitoFinder (example : Gene1 is not equal to gene1 or gene-1 , use one unique name for all equivalent genes in the different references) "
print " "
print "Aborting"
print " "
logfile.write("ERROR: Gene named \""+name+"\" in the reference file(s) are not recognized by MitoFinder\n"+"These genes are not standard mitochondrial genes (use --ignore or --new-genes options) or please change them to one of the following gene names:\n"+"COX1; COX2; COX3; CYTB; ND1; ND2; ND3; ND4; ND4L; ND5; ND6; ATP8; ATP6; rrnL; rrnS\n\nIf you decide to use the new-genes option, please be aware that the names of the new genes in your reference(s) should be homogenized to be considered as unique by MitoFinder (example : Gene1 is not equal to gene1 or gene-1 , use one unique name for all equivalent genes in the different references)\n"+"Aborting\n\n")
exit()
print ""
logfile.write("\n")
command = blastFolder + "makeblastdb -in " + str(faa_filename) + " -dbtype nucl" #need to formatdb refseq first
args1 = shlex.split(command)
formatDB = Popen(args1, stdout=open(os.devnull, 'wb'))
formatDB.wait()
command = blastFolder + "makeblastdb -in contig_id_database.fasta -dbtype nucl" #need to formatdb refseq first
args1 = shlex.split(command)
formatDB = Popen(args1, stdout=open(os.devnull, 'wb'))
formatDB.wait()
geneList=open(pathtowork+"/genes_list",'w')
for cle, valeur in dico_genes.items():
geneList.write(cle+"\n")
geneList.close()
for i in ("COX1","COX2","COX3","CYTB","ND1","ND2","ND3","ND4","ND4L","ND5","ND6","ATP6","ATP8","rrnL","rrnS"):
if not i in open(pathtowork+"/genes_list","r").read():
print "WARNING: "+i+" is not in the reference file. MitoFinder will not annotate this gene."
logfile.write("WARNING: "+i+" is not in the reference file. MitoFinder will not annotate this gene.\n")
Assembly=True
if args.Assembly != "":
args.Assembly=os.path.join(initial_path,args.Assembly)
args.megahit = False
args.idba = False
args.metaspades = False
if os.path.exists(pathtowork+"/"+args.processName+"_link.scafSeq"):
os.remove(pathtowork+"/"+args.processName+"_link.scafSeq")
os.symlink(args.Assembly, pathtowork+"/"+args.processName+"_link.scafSeq")
link_file=args.processName+"_link.scafSeq"
assembler=""
if args.megahit == True and args.idba == False and args.metaspades == False:
assembler="_megahit"
if args.idba == True:
assembler="_idba"
if args.metaspades == True:
assembler="_metaspades"
pathOfFinalResults = pathtowork + "/" + args.processName + "_MitoFinder" + assembler + "_" + tRNA + '_Final_Results/'
if os.path.exists(pathOfFinalResults):
shutil.rmtree(pathOfFinalResults)
if not os.path.exists(pathOfFinalResults):
os.makedirs(pathOfFinalResults)
if Assembly == True:
logfile.close()
#let's call megahit
if args.megahit == True and args.idba == False and args.metaspades == False:
firstStep = runMegahit.runMegahit(processName = args.processName, inputFile = args.inputFile, shortestContig = args.shortestContig, processorsToUse = args.processorsToUse, megahitFolder = pathToMegahitFolder, refSeqFile = args.refSeqFile, organismType = args.organismType, blastFolder = blastFolder, maxMemory=args.mem, logfile=Logfile, override=args.override)
out=args.processName+"_megahit"
logfile=open(Logfile,"a")
if not os.path.isfile(pathtowork+"/"+out+"/"+out+".contigs.fa") == True:
print "\n Megahit didn't run"
print "Delete or rename the Megahit result folder and restart MitoFinder"
logfile.write("\n Megahit didn't run\n"+"Delete or rename the Megahit result folder and restart MitoFinder\n")
exit()
if os.path.exists(pathtowork+"/"+args.processName+"_link_megahit.scafSeq"):
os.remove(pathtowork+"/"+args.processName+"_link_megahit.scafSeq")
os.symlink(pathtowork+"/"+out+"/"+out+".contigs.fa", pathtowork+"/"+args.processName+"_link_megahit.scafSeq")
link_file=args.processName+"_link_megahit.scafSeq"
#let's call IDBA-UD
if args.idba == True :
firstStep = runIDBA.runIDBA(processName = args.processName, inputFile = args.inputFile, shortestContig = args.shortestContig, processorsToUse = args.processorsToUse, idbaFolder = pathToIdbaFolder, refSeqFile = args.refSeqFile, organismType = args.organismType, blastFolder = blastFolder, logfile=Logfile, override=args.override)
out=args.processName+"_idba"
logfile=open(Logfile,"a")
if not os.path.isfile(pathtowork+"/"+out+"/contig.fa") == True:
print "\n IDBA-UD didn't run"
print "Delete or rename the IDBA-UD result folder and restart MitoFinder"
logfile.write("\n IDBA-UD didn't run\n"+"Delete or rename the IDBA-UD result folder and restart MitoFinder\n")
exit()
if os.path.exists(pathtowork+"/"+args.processName+"_link_idba.scafSeq"):
os.remove(pathtowork+"/"+args.processName+"_link_idba.scafSeq")
os.symlink(pathtowork+"/"+out+"/contig.fa", pathtowork+"/"+args.processName+"_link_idba.scafSeq")
link_file=args.processName+"_link_idba.scafSeq"
#let's call MetaSPAdes
if args.metaspades == True :
firstStep = runMetaspades.runMetaspades(processName = args.processName, inputFile = args.inputFile, shortestContig = args.shortestContig, processorsToUse = args.processorsToUse, metaspadesFolder = pathToMetaspadesFolder, refSeqFile = args.refSeqFile, organismType = args.organismType, blastFolder = blastFolder, maxMemory=args.mem, logfile=Logfile, override=args.override)
out=args.processName+"_metaspades"
logfile=open(Logfile,"a")
if not os.path.isfile(pathtowork+"/"+out+"/"+"scaffolds.fasta") == True:
print "\n MetaSPAdes didn't run"
print "Delete or rename the MetaSPAdes result folder and restart MitoFinder"
logfile.write("\n MetaSPAdes didn't run\n"+"Delete or rename the MetaSPAdes result folder and restart MitoFinder\n")
exit()
if os.path.exists(pathtowork+"/"+args.processName+"_link_metaspades.scafSeq"):
os.remove(pathtowork+"/"+args.processName+"_link_metaspades.scafSeq")
os.symlink(pathtowork+"/"+out+"/"+"scaffolds.fasta", pathtowork+"/"+args.processName+"_link_metaspades.scafSeq")
link_file=args.processName+"_link_metaspades.scafSeq"
#identification of contigs matching on the refSeq
blasteVal=args.blasteVal
if args.metaspades == False and args.megahit == False and args.idba == False:
logfile=open(Logfile,"a")
print "Formatting database for mitochondrial contigs identification..."
logfile.write("Formatting database for mitochondrial contigs identification...\n")
command = blastFolder+"/makeblastdb -in " + link_file + " -dbtype nucl"
args1 = shlex.split(command)
formatDB = Popen(args1, stdout=open(os.devnull, 'wb'))
formatDB.wait()
print "Running mitochondrial contigs identification step..."
logfile.write("Running mitochondrial contigs identification step...\n")
with open(args.processName + '_blast_out.txt','w') as BlastResult:
command = blastFolder+"/blastn -db " + link_file + " -query contig_id_database.fasta -evalue " + str(blasteVal) + " -outfmt 6 -perc_identity " + str(args.blastIdentityNucl)
args1 = shlex.split(command)
blast = Popen(args1, stdout=BlastResult)
blast.wait()
os.rename(args.processName+'_blast_out.txt', pathtowork+"/"+args.processName+'_blast_out.txt')
mitoblast=open(pathtowork+"/"+args.processName+'_blast_out.txt')
#fl = sum(1 for line in open(pathtowork+"/"+args.processName+'_blast_out.txt'))
dico_size_contig={}
for r in SeqIO.parse(pathtowork+"/"+link_file,"fasta"):
dico_size_contig[r.id]=len(r.seq)
dico_direction={}
dico_score={}
sup=0
for line in mitoblast:
#testedGene=line.split("\t")[0].split("@")[1]
contig=line.split("\t")[1].split("\t")[0]
if float(dico_size_contig.get(contig)) >= args.MinContigSize and float(dico_size_contig.get(contig)) <= args.MaxContigSize :
score=float(line.split("\t")[11])
ident=line.split("\t")[2]
start=float(line.split("\t")[8])
end=float(line.split("\t")[9])
if start < end:
direction="+"
else:
direction="-"
if dico_direction.has_key(contig):
dico_direction[contig]=dico_direction.get(contig)+";"+direction
else:
dico_direction[contig]=direction
if dico_score.has_key(contig):
if score > dico_score.get(contig):
dico_score[contig]=score
else:
dico_score[contig]=score
elif float(dico_size_contig.get(contig)) >= args.MinContigSize and float(dico_size_contig.get(contig)) >= args.MaxContigSize:
sup=1
sorted_y = sorted(dico_score.items(), key=operator.itemgetter(1), reverse = True)
sorted_dico_score = collections.OrderedDict(sorted_y)
if len(collections.OrderedDict(sorted_y)) == 0:
if sup == 0:
print "MitoFinder dit not found any mitochondrial contig"
print ""
logfile.write("MitoFinder dit not found any mitochondrial contig\n\n")
time=datetime.now() - start_time
print "Total wall-clock time used by MitoFinder = "+str(time)
logfile.write("\nTotal wall-clock time used by MitoFinder = "+str(time)+"\n")
exit()
elif sup == 1:
print "MitoFinder dit not found any mitochondrial contig with a size lower than "+str(args.MaxContigSize)+" bp."
print ""
logfile.write("MitoFinder dit not found any mitochondrial contig with a size lower than "+str(args.MaxContigSize)+" bp.\n\n")
time=datetime.now() - start_time
print "Total wall-clock time used by MitoFinder = "+str(time)
logfile.write("\nTotal wall-clock time used by MitoFinder = "+str(time)+"\n")
exit()
elif len(collections.OrderedDict(sorted_y)) == 1:
print ''
print 'MitoFinder found a single mitochondrial contig'
print 'Checking resulting contig for circularization...'
logfile.write('\nMitoFinder found a single mitochondrial contig\n'+'Checking resulting contig for circularization...\n')
elif len(collections.OrderedDict(sorted_y)) > 1:
print ''
print 'MitoFinder found '+str(len(collections.OrderedDict(sorted_y)))+' contigs matching provided mitochondrial reference(s)'
if args.maxContig == 0:
print 'Did not check for circularization'
logfile.write('\nMitoFinder found '+str(len(collections.OrderedDict(sorted_y)))+' contigs matching provided mitochondrial reference(s)'+'\nDid not check for circularization\n')
if args.maxContig != 0 and len(collections.OrderedDict(sorted_y)) > args.maxContig:
if args.maxContig == 1:
print "As requested, only the first contig (best match) will be analysed"
print 'Checking resulting contig for circularization...'
logfile.write("As requested, only the first contig (best match) will be analysed"+'\nChecking resulting contig for circularization...\n')
else:
print "As requested, only the "+str(args.maxContig)+" first contigs (sorted by hit score) will be analysed"
print 'Did not check for circularization'
logfile.write("As requested, only the "+str(args.maxContig)+" first contigs (sorted by hit score) will be analysed"+'\nDid not check for circularization\n')
fl=0
ID_dico={}
for k, v in sorted_dico_score.items():
fl+=1
if args.maxContig == 0 or fl <= args.maxContig:
ID_dico[k]=fl
else:
fl-=1
break
dico_final_direction={}
for key, values in dico_direction.items():
if ";" in values:
plus=values.count("+")
minus=values.count("-")
if plus > minus:
dico_final_direction[key]="+"
else:
dico_final_direction[key]="-"
else:
dico_final_direction[key]=values
if fl == 1:
fout=open(pathtowork+"/"+args.processName+'_contig.fasta','w')
for r in SeqIO.parse(pathtowork+"/"+link_file,"fasta"):
if ID_dico.has_key(r.id):
SeqIO.write(r, fout, "fasta")
fout.close()
pathOfResult = pathtowork+"/"+args.processName+'_contig.fasta'
command = module_dir+"/circularizationCheck.py " + pathOfResult + " " + str(args.circularSize) + " " + str(args.circularOffSet)
args1 = shlex.split(command)
fourthStep = Popen(args1, stdout=subprocess.PIPE, stderr=open(os.devnull, 'wb')).communicate()[0]
fourthStep = fourthStep.rstrip().replace(" ","").replace("(","").replace(")","").split(",")
#circularizationcheck will return a tuple with (True, start, end)
print ''
logfile.write('\n')
resultFile = args.processName + '.fasta'
if fourthStep[0] == "True":
print 'Evidences of circularization were found!'
print 'Sequence is going to be trimmed according to circularization position. \n'
print ''
logfile.write('Evidences of circularization were found!\n'+'Sequence is going to be trimmed according to circularization position. \n\n')
with open(resultFile, "w") as outputResult: #create draft file to be checked and annotated
finalResults = SeqIO.read(open(pathOfResult, 'rU'), "fasta", generic_dna)
finalResults.seq = finalResults.seq[int(fourthStep[2]):].upper()
count = SeqIO.write(finalResults, outputResult, "fasta") #trims according to circularization position
else:
print 'Evidences of circularization could not be found, but everyother step was successful'
print ''
logfile.write('Evidences of circularization could not be found, but everyother step was successful\n\n')
with open(resultFile, "w") as outputResult: #create draft file to be checked and annotated
finalResults = SeqIO.read(open(pathOfResult, 'rU'), "fasta", generic_dna)
finalResults.seq = finalResults.seq.upper()
count = SeqIO.write(finalResults, outputResult, "fasta") #no need to trim, since circularization wasn't found
pathOfFinalResults = pathtowork + "/" + args.processName + "_MitoFinder" + assembler + "_" + tRNA + '_Final_Results/'
if not os.path.exists(pathOfFinalResults):
os.makedirs(pathOfFinalResults)
#creating some stat file:
print "\n"
print "Creating summary statistics for the mtDNA contig"
logfile.write("\n\n"+"Creating summary statistics for the mtDNA contig\n")