-
Notifications
You must be signed in to change notification settings - Fork 1
/
BUSCO.py
executable file
·3015 lines (2660 loc) · 129 KB
/
BUSCO.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
"""
.. module:: BUSCO
:synopsis: BUSCO - Benchmarking Universal Single-Copy Orthologs.
.. moduleauthor:: Felipe A. Simao <felipe.simao@unige.ch>
.. moduleauthor:: Robert M. Waterhouse <robert.waterhouse@unige.ch>
.. moduleauthor:: Mathieu Seppey <mathieu.seppey@unige.ch>
.. versionadded:: 1.0
.. versionchanged:: 2.0
BUSCO - Benchmarking Universal Single-Copy Orthologs.
To get help, ``python BUSCO.py -h``. See also the user guide.
Visit our website `<http://busco.ezlab.org/>`_
Copyright (C) 2016 E. Zdobnov lab
BUSCO is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>
BUSCO is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
"""
import os
import sys
import subprocess
import argparse
from argparse import RawTextHelpFormatter
import time
import threading
import heapq
import logging
import copy
import traceback
import random
from abc import ABCMeta, abstractmethod
from collections import deque
try:
import queue as Queue
except ImportError:
import Queue # Python 2
class BUSCOLogger(logging.getLoggerClass()):
"""
This class customizes the _logger class
"""
def __init__(self, name):
"""
:param name: the name of the BUSCOLogger instance to be created
:type name: str
"""
super(BUSCOLogger, self).__init__(name)
self.setLevel(logging.INFO)
self._has_warning = False
self._formatter = logging.Formatter('%(levelname)s\t%(message)s')
self._thread_formatter = logging.Formatter('%(levelname)s:%(threadName)s\t%(message)s')
self._formatter_blank_line = logging.Formatter('')
self._out_hdlr = logging.StreamHandler(sys.stdout)
self._out_hdlr.setFormatter(self._formatter)
self._out_hdlr_blank_line = logging.StreamHandler(sys.stdout)
self._out_hdlr_blank_line.setFormatter(self._formatter_blank_line)
self.addHandler(self._out_hdlr)
def add_blank_line(self):
"""
This function add a blank line in the logs
"""
self.removeHandler(self._out_hdlr)
self.addHandler(self._out_hdlr_blank_line)
self.info('')
self.removeHandler(self._out_hdlr_blank_line)
self.addHandler(self._out_hdlr)
def add_thread_info(self):
"""
This function appends the thread name to the logs output, e.g. INFO:BUSCO.py:thread_name
"""
self._out_hdlr.setFormatter(self._thread_formatter)
def remove_thread_info(self):
"""
This function disables the thread name in the logs output, e.g. INFO:BUSCO.py
"""
self._out_hdlr.setFormatter(self._formatter)
def warn(self, msg, *args, **kwargs):
"""
This function overrides the _logger class warn
:param msg: the message to log
:type msg: str
"""
self.warning(msg, *args, **kwargs)
def warning(self, msg, *args, **kwargs):
"""
This function overrides the _logger class warning
:param msg: the message to log
:type msg: str
"""
self._has_warning = True
super(BUSCOLogger, self).warning(msg, *args, **kwargs)
def has_warning(self):
"""
:return: whether the _logger did log warnings
:rtype: book
"""
return self._has_warning
def info_external_tool(self, tool, msg, *args, **kwargs):
"""
This function logs an info line mentioning this is an external tool
:param tool: the name of the tool
:type tool: str
:param msg: the message
:type msg: str
:return:
"""
if msg != '': # do not log blank lines
self.info('[%s]\t%s' % (tool, msg), *args, **kwargs)
class Analysis(object):
"""
This class is the parent of all type of analysis that can be done by BUSCO. It has to be extended by a subclass \
to represent an actual analysis
"""
class _AugustusThreads(threading.Thread):
"""
This class extends ``threading.Thread`` to run Augustus in a multi-threaded manner.
.. seealso:: Analysis._augustus(), Analysis._augustus_rerun(), Analysis._process_augustus_tasks()
"""
CLASS_ABREV = 'augustus'
def __init__(self, thread_id, name, analysis):
"""
:param thread_id: an int id for the thread
:type thread_id: int
:param name: a name for the thread
:type name: str
:param analysis: the Analysis object that is bound to this thread
:type analysis: Analysis
"""
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.analysis = analysis
def run(self):
"""
This function defines what is run by within the thread
"""
self.analysis._process_augustus_tasks()
class _HmmerThreads(threading.Thread):
"""
This class extends ``threading.Thread`` to run hmmersearch in a multi-threaded manner.
.. seealso:: Analysis._hmmer(), Analysis._augustus_rerun(), Analysis._process_hmmer_tasks()
"""
CLASS_ABREV = 'hmmer'
def __init__(self, thread_id, name, analysis):
"""
:param thread_id: an int id for the thread
:type thread_id: int
:param name: a name for the thread
:type name: str
:param analysis: the Analysis object that is bound to this thread
:type analysis: Analysis
"""
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.analysis = analysis
def run(self):
"""
This function defines what is run by within the thread
"""
self.analysis._process_hmmer_tasks()
class _Gff2gbSmallDNAThreads(threading.Thread):
"""
This class extends ``threading.Thread`` to run the gff2gbSmallDNA.pl script in a multi-threaded manner.
.. seealso:: Analysis._process_gff2gbsmalldna_tasks()
"""
CLASS_ABREV = 'gff2gbsmalldna'
def __init__(self, thread_id, name, analysis):
"""
:param thread_id: an int id for the thread
:type thread_id: int
:param name: a name for the thread
:type name: str
:param analysis: the Analysis object that is bound to this thread
:type analysis: Analysis
"""
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.analysis = analysis
def run(self):
"""
This function defines what is run by within the thread
"""
self.analysis._process_gff2gbsmalldna_tasks()
# declare a metaclass ABCMeta, which means that this class is abstract
__metaclass__ = ABCMeta
# Default params
EVALUE_DEFAULT = 1e-3
MAX_FLANK = 20000
REGION_LIMIT_DEFAULT = 3
CPUS_DEFAULT = 1
TMP_DEFAULT = './tmp'
SPECIES_DEFAULT = 'fly'
# Genetic code for translating nucleotides
CODONS = {'TTT': 'F', 'TTC': 'F', 'TTY': 'F',
'TTA': 'L', 'TTG': 'L', 'CTT': 'L', 'CTC': 'L', 'CTA': 'L', 'CTG': 'L', 'CTN': 'L',
'YTN': 'L', 'TTR': 'L',
'ATT': 'I', 'ATC': 'I', 'ATA': 'I', 'ATH': 'I',
'ATG': 'M',
'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V', 'GTN': 'V',
'TCT': 'S', 'TCC': 'S', 'TCA': 'S', 'TCG': 'S', 'TCN': 'S',
'AGT': 'S', 'AGC': 'S', 'WSN': 'S', 'AGY': 'S',
'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P', 'CCN': 'P',
'ACT': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T', 'ACN': 'T',
'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A', 'GCN': 'A',
'TAT': 'Y', 'TAC': 'Y', 'TAY': 'Y',
'TAA': 'X', 'TAG': 'X', 'TGA': 'X', 'TRR': 'X', 'TAR': 'X', 'NNN': 'X',
'CAT': 'H', 'CAC': 'H', 'CAY': 'H',
'CAA': 'Q', 'CAG': 'Q', 'CAR': 'Q',
'AAT': 'N', 'AAC': 'N', 'AAY': 'N',
'AAA': 'K', 'AAG': 'K', 'AAR': 'K',
'GAT': 'D', 'GAC': 'D', 'GAY': 'D',
'GAA': 'E', 'GAG': 'E', 'GAR': 'E',
'TGT': 'C', 'TGC': 'C', 'TGY': 'C',
'TGG': 'W',
'CGT': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'MGN': 'R', 'CGN': 'R', 'AGR': 'R',
'AGA': 'R', 'AGG': 'R',
'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G', 'GGN': 'G'}
# Complementary nucleotides
COMP = {'A': 'T', 'T': 'A', 'U': 'A',
'C': 'G', 'G': 'C',
'B': 'V', 'V': 'B',
'D': 'H', 'H': 'D',
'K': 'M', 'M': 'K',
'S': 'S', 'W': 'W',
'R': 'Y', 'Y': 'R',
'X': 'X', 'N': 'N'}
@staticmethod
def cmd_exists(cmd):
"""
Check if command exists and is accessible from the command-line
:param cmd: a bash command
:type cmd: str
:return: True if the command can be run, False if it is not the case
:rtype: bool
"""
return subprocess.call('type %s' % cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
@staticmethod
def p_open(cmd, name, shell=False):
"""
This function call subprocess.Popen for the provided command and log the results with the provided name
:param cmd: the command to execute
:type cmd: list
:param name: the name to use in the log
:type name: str
:param shell: whether to use the shell parameter to Popen. Needed if wildcard charcter used (*?). See on web
:type shell: bool
"""
# note, all augustus related commands do not write to the stdout and stderr and therefore get nothing here
process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=shell)
process_out = process.stderr.readlines() + process.stdout.readlines()
for line in process_out:
_logger.info_external_tool(name, line.decode("utf-8").strip())
@staticmethod
def check_fasta_header(header):
"""
This function checks problematic characters in fasta headers, and warns the user and stops the execution
:param header: a fasta header to check
:type header: str
:raises SystemExit: if a problematic character is found
"""
for char in FORBIDDEN_HEADER_CHARS:
if char in header:
_logger.error('The character \'%s\' is present in the fasta header %s, '
'which will crash BUSCO. '
'Please clean the header of your input file.' % (char, header.strip()))
raise SystemExit
for char in FORBIDDEN_HEADER_CHARS_BEFORE_SPLIT:
if char in header.split()[0]:
_logger.error('The character \'%s\' is present in the fasta header %s, '
'which will crash BUSCO. '
'Please clean the header of your input file.' % (char, header.split()[0].strip()))
raise SystemExit
@staticmethod
def _check_blast():
"""
Check if blast is accessible from command-line (tblastn)
:raises SystemExit: if blast is not accessible
"""
if not Analysis.cmd_exists('tblastn'):
_logger.error('Blast is not accessible from the command-line, please add it to the environment')
raise SystemExit
@staticmethod
def _check_hmmer():
"""
Check if it is accessible from command-line (as 'hmmsearch')
Also check if HMMer is the correct version (3.1+)
:raises SystemExit: if HMMer is not accessible or not the correct version
"""
if not Analysis.cmd_exists('hmmsearch'):
_logger.error('HMMer is not accessible from the command-line, please add it to the environment')
raise SystemExit
else:
try:
hmmer_check = subprocess.check_output('hmmsearch -h', shell=True)
hmmer_check = hmmer_check.decode('utf-8')
hmmer_check = hmmer_check.split('\n')[1].split()[2]
hmmer_check = float(hmmer_check[:3])
except ValueError:
# to avoid a crash with super old version and notify the user, will be useful
hmmer_check = subprocess.check_output('hmmsearch -h', shell=True)
hmmer_check = hmmer_check.decode('utf-8')
hmmer_check = hmmer_check.split('\n')[1].split()[1]
hmmer_check = float(hmmer_check[:3])
except subprocess.CalledProcessError:
_logger.error('HMMer is not accessible from the command-line, please add it to the environment')
raise SystemExit
if hmmer_check >= 3.1:
pass
else:
_logger.error('HMMer version detected is not supported, please use HMMer 3.1+')
raise SystemExit
@staticmethod
def _split_seq_id(seq_id):
"""
This function split the provided seq id into id, start and stop
:param seq_id: the seq id to split
:type seq_id: str
:return: a dict containing the id, the start, the end found in seq_id
:rtype: dict
"""
# -2,-1 instead of 0,1, if ':' in the fasta header, same for [,]
name = seq_id.replace(']', '').split('[')[-1].split(':')[-2]
start = seq_id.replace(']', '').split('[')[-1].split(':')[-1].split('-')[0]
end = seq_id.replace(']', '').split('[')[-1].split(':')[-1].split('-')[1]
return {'id': name, 'start': start, 'end': end}
def check_dataset(self):
"""
Check the dataset integrity, if files and folder are present
:raises SystemExit: if the dataset miss files or folders
"""
# hmm folder
flag = False
for dirpath, dirnames, files in os.walk('%shmms' % self._clade_path):
if files:
flag = True
if not flag:
_logger.error('The dataset you provided lacks hmm profiles in %shmms' % self._clade_path)
raise SystemExit
# note: score and length cutoffs are checked when read, see _load_scores and _load_lengths
def _check_augustus(self):
"""
Check if Augustus is accessible from command-line and properly configured.
:raises SystemExit: if Augustus is not accessible
:raises SystemExit: if Augustus config path is not writable or not set at all
:raises SystemExit: if Augustus config path does not contain the needed species
:raises SystemExit: if additional perl scripts for retraining are not present
"""
if not Analysis.cmd_exists('augustus'):
_logger.error('Augustus is not accessible from the command-line, please add it to the environment')
raise SystemExit
try:
if not os.access(self._augustus_config_path, os.W_OK):
_logger.error('Cannot write to Augustus config path, please make sure you have '
'write permissions to %s' % self._augustus_config_path)
raise SystemExit
except TypeError:
_logger.error('The environment variable AUGUSTUS_CONFIG_PATH is not set')
raise SystemExit
if not os.path.exists(self._augustus_config_path + '/species/%s' % self._target_species):
_logger.error('Impossible to locate the species "%s" in Augustus config path (%sspecies), check '
'that AUGUSTUS_CONFIG_PATH is properly set and contains this species. '
'\n\t\tSee the help if you want to provide an alternative species'
% (self._target_species, self._augustus_config_path))
raise SystemExit
if not Analysis.cmd_exists('gff2gbSmallDNA.pl'):
_logger.error('Impossible to locate the required script gff2gbSmallDNA.pl. Check that you declared '
'the Augustus scripts folder in your $PATH environmental variable')
raise SystemExit
if not Analysis.cmd_exists('new_species.pl'):
_logger.error('Impossible to locate the required script new_species.pl. Check that you declared '
'the Augustus scripts folder in your $PATH environmental variable')
raise SystemExit
if self._long and not Analysis.cmd_exists('optimize_augustus.pl'):
_logger.error('Impossible to locate the required script optimize_augustus.pl. Check that you declared '
'the Augustus scripts folder in your $PATH environmental variable')
raise SystemExit
def _check_nucleotide(self):
"""
This function checks that the provided file is nucleotide
:raises SystemExit: if AA found
"""
aas = set(Analysis.CODONS.values())
nucls = Analysis.COMP.keys()
for nucl in nucls:
try:
aas.remove(nucl)
except KeyError:
pass
file = open(self._sequences)
n = 0
for line in file:
if n > 10:
break
n += 1
if '>' not in line:
for aa in aas:
if aa.upper() in line or aa.lower() in line:
_logger.error('Please provide a nucleotide file as input, it should not contains \'%s or %s\''
% (aa.upper(), aa.lower()))
file.close()
raise SystemExit
file.close()
def _check_protein(self):
"""
This function checks that the provided file is protein
:raises SystemExit: if only ACGTN is found over a reasonable amount of lines
"""
aas = set(Analysis.CODONS.values())
aas.remove('A')
aas.remove('C')
aas.remove('G')
aas.remove('T')
aas.remove('N')
is_aa = False
file = open(self._sequences)
n = 0
for line in file:
if n > 100:
break
n += 1
if '>' not in line:
for aa in aas:
if aa.lower() in line or aa.upper() in line:
is_aa = True
break
file.close()
if not is_aa:
_logger.error('Please provide a protein file as input')
raise SystemExit
def _define_checkpoint(self, nb=None):
"""
This function update the checkpoint file with the provided id or delete it if none is provided
:param nb: the id of the checkpoint
:type nb: int
"""
if nb:
open('%scheckpoint.tmp' % self.mainout, 'w').write('%s.%s.%s' % (nb, self._mode, self._random))
else:
if os.path.exists('%scheckpoint.tmp' % self.mainout):
os.remove('%scheckpoint.tmp' % self.mainout)
def _get_checkpoint(self, reset_random_suffix=False):
"""
This function return the checkpoint if the checkpoint.tmp file exits or None if absent
:param reset_random_suffix: to tell whether to reset the self._random value with the one found the checkpoint
:type reset_random_suffix: bool
:return: the checkpoint name
:rtype: int
"""
if os.path.exists('%scheckpoint.tmp' % self.mainout):
line = open('%scheckpoint.tmp' % self.mainout, 'r').readline()
if reset_random_suffix:
_logger.debug('Resetting random suffix to %s' % self._random)
self._random = line.split('.')[-1]
return int(int(line.split('.')[0]))
else:
return None
def _extract_missing_and_frag_buscos_ancestral(self, ancestral_variants=False):
"""
This function extracts from the file ancestral the sequences that match missing or fragmented buscos
:param ancestral_variants: tell whether to use the ancestral_variants file
:type ancestral_variants: bool
"""
if self._has_variants_file:
_logger.info('Extracting missing and fragmented buscos from the ancestral_variants file...')
else:
_logger.info('Extracting missing and fragmented buscos from the ancestral file...')
if ancestral_variants:
ancestral = open('%sancestral_variants' % self._clade_path, 'r')
output = open('%sblast_output/missing_and_frag_ancestral_variants' % self.mainout, 'w')
else:
ancestral = open('%sancestral' % self._clade_path, 'r')
output = open('%sblast_output/missing_and_frag_ancestral' % self.mainout, 'w')
result = ''
buscos_to_retrieve = self._missing_busco_list + self._fragmented_busco_list
buscos_retrieved = []
add = False
for line in ancestral:
if line.startswith('>'):
if ancestral_variants:
line = '_'.join(line.split("_")[:-1])
# This pattern can support name like EOG00_1234_1
busco_id = line.strip().strip('>')
if busco_id in buscos_to_retrieve:
_logger.debug('Found contig %s' % busco_id)
add = True
buscos_retrieved.append(busco_id)
else:
add = False
if add:
if line.endswith('\n'):
result += line
else:
result += line + '\n'
if len(list(set(buscos_to_retrieve) - set(buscos_retrieved))) > 0:
if self._has_variants_file:
_logger.warning('The busco id(s) %s were not found in the ancestral_variants file' %
list(set(buscos_to_retrieve) - set(buscos_retrieved)))
else:
_logger.warning('The busco id(s) %s were not found in the ancestral file' %
list(set(buscos_to_retrieve) - set(buscos_retrieved)))
output.write(result)
output.close()
ancestral.close()
output.close()
@staticmethod
def _check_overlap(a, b):
"""
This function checks whether two regions overlap
:param a: first region, start and end
:type a: list
:param b: second region, start and end
:type b: list
:return: the number of overlapping positions
:rtype: int
"""
return max(0, min(a[1], b[1]) - max(a[0], b[0]))
@staticmethod
def _define_boundary(a, b):
"""
This function defines the boundary of two overlapping regions
:param a: first region, start and end
:type a: list
:param b: second region, start and end
:type b: list
:return: the boundaries, i.e. start and end
:rtype: collections.deque
"""
temp_start = a[0]
temp_end = a[1]
current_start = b[0]
current_end = b[1]
boundary = None
if temp_start < current_start and temp_end < current_start:
# i.e. entry is fully before
# append left, IF entry is the first one; otherwise put into the proper position
boundary = deque([a, b])
elif temp_start < current_start <= temp_end <= current_end:
# i.e. overlap starts before, but ends inside
boundary = deque([temp_start, current_end])
elif current_start <= temp_start <= current_end < temp_end:
# overlap starts inside, but ends outside
boundary = deque([current_start, temp_end])
elif temp_start > current_end and temp_end > current_end:
# i.e. query is fully after
# append right; otherwise put into the proper position
boundary = deque([b, a])
elif current_start <= temp_start <= temp_end <= current_end:
# i.e. query is fully inside, no further operations needed
boundary = deque(b)
elif temp_start == current_start and temp_end == current_end:
boundary = deque(a)
elif temp_start <= current_start and temp_end >= current_end:
# i.e. query is longer and contains all coordinates
# replace by the query
boundary = deque(a)
return boundary
@staticmethod
def _gargantua(deck):
"""
:param deck:
:type deck: list
:return:
:rtype: int
"""
# todo comment
total = 0
for entry in deck:
total += entry[1] - entry[0]
return total
@staticmethod
def _sixpack(seq):
"""
Gets the sixframe translation for the provided sequence
:param seq: the sequence to be translated
:type seq: str
:return: the six translated sequences
:rtype: list
"""
s1 = seq
s2 = seq[1:]
s3 = seq[2:]
rev = ''
for letter in seq[::-1]:
try:
rev += Analysis.COMP[letter]
except KeyError:
rev += Analysis.COMP['N']
r1 = rev
r2 = rev[1:]
r3 = rev[2:]
transc = []
frames = [s1, s2, s3, r1, r3, r2]
for sequence in frames:
part = ''
new = ''
for letter in sequence:
if len(part) == 3:
try:
new += Analysis.CODONS[part]
except KeyError:
new += 'X'
part = ''
part += letter
else:
part += letter
if len(part) == 3:
try:
new += Analysis.CODONS[part]
except KeyError:
new += 'X'
transc.append(new)
return transc
@staticmethod
def _measuring(nested):
"""
:param nested:
:type nested:
:return:
:rtype:
"""
# todo comment
total_len = 0
if isinstance(nested, str):
return '0'
scaffolds = list(nested.keys())
if len(nested) == 1:
total_len = [0]
for hit in nested[scaffolds[0]]:
total_len[0] += hit[1] - hit[0]
elif len(nested) > 1:
total_len = [0] * len(nested)
for entry in range(0, len(scaffolds)):
for hit in nested[scaffolds[entry]]:
total_len[entry] += hit[1] - hit[0]
return total_len
@staticmethod
def _remove_bad_ratio_genes(original):
"""
This function removes duplicate positive results if the score is above a 0.85 threshold compared to the top
scoring match
:param original: a dict with BUSCO as key, and a dict of matching genes as values
:type original: dict
:return: the filtered dict
:rtype: dict
"""
ratio = 0.85
filtered = copy.deepcopy(original)
for k in original.keys():
max_score = 0
for k2 in original[k]:
if original[k][k2][2] > max_score:
max_score = original[k][k2][2]
for k2 in original[k]:
if original[k][k2][2] < max_score*ratio:
del filtered[k][k2]
if len(filtered[k]) == 0:
del filtered[k]
return filtered
@staticmethod
def _filter_multi_match_genes(original):
"""
This function identifies genes that match the same BUSCO, and keeps the one with the best score only
:param original: a dict with BUSCO as key, and a dict of matching genes as values
:type original: dict
:return: the filtered dict
:rtype: dict
"""
filtered = copy.deepcopy(original)
# reorganize the key/value by gene
gene_dict = {}
for d in original.values():
for key in d.keys():
if key in gene_dict:
gene_dict[key].append(d[key])
else:
gene_dict[key] = [d[key]]
# identify genes belonging to two or more buscos
# keep the best score
to_keep = {}
for key in gene_dict.keys():
if len(gene_dict[key]) > 1:
max_score = 0
busco_to_keep = ""
for busco in gene_dict[key]:
if max_score < busco[2]:
max_score = busco[2]
busco_to_keep = busco[5][0:11]
to_keep[key] = busco_to_keep
# clean the original list
for k in original.keys():
for k2 in original[k].keys():
if k2 in to_keep.keys():
if to_keep[k2] != k:
del filtered[k][k2]
if len(filtered[k]) == 0:
del filtered[k]
return filtered
@abstractmethod
def __init__(self, params):
"""
Initialize an instance, need to be overriden by subclasses
:param params: Values of all parameters that have to be defined
:type params: dict
"""
# todo move child specific variable to its child class, e.g. self._transcriptome_by_scaff
self._random = "_"+str(random.getrandbits(32)) # to have a unique value for temporary file names
self._abrev = params['abrev']
self._tmp = params['tmp']
self._force = params['force']
self._restart = params['restart']
self._sequences = params['sequences']
self._cpus = params['cpus']
self._clade_path = params['clade_path']
self._clade_name = params['clade_name']
self._domain = params['domain']
self._ev_cutoff = params['ev_cutoff']
self._region_limit = params['region_limit']
self._flank = params['flank']
self._long = params['long']
self._target_species = params['target_species']
self._augustus_config_path = params['augustus_config_path']
self._tarzip = params['tarzip']
self._dataset_creation_date = params['dataset_creation_date']
self._dataset_nb_species = params['dataset_nb_species']
self._dataset_nb_buscos = params['dataset_nb_buscos']
self.mainout = None
self._totalbuscos = 0
self._total = 0
self._cutoff_dictionary = {}
self._thread_list = None
self._no_prediction = None
self._exit_flag = None
self._queue_lock = None
self._work_queue = None
self._missing_busco_list = []
self._fragmented_busco_list = []
self._location_dic = {}
self._single_copy_files = None
self._transcriptome_by_scaff = {}
self._mode = None
self._has_variants_file = False
def cleanup(self):
"""
This function cleans temporary files. \
It has to be overriden by subclasses when needed
"""
Analysis.p_open(['rm', '%stemp_%s%s' % (self._tmp, self._abrev, self._random)], 'bash', shell=False)
if self._tarzip:
self._run_tarzip()
def _run_tarzip(self):
"""
This function tarzips results folder
It has to be overriden by subclasses when needed
"""
Analysis.p_open(['tar', '-C', '%s' % self.mainout, '-zcf',
'%shmmer_output.tar.gz' % self.mainout, 'hmmer_output',
'--remove-files'],
'bash', shell=False)
def _get_coordinates(self):
"""
This function gets coordinates for candidate regions from tblastn result file. \
It has to be overriden by subclasses when needed
"""
pass
def _extract_scaffolds(self, missing_and_frag_only=False):
"""
This function extract the scaffold having blast results
:param missing_and_frag_only: to tell which coordinate file to look for, complete or just missing and fragment
:type missing_and_frag_only: bool
"""
_logger.info('Pre-Augustus scaffold extraction...')
if missing_and_frag_only:
coord = open('%s/blast_output/coordinates_%s_missing_and_frag_rerun.tsv' % (self.mainout, self._abrev))
else:
coord = open('%s/blast_output/coordinates_%s.tsv' % (self.mainout, self._abrev))
dic = {}
scaff_list = []
for i in coord:
i = i.strip().split()
if len(i) != 2:
dic[i[0]] = [i[1], i[2], i[3]]
if i[1] not in scaff_list:
scaff_list.append(i[1])
coord.close()
f = open(self._sequences)
check = 0
out = None
for i in f:
if i.startswith('>'):
i = i.split()
i = i[0][1:]
if i in scaff_list:
out = open('%s%s%s%s_.temp' % (self._tmp, i, self._abrev, self._random), 'w')
out.write('>%s\n' % i)
check = 1
else:
check = 0
elif check == 1:
out.write(i)
f.close()
if out:
out.close()
@abstractmethod
def _hmmer(self):
"""
This function runs hmmsearch. It has to be overriden by subclasses
"""
pass
def _write_output_header(self, out):
"""
This function adds a header to the provided file
:param out: a file to which the header will be added
:type out: file
"""
out.write('# BUSCO version is: %s \n# The lineage dataset is: %s (Creation date: %s,'
' number of species: %s, number of BUSCOs: %s)\n'
% (VERSION, self._clade_name, self._dataset_creation_date, self._dataset_nb_species,
self._dataset_nb_buscos))
out.write('# To reproduce this run: %s\n#\n' % _rerun_cmd)
@staticmethod
def _write_full_table_header(out):
"""
This function adds a header line to the full table file
:param out: a full table file
:type out: file
"""
out.write('# Busco id\tStatus\tSequence\tScore\tLength\n')
def _blast(self, missing_and_frag_only=False, ancestral_variants=False):
"""
This function runs tblastn
:param missing_and_frag_only: to tell whether to blast only missing and fragmented buscos
:type missing_and_frag_only: bool
:param ancestral_variants: to tell whether to use the ancestral_variants file
:type ancestral_variants: bool
"""
if ancestral_variants:
ancestral_suffix = '_variants'
else:
ancestral_suffix = ''
if missing_and_frag_only:
self._extract_missing_and_frag_buscos_ancestral(ancestral_variants)
output_suffix = '_missing_and_frag_rerun'
query_file = '%sblast_output/missing_and_frag_ancestral%s' % (self.mainout, ancestral_suffix)
else:
output_suffix = ''
query_file = '%sancestral%s' % (self._clade_path, ancestral_suffix)
if not missing_and_frag_only:
_logger.info('Create blast database...')
Analysis.p_open(['makeblastdb', '-in', self._sequences, '-dbtype', 'nucl', '-out',
'%s%s%s' % (self._tmp, self._abrev, self._random)], 'makeblastdb',
shell=False)
if not os.path.exists('%sblast_output' % self.mainout):
Analysis.p_open(['mkdir', '%sblast_output' % self.mainout], 'bash', shell=False)
_logger.info('Running tblastn, writing output to %sblast_output/tblastn_%s%s.tsv...'
% (self.mainout, self._abrev, output_suffix))
Analysis.p_open(['tblastn', '-evalue', str(self._ev_cutoff), '-num_threads', str(self._cpus),
'-query', query_file,
'-db', '%s%s%s' % (self._tmp, self._abrev, self._random),
'-out', '%sblast_output/tblastn_%s%s.tsv'
% (self.mainout, self._abrev, output_suffix), '-outfmt', '7'], 'tblastn',
shell=False)
# check that blast worked
if not os.path.exists('%sblast_output/tblastn_%s%s.tsv' % (self.mainout, self._abrev, output_suffix)):
_logger.error('tblastn failed !')
raise SystemExit
# check that the file is not truncated
try:
if "processed" not in open('%sblast_output/tblastn_%s%s.tsv' % (self.mainout, self._abrev, output_suffix),
'r').readlines()[-1]:
_logger.warning('tblastn might have ended prematurely (the result file lacks the expected final line), '
'which could produce incomplete results in the next steps !')
except IndexError:
pass # if the tblastn result file is empty, for example in phase 2 if 100% was found in phase 1
def _run_threads(self, command_strings, thread_class, display_percents=True):
"""
This class creates and run threads of the provided type for each provided command
:param command_strings: the list of commands to be run in the threads
:type command_strings: list
:param thread_class: the type of thread class to create
:type thread_class: type Analysis.threads
:param display_percents: to tell whether to display a log for 0% and 100% complete
:type display_percents: bool
"""
self.slate = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
if len(command_strings) < 11:
self.slate = [100, 50] # to avoid false progress display if not enough entries
self._exit_flag = 0
# Create X number of threads
self._thread_list = []
self._total = len(command_strings)
mark = 0
for i in range(int(self._cpus)):
mark += 1
self._thread_list.append("%s-%s-%s" % (thread_class.CLASS_ABREV, self._abrev, str(i + 1)))
if mark >= self._total:
break
self._queue_lock = threading.Lock()
self._work_queue = Queue.Queue(len(command_strings))
threads = []
thread_id = 1
# Generate the new threads
for t_name in self._thread_list:
thread = thread_class(thread_id, t_name, self)
thread.start()
threads.append(thread)
thread_id += 1
if display_percents:
_logger.info('%s =>\t0%% of predictions performed (%i to be done)'
% (time.strftime("%m/%d/%Y %H:%M:%S"), self._total))
# Fill the queue with the commands