-
Notifications
You must be signed in to change notification settings - Fork 2
/
BYO_transcriptome.py
2442 lines (2078 loc) · 118 KB
/
BYO_transcriptome.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
# Author: Chris Jackson 2020
"""
Script to add sequences to the gene references in a nucleotide bait-capture target file, using a user-provided
set of transcriptomes.
########################################################################################################################
Additional information:
NOTE:
1) Your target genes should be grouped and differentiated by a suffix in the fasta header,
consisting of a dash followed by an ID unique to each gene, e.g.:
>AJFN-4471
>Ambtr-4471
>Ambtr-4527
>Arath-4691
>BHYC-4691
etc...
2) Your transcriptomes should be named with a unique identifier; this can optionally be followed by a dash and
additional text,
e.g.:
AVJK.fa.gz
PPPZ.fa.gz
etc...
or
AVJK-SOAPdenovo-Trans-assembly.fa.gz
PPPZ-SOAPdenovo-Trans-assembly.fa.gz
etc...
3) In the summary report, the sum of new sequences added might differ slightly from the difference between the
total number of sequences in the original vs new target files, if the transcriptomes searched already have sequences
present in the target file provided.
4) If you are providing your own target taxon names for use in transcriptome hit trimming and frameshift correction
(using the -trim_to_refs <taxon_name> flag), you need to provide each taxon name separately e.g.:
-trim_to_refs species1_name -trim_to_refs species2_name
########################################################################################################################
"""
import sys
try:
import Bio
except ImportError:
sys.exit(f"Required Python package 'Bio' not found. Is it installed for the Python used to run this script?")
try:
import numpy
except ImportError:
sys.exit(f"Required Python package 'numpy' not found. Is it installed for the Python used to run this script?")
import logging
import datetime
import sys
import argparse
import os
from Bio.Align.Applications import MafftCommandline
import subprocess
import re
import shutil
import textwrap
import itertools
from concurrent.futures.process import ProcessPoolExecutor
from concurrent.futures import wait
from Bio import SeqIO, AlignIO, SearchIO
from Bio.Seq import Seq, translate
from Bio.SeqRecord import SeqRecord
from Bio.Align import MultipleSeqAlignment
from Bio.Phylo.TreeConstruction import DistanceCalculator
from collections import defaultdict, OrderedDict
import glob
import gzip
import bz2
import zipfile
import numpy as np
from operator import itemgetter
from multiprocessing import Manager
import pkg_resources
biopython_version = pkg_resources.get_distribution('biopython').version
biopython_version = [int(value) for value in re.split('[.]', biopython_version)]
if biopython_version[0:2] >= [1, 78]:
from Bio.Align import substitution_matrices
from Bio.Align.substitution_matrices import Array
########################################################################################################################
########################################################################################################################
# Configure logger:
def setup_logger(name, log_file, console_level=logging.INFO, file_level=logging.DEBUG,
logger_object_level=logging.DEBUG):
"""
Function to create a logger instance.
By default, logs level DEBUG and above to file.
By default, logs level INFO and above to stderr and file.
:param str name: name for the logger instance
:param str log_file: filename for log file
:param str console_level: logger level for logging to console
:param str file_level: logger level for logging to file
:param str logger_object_level: logger level for logger object
:return: logging.Logger: logger object
"""
# Get date and time string for log filename:
date_and_time = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
# Log to file:
file_handler = logging.FileHandler(f'{log_file}_{date_and_time}.log', mode='w')
file_handler.setLevel(file_level)
file_format = logging.Formatter('%(asctime)s - %(filename)s - %(name)s - %(funcName)s - %(levelname)s - %('
'message)s')
file_handler.setFormatter(file_format)
# Log to Terminal (stderr):
console_handler = logging.StreamHandler(sys.stderr)
console_handler.setLevel(console_level)
console_format = logging.Formatter('%(message)s')
console_handler.setFormatter(console_format)
# Setup logger:
logger_object = logging.getLogger(name)
logger_object.setLevel(logger_object_level) # Default level is 'WARNING'
# Add handlers to the logger
logger_object.addHandler(console_handler)
logger_object.addHandler(file_handler)
return logger_object
logger = setup_logger(__name__, 'BYO_transcriptomes')
########################################################################################################################
########################################################################################################################
# Define functions:
def createfolder(directory):
"""
Attempts to create a directory with the name provided if it doesn't exist, and provides an error message on
failure.
"""
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
logger.info(f'Error: Creating directory: {directory}')
def file_exists_and_not_empty(file_name):
"""
Checks if file exists and is not empty by confirming that its size is not 0 bytes.
"""
return os.path.isfile(file_name) and not os.path.getsize(file_name) == 0
def unzip(file):
"""
Unzips a .zip file unless unzipped file already exists.
"""
expected_unzipped_file = re.sub('.zip', '', file)
directory_to_unzip = os.path.dirname((file))
if not file_exists_and_not_empty(expected_unzipped_file):
with zipfile.ZipFile(file) as infile:
infile.extractall(directory_to_unzip)
os.remove(file)
def gunzip(file):
"""
Unzips a .gz file unless unzipped file already exists.
"""
expected_unzipped_file = re.sub('.gz', '', file)
if not file_exists_and_not_empty(expected_unzipped_file):
with open(expected_unzipped_file, 'w') as outfile:
with gzip.open(file, 'rt') as infile:
outfile.write(infile.read())
os.remove(file)
def decompress_bz2(file):
"""
Unzips a .bz2 file unless unzipped file already exists.
"""
expected_unzipped_file = re.sub('.bz2', '', file)
if not file_exists_and_not_empty(expected_unzipped_file):
with open(expected_unzipped_file, 'wb') as outfile:
with bz2.BZ2File(file, 'rb') as infile:
shutil.copyfileobj(infile, outfile)
os.remove(file)
def concatenate_small(outfile, *args):
"""
Takes an output filename and one or more files as parameters; concatenates files. Note that this will append if
the output file already exists.
e.g. concatenate_small('test.fastq', 'IDX01_S1_L001_R1_001.fastq', 'IDX01_S1_L001_R2_001.fastq').
"""
with open(outfile, 'a+') as outfile:
for filename in args:
with open(filename, 'r') as infile:
outfile.write(infile.read())
def pad_seq(sequence):
"""
Pads a sequence Seq object to a multiple of 3 with 'N'.
"""
remainder = len(sequence) % 3
return sequence if remainder == 0 else sequence + Seq('N' * (3 - remainder))
def done_callback(future_returned):
"""
Callback function for ProcessPoolExecutor futures; gets called when a future is cancelled or 'done'.
"""
if future_returned.cancelled():
logger.info(f'{future_returned}: cancelled')
return
elif future_returned.done():
error = future_returned.exception()
if error:
logger.info(f'\n{future_returned}: error returned: {error}')
return
else:
result = future_returned.result()
return result
def check_dependencies(target_file,
transcriptomes_folder,
python_threads,
external_program_threads,
length_percentage,
hmmsearch_evalue,
refs_for_manual_trimming,
no_n,
discard_short):
"""
Checks Python version, successful import of third party Python modules, the presence of external executables, and
HMMER, Exonerate and MAFFT versions. Prints and logs the run parameters.
"""
# Check python version
if sys.version_info[0:2] < (3, 7):
sys.exit(
f'Must be using Python 3.7 or higher. You are using version {sys.version_info[0]}.{sys.version_info[1]}. '
f'You could try running the script in a conda environment with version 3.7 installed...')
# Check external executables
executables = ['hmmbuild',
'hmmsearch',
'mafft',
'exonerate',
'TransDecoder.LongOrfs',
'TransDecoder.Predict']
logger.info('')
for executable in executables:
if not shutil.which(executable):
sys.exit(f"Required executable '{executable}' not found. Is it installed and in your PATH?")
else:
logger.info(f"Found required executable: {executable:<25}{shutil.which(executable):<30}")
logger.info('')
# Check HMMer version is at least 3.2.1
hmmmer_help = subprocess.run(['hmmsearch', '-h'], capture_output=True)
version = re.search(r'\bHMMER [0-9][.][0-9].[0-9]\b|\bHMMER [0-9][.][0-9]\b', str(hmmmer_help)).group(0)
if not version:
logger.info(f"Can't determine HMMer version. Please make sure you are using at least v3.2.1!\n")
elif [int(integer) for integer in re.split(r'[.]| ', version)[1:]] < [3, 2, 1]:
sys.exit(f'Please use at least HMMer version 3.2.1. You are using {version}')
else:
logger.info(f"You're using HMMer version '{version}', continuing...")
# Check Exonerate version is at least 2.4.0
exonerate_help = subprocess.run(['exonerate', '-h'], capture_output=True)
version = re.search(r'\bexonerate version [0-9][.][0-9].[0-9]\b', str(exonerate_help)).group(0)
if not version:
logger.info(f"Can't determine Exonerate version. Please make sure you are using at least v2.4.0!\n")
elif [int(integer) for integer in re.split(r'[.]| ', version)[2:]] < [2, 4, 0]:
sys.exit(f'Please use at least Exonerate version 2.4.0. You are using {version}')
else:
logger.info(f"You're using Exonerate version '{version}', continuing...")
# Check mafft version is at least 7.407
mafft_version = subprocess.run(['mafft', '--version'], capture_output=True)
version = re.search(r'\bv[0-9][.][0-9][0-9][0-9]\b', str(mafft_version)).group(0)
if not version:
logger.info(f"Can't determine mafft version. Please make sure you are using at least v7.407!\n")
elif [int(integer) for integer in re.split(r'[v.]| ', version)[1:]] < [7, 407]:
sys.exit(f'Please use at least mafft version 7.450. You are using {version}')
else:
logger.info(f"You're using mafft version '{version}', continuing...\n")
# Check python modules
python_modules = ['Bio', 'numpy']
for module in python_modules:
if module in sys.modules:
logger.info(f"Imported required python module: {module:8}")
# Check hmmsearch eValue is in scientific notation
if not re.search(r'\b[0-9]+e-[0-9]+\b', hmmsearch_evalue):
sys.exit(f'The eValue for hmmsearch is not in scientific notation. Value used: {hmmsearch_evalue}')
# Check length_percentage value is a float between 0 and 1
if not 0 < float(length_percentage) <= 1.0:
sys.exit(f'The value for length_percentage should be > 0 and <= 1. Value provided'
f': {length_percentage}')
# Print parameters for run
default_refs = ['Ambtr', 'Arath', 'Orysa']
try:
commandline_refs_for_manual_trimming = list(sorted(set(refs_for_manual_trimming)))
except TypeError:
commandline_refs_for_manual_trimming = None
if commandline_refs_for_manual_trimming:
refs_for_manual_trimming = commandline_refs_for_manual_trimming
else:
refs_for_manual_trimming = default_refs
if not discard_short:
logger.info(f'\n{"*" * 28} Running analysis with the following settings: {"*" * 29}\n\n'
f'{"Target file:":<50}{target_file:<50}\n'
f'{"Transcriptomes folder:":<50}{transcriptomes_folder:<50}\n'
f'{"Python multiprocessing pool threads:":<50}{python_threads:<50}\n'
f'{"External program threads:":<50}{external_program_threads:<50}\n'
f'{"Length percentage cut-off for grafting:":<50}{length_percentage:<50}\n'
f'{"eValue for hmmsearch:":<50}{hmmsearch_evalue:<50}\n'
f'{"References for trimming transcriptome hits:":<50}{", ".join(refs_for_manual_trimming):<50}\n'
f'{"Remove all n characters from transcriptome hits:":<50}{str(no_n):<50}\n')
else:
logger.info(f'\n{"*" * 28} Running analysis with the following settings: {"*" * 29}\n\n'
f'{"Target file:":<50}{target_file:<50}\n'
f'{"Transcriptomes folder:":<50}{transcriptomes_folder:<50}\n'
f'{"Python multiprocessing pool threads:":<50}{python_threads:<50}\n'
f'{"External program threads:":<50}{external_program_threads:<50}\n'
f'{"Length percentage cut-off for discarding hits:":<50}{length_percentage:<50}\n'
f'{"eValue for hmmsearch:":<50}{hmmsearch_evalue:<50}\n'
f'{"References for trimming transcriptome hits:":<50}{", ".join(refs_for_manual_trimming):<50}\n'
f'{"Remove all n characters from transcriptome hits:":<50}{str(no_n):<50}\n')
return
def check_files_for_processing(target_fasta_file,
transcriptomes_folder,
refs_for_manual_trimming,
renamed_transcriptome_folder):
"""
Checks the number, type and naming conventions of files and target-file fasta headers. Unzips transcriptome files
if necessary and creates a copy of each with transcripts renamed to 'contig_1-transcriptomeID,
contig_2-transcriptomeID' etc. Checks that a reference sequence (from either the default list: ['Ambtr', 'Arath',
'Orysa'] or as provided by the -trim_to_refs command line option) is available for each gene in the target file.
Checks that each sequence in the target file can be translated without stop codons (or with only a single stop
codon found within the last 10 amino-acids) in one of the forwards frames.
:param target_fasta_file:
:param transcriptomes_folder:
:param refs_for_manual_trimming:
:param str renamed_transcriptome_folder: folder to create for transcriptomes with renamed sequences
:return:
"""
createfolder(renamed_transcriptome_folder)
transcriptomes_folder_base = os.path.basename(transcriptomes_folder)
target_fasta_file_base = os.path.basename(target_fasta_file)
# Check target-file fasta header formatting:
gene_lists = defaultdict(list)
with open(target_fasta_file, 'r') as target_file:
seqs = SeqIO.parse(target_file, 'fasta')
incorrectly_formatted_fasta_headers = []
for seq in seqs:
if not re.match('.+-[^-]+', seq.name):
incorrectly_formatted_fasta_headers.append(seq.name)
gene_id = re.split('-', seq.name)[-1]
gene_lists[gene_id].append(seq)
if incorrectly_formatted_fasta_headers:
sys.exit(f'The target-file provided "{target_fasta_file_base}" contains the following genes with incorrectly '
f'formatted fasta headers: {", ".join(incorrectly_formatted_fasta_headers)}.')
gene_names_in_target_file = [seq.name for gene_seq_list in gene_lists.values() for seq in gene_seq_list]
# Check that seqs in target_fasta_file can be translated in one of the forwards frames:
seqs_with_frameshifts_dict = defaultdict(list)
sequences = list(SeqIO.parse(target_fasta_file, 'fasta'))
for sequence in sequences:
gene_name = sequence.name.split('-')[-1]
num_stop_codons = pad_seq(sequence.seq).translate().count('*')
if num_stop_codons == 0:
logger.debug(f'Translated sequence {sequence.name} does not contain any stop codons, proceeding...')
elif num_stop_codons == 1 and re.search('[*]', str(pad_seq(sequence.seq).translate())[-10:]):
logger.debug(f'Translated sequence {sequence.name} contains a single stop codon in the last 10 codons, '
f'proceeding...')
elif num_stop_codons > 0:
frames_with_stop_codons = 0
for frame_start in [1, 2]:
num_stop_codons = pad_seq(sequence[frame_start:].seq).translate().count('*')
if not num_stop_codons:
logger.debug(f'Translated sequence {sequence.name} does not contain any stop codons when '
f'translated in forwards frame {frame_start + 1}, proceeding...')
break
elif num_stop_codons == 1 and re.search('[*]', str(pad_seq(
sequence[frame_start:].seq).translate())[-10:]):
logger.debug(f'Translated sequence {sequence.name} contains a single stop codon in the last 10 '
f'codons when translated in frame {frame_start + 1}, proceeding')
else:
frames_with_stop_codons += 1
if frames_with_stop_codons == 2: # CJJ i.e. both 2nd and 3rd frames have stop codons in them too.
seqs_with_frameshifts_dict[gene_name].append(sequence.name)
if len(seqs_with_frameshifts_dict) != 0:
logger.info(f'The following target file sequences cannot be translated without stop codons in any forwards '
f'frame, please correct this:')
for key, value in seqs_with_frameshifts_dict.items():
logger.info(f'Gene {key}: {", ".join(value)}')
sys.exit(f'Please check your target file and try again')
# Check if a reference is present for each gene:
try:
refs_for_trimming_and_exonerate = list(sorted(set(refs_for_manual_trimming)))
except TypeError:
refs_for_trimming_and_exonerate = ['Ambtr', 'Arath', 'Orysa']
re_compile_string = '|'.join(refs_for_trimming_and_exonerate)
pattern = re.compile(re_compile_string)
genes_without_refs = []
for gene_name, gene_list in gene_lists.items():
gene_names = [seq.name for seq in gene_list]
if not re.search(pattern, ','.join(gene_names)):
genes_without_refs.append(gene_name)
if not genes_without_refs:
logger.info(f'Target-file fasta headers look good, continuing...')
else:
sys.exit(f"No reference from list {refs_for_trimming_and_exonerate} found for gene(s): "
f"{', '.join(genes_without_refs)}. A reference for each gene is required for alignment trimming and "
f"Exonerate frameshift correction steps!")
# Unzip transcriptome files if necessary
for transcriptome in glob.glob(f'{transcriptomes_folder}/*'):
transcriptome_id = os.path.basename(transcriptome)
filename, file_extension = os.path.splitext(transcriptome)
if file_extension == '.gz':
logger.info(f'Unzipping transcriptome {transcriptome_id}...')
gunzip(transcriptome)
elif file_extension == '.bz2':
logger.info(f'Unzipping transcriptome {transcriptome_id}...')
decompress_bz2(transcriptome)
elif file_extension == '.zip':
logger.info(f'Unzipping transcriptome {transcriptome_id}...')
unzip(transcriptome)
# Rename transcriptome sequences
logger.info(f'Renaming transcriptome sequences...')
transcriptomes_to_process = []
for transcriptome in [fn for fn in glob.glob(f'{transcriptomes_folder}/*') if not fn.endswith('renamed.fasta')]:
transcriptome_id = os.path.basename(transcriptome)
transcriptome_unique_code = re.split('[-.]', transcriptome_id)[0]
filename, file_extension = os.path.splitext(transcriptome_id)
transcriptome_renamed = f'{renamed_transcriptome_folder}/{filename}_renamed.fasta'
if file_exists_and_not_empty(f'{transcriptome_renamed}'):
os.remove(f'{transcriptome_renamed}')
transcriptomes_to_process.append(filename)
renamed_seqs = []
seqs = SeqIO.parse(transcriptome, 'fasta')
contig_num = 1
for seq in seqs:
seq.description = seq.name
seq.name = f'transcript_{contig_num}-{transcriptome_unique_code}'
seq.id = f'transcript_{contig_num}-{transcriptome_unique_code}'
renamed_seqs.append(seq)
contig_num += 1
with open(f'{transcriptome_renamed}', 'w') as renamed:
SeqIO.write(renamed_seqs, renamed, 'fasta')
if not transcriptomes_to_process:
sys.exit(f'The folder provided "{transcriptomes_folder_base}" does not appear to contain any files!')
logger.info(f'\n{"*" * 50}INFO{"*" * 50}\n')
logger.info(f'{"Number of sequences in target file:":<50}{len(gene_names_in_target_file)}')
logger.info(f'{"Number of unique gene ids in target file:":<50}{len(gene_lists)}')
logger.info(f'{"Number of transcriptomes to search:":<50}{len(transcriptomes_to_process)}\n')
logger.info(f'If the numbers above do not match your expectations, please check your file and sequences names.')
logger.info(f'\n{"*" * 104}\n')
return
def split_targets(target_fasta_file,
output_folder):
"""
Takes the target fasta file and splits it into one fasta file per gene (grouping via the uniqueID suffix in
the fasta header e.g.
>AJFN-4471
>Ambtr-4471
...
"""
createfolder(output_folder)
gene_lists = defaultdict(list)
with open(target_fasta_file, 'r') as target_file:
seqs = SeqIO.parse(target_file, 'fasta')
for seq in seqs:
gene_id = re.split('-', seq.name)[-1]
gene_lists[gene_id].append(seq)
for key, value in gene_lists.items():
with open(f'{output_folder}/{key}.fasta', 'w') as outfile:
for sequence in value:
SeqIO.write(sequence, outfile, 'fasta')
def align_targets(fasta_file,
algorithm,
output_folder,
counter,
lock,
num_files_to_process,
threads=2):
"""
Uses mafft to align a fasta file of sequences, using the algorithm and number of threads provided. Returns filename
of the alignment produced.
"""
createfolder(output_folder)
fasta_file_basename = os.path.basename(fasta_file)
expected_alignment_file = f'{output_folder}/{re.sub(".fasta", ".aln.fasta", fasta_file_basename)}'
try:
assert file_exists_and_not_empty(expected_alignment_file)
logger.debug(f'Alignment exists for {fasta_file_basename}, skipping...')
except AssertionError:
mafft_cline = (MafftCommandline(algorithm, thread=threads, input=fasta_file))
stdout, stderr = mafft_cline()
with open(expected_alignment_file, 'w') as alignment_file:
alignment_file.write(stdout)
finally:
with lock:
counter.value += 1
print(f'\rFinished generating alignment for file {fasta_file_basename}, '
f'{counter.value}/{num_files_to_process}', end='')
return os.path.basename(expected_alignment_file)
def align_targets_multiprocessing(target_gene_folder,
alignments_output_folder,
algorithm='linsi',
pool_threads=1,
mafft_threads=2):
"""
Generate alignments via function <align_targets> using multiprocessing.
"""
createfolder(alignments_output_folder)
logger.info('===> Generating target gene alignments to construct HMM profiles...')
target_genes = [file for file in sorted(glob.glob(f'{target_gene_folder}/*.fasta'))]
with ProcessPoolExecutor(max_workers=pool_threads) as pool:
manager = Manager()
lock = manager.Lock()
counter = manager.Value('i', 0)
future_results = [pool.submit(align_targets, fasta_file, algorithm, alignments_output_folder, counter, lock,
num_files_to_process=len(target_genes), threads=mafft_threads)
for fasta_file in target_genes]
for future in future_results:
future.add_done_callback(done_callback)
wait(future_results, return_when="ALL_COMPLETED")
alignment_list = [alignment for alignment in glob.glob(f'{alignments_output_folder}/*.aln.fasta') if
file_exists_and_not_empty(alignment)]
logger.info(f'\n{len(alignment_list)} alignments generated from {len(future_results)} fasta files.\n')
if len(target_genes) != len(alignment_list):
sys.exit(f'Only {len(alignment_list)} alignments were generated from {len(target_genes)} fasta files, check '
f'for errors!')
def create_hmm_profile(alignment,
output_folder,
counter,
lock,
num_files_to_process,
hmmbuild_threads=2):
"""
Create HMM profile from alignment using HMMer. Returns filename of the HMM profile produced.
"""
createfolder(output_folder)
alignment_file_basename = os.path.basename(alignment)
expected_hmm_file = f'{output_folder}/{re.sub(".aln.fasta", ".hmm", alignment_file_basename)}'
try:
assert file_exists_and_not_empty(expected_hmm_file)
logger.debug(f'HMM profile exists for {alignment_file_basename}, skipping...')
except AssertionError:
subprocess.run(['hmmbuild', '-o', '/dev/null', '--symfrac', '0.0', '--cpu', str(hmmbuild_threads), '--dna',
expected_hmm_file, alignment], check=True)
finally:
with lock:
counter.value += 1
print(f'\rFinished generating HMM profile for alignment {alignment_file_basename}, '
f'{counter.value}/{num_files_to_process}', end='')
return alignment_file_basename
def create_hmm_profile_multiprocessing(alignments_folder,
hmm_output_folder,
pool_threads=1,
hmmbuild_threads=2):
"""
Generate HMM profiles via function <create_hmm_profile> using multiprocessing.
"""
createfolder(hmm_output_folder)
logger.info('===> Generating hmm profiles from gene alignments...')
alignments = [file for file in sorted(glob.glob(f'{alignments_folder}/*.fasta'))]
with ProcessPoolExecutor(max_workers=pool_threads) as pool:
manager = Manager()
lock = manager.Lock()
counter = manager.Value('i', 0)
future_results = [pool.submit(create_hmm_profile, alignment, hmm_output_folder, counter, lock,
num_files_to_process=len(alignments), hmmbuild_threads=hmmbuild_threads)
for alignment in alignments]
for future in future_results:
future.add_done_callback(done_callback)
wait(future_results, return_when="ALL_COMPLETED")
hmm_list = [hmm for hmm in glob.glob(f'{hmm_output_folder}/*.hmm') if file_exists_and_not_empty(hmm)]
logger.info(f'\n{len(hmm_list)} HMM profiles generated from {len(future_results)} alignment files.\n')
if len(alignments) != len(hmm_list):
sys.exit(f'Only {len(hmm_list)} hmm profiles were generated from {len(alignments)} alignments, check '
f'for errors!')
def hmm_vs_transcriptome(hmm_profile,
transcriptomes_folder,
hits_output_folder,
hmm_logs_output_folder,
num_hits_to_recover,
counter,
lock,
num_files_to_process,
hmmsearch_threads=1,
hmmsearch_evalue='1e-50'):
"""
Performs HMM searches against transcriptome fasta files using the provided HMM profile, extracts hits from
transcriptome and writes them to a fasta file.
"""
hmm_profile_basename = os.path.basename(hmm_profile)
gene_name = hmm_profile_basename.split('.')[0]
logger.debug(f'SEARCH: searching with profile {hmm_profile_basename}')
createfolder(f'{hits_output_folder}/{gene_name}')
# If a HMM hit file doesn't already exist, search each transcriptome with the HMM profile
for transcriptome in sorted(glob.glob(f'{transcriptomes_folder}/*renamed.fasta'),
key=lambda a: re.split('/', a)[-1]):
transcriptome_id = os.path.basename(transcriptome)
fasta_hit_file = f'{hits_output_folder}/{gene_name}/{transcriptome_id}_{gene_name}_HMM_hits.fasta'
seqs_to_recover = []
if file_exists_and_not_empty(fasta_hit_file):
logger.debug(f'A fasta file of HMM hits for gene {gene_name} vs transcriptome {transcriptome_id} already '
f'exists, skipping...')
continue
logger.debug(f'SEARCH: searching transcriptome {transcriptome_id} with profile {hmm_profile_basename}')
log_file = f'{hmm_logs_output_folder}/{hmm_profile_basename}_{transcriptome_id}.log'
human_readable_log_file = f'{hmm_logs_output_folder}/' \
f'{hmm_profile_basename}_{transcriptome_id}.human_readable.log'
try:
result = subprocess.run(['nhmmer', '--cpu', str(hmmsearch_threads), '--tblout', log_file, '-E',
str(hmmsearch_evalue), '-o', human_readable_log_file, hmm_profile, transcriptome],
universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
check=True)
logger.debug(f'nhmmer check_returncode() is: {result.check_returncode()}')
logger.debug(f'nhmmer stdout is: {result.stdout}')
logger.debug(f'nhmmer stderr is: {result.stderr}')
except subprocess.CalledProcessError as exc:
logger.error(f'nhmmer FAILED. Output is: {exc}')
logger.error(f'nhmmer stdout is: {exc.stdout}')
logger.error(f'nhmmer stderr is: {exc.stderr}')
raise ValueError('There was an issue running nhmmer. Check input files!')
# Read in log file and recover hit name(s), and strand:
all_transcript_hits = []
with open(log_file, 'r') as hmm_results:
results = hmm_results.readlines()
for line in results:
if not line.startswith('#'):
transcript_name, _, _, _, _, _, ali_from, ali_to, _, _, _, strand, _, _, _, _ = line.split()
all_transcript_hits.append([transcript_name, ali_from, ali_to, strand])
if len(all_transcript_hits) != 0:
logger.debug(f'*** Transcriptome {transcriptome_id} contains {len(all_transcript_hits)} hits for '
f'{hmm_profile_basename} ***')
for hit in all_transcript_hits[0:num_hits_to_recover]:
seqs_to_recover.append(hit)
else:
logger.debug(f'No hits for {gene_name} from transcriptome {transcriptome_id}...')
pass
# Parse transcriptome fasta file and recover hit sequences
seq2strand_dict = dict()
for item in seqs_to_recover:
seq2strand_dict[item[0]] = item[3]
with open(transcriptome) as transcriptome_fasta:
seq_records_to_write = []
seqs = SeqIO.parse(transcriptome_fasta, 'fasta')
for seq in seqs:
if seq.name in seq2strand_dict:
strand = seq2strand_dict[seq.name]
if strand == '-':
seq.seq = seq.reverse_complement().seq
seq_records_to_write.append(seq)
# Write the hits sequences to a fasta file
with open(fasta_hit_file, 'w') as fasta_output:
for seq_record in seq_records_to_write:
SeqIO.write(seq_record, fasta_output, 'fasta')
with lock:
counter.value += 1
print(f'\rFinished searching transcriptomes with {hmm_profile_basename}, '
f'{counter.value}/{num_files_to_process}', end='')
return hmm_profile_basename
def hmm_vs_transcriptome_multiprocessing(hmmprofile_folder,
transcriptomes_folder,
hits_output_folder,
hmm_logs_output_folder,
num_hits_to_recover,
pool_threads=1,
hmmsearch_threads=1,
hmmsearch_evalue='1e-50'):
"""
Run HMM searches of transcriptomes via function <hmm_vs_transcriptome> using multiprocessing.
"""
createfolder(hits_output_folder)
createfolder(hmm_logs_output_folder)
logger.info('===> Searching transcriptomes with HMM profiles...')
hmm_profiles = [hmm for hmm in sorted(glob.glob(f'{hmmprofile_folder}/*.hmm'))]
with ProcessPoolExecutor(max_workers=pool_threads) as pool:
manager = Manager()
lock = manager.Lock()
counter = manager.Value('i', 0)
future_results = [pool.submit(hmm_vs_transcriptome, hmm_profile, transcriptomes_folder, hits_output_folder,
hmm_logs_output_folder, num_hits_to_recover, counter, lock,
num_files_to_process=len(hmm_profiles), hmmsearch_threads=hmmsearch_threads,
hmmsearch_evalue=hmmsearch_evalue)
for hmm_profile in hmm_profiles]
for future in future_results:
future.add_done_callback(done_callback)
wait(future_results, return_when="ALL_COMPLETED")
def remove_empty_seqs_aln(alignment_fasta_file):
"""
Removes any empty sequences from an alignment.
"""
seqs_to_keep = []
aln_obj = AlignIO.read(alignment_fasta_file, 'fasta')
for seq in aln_obj:
ungapped_seq_length = len(seq.seq.replace('-', ''))
if not ungapped_seq_length == 0:
seqs_to_keep.append(seq)
else:
logger.debug(f'Length of seq {seq.name} in alignment {alignment_fasta_file} is zero - HMM hit could not '
f'be aligned! Discarding...')
alignment_empty_seqs_removed = MultipleSeqAlignment(seqs_to_keep)
AlignIO.write(alignment_empty_seqs_removed, alignment_fasta_file, 'fasta')
def align_extractions_single_reference(single_gene_alignment,
single_gene_alignment_object,
concatenated_hits,
mafft_threads,
single_gene_alignment_with_hits_name):
"""
Processes alignments of transcriptome hits to a target file reference in the case where only a single reference is
present in the target file.
"""
for single_sequence in single_gene_alignment_object:
single_sequence.id = f'_seed_{single_sequence.name}'
single_sequence.description = ''
single_sequence.name = ''
single_ref_sequence = single_sequence
if file_exists_and_not_empty(concatenated_hits):
single_gene_alignment = re.sub('.fasta', '.single_seed.fasta', single_gene_alignment)
seqs_to_align = [single_ref_sequence]
for hit_seq in SeqIO.parse(concatenated_hits, 'fasta'):
seqs_to_align.append(hit_seq)
with open(single_gene_alignment, 'w') as seed_single_file:
SeqIO.write(seqs_to_align, seed_single_file, 'fasta')
mafft_cline = (MafftCommandline(localpair=True, thread=mafft_threads, input=single_gene_alignment,
lop=-5.00, lep=-0.5, lexp=-0.1))
stdout, stderr = mafft_cline()
with open(single_gene_alignment_with_hits_name, 'w') as alignment_file:
alignment_file.write(stdout)
remove_empty_seqs_aln(single_gene_alignment_with_hits_name)
os.remove(single_gene_alignment)
elif not file_exists_and_not_empty(concatenated_hits): # i.e. if there are no transcriptome hits.
with open(single_gene_alignment_with_hits_name, 'w') as alignment_file:
SeqIO.write(single_ref_sequence, alignment_file, 'fasta')
def strip_n(concatenated_hits):
"""
Strips the character N from a fasta file of nucleotide sequences.
"""
concatenated_seqs = SeqIO.parse(concatenated_hits, 'fasta')
stripped_seqs_to_write = []
for seq in concatenated_seqs:
seq.seq = seq.seq.replace('N', '')
stripped_seqs_to_write.append(seq)
with open(concatenated_hits, 'w') as n_stripped_concatenated_hits:
SeqIO.write(stripped_seqs_to_write, n_stripped_concatenated_hits, 'fasta')
def align_extractions(single_gene_alignment,
output_folder,
hit_folder,
concatenated_folder,
seqs_with_ns_folder,
counter,
lock,
num_files_to_process,
mafft_threads=2,
no_n=False):
"""
Takes a single gene alignment (from folder_02) from the target fasta file and aligns the hits extracted from
the transcriptomes (from folder_04) using the mafft 'seed' option, which prefixes sequence fasta headers in the
original alignment with the string '_seed_'. Note that this occurs even if there are no sequences in the
'concatenated hits' file. In cases where the target file only contains a single sequence for a given gene, the
string '_seed_' is manually added as a prefix in the fasta header, and a standard alignment is performed. In the
latter case, if there are no sequences in the 'concatenated hits' file, the prefixed target sequence is written to
to a new file by itself.
"""
single_gene_alignment_object = AlignIO.read(single_gene_alignment, 'fasta')
seqs = [seq for seq in single_gene_alignment_object]
if len(seqs) == 1:
single_reference = True
else:
single_reference = False
single_gene_alignment_name = os.path.basename(single_gene_alignment)
single_gene_alignment_with_hits_name = f'{output_folder}/' \
f'{re.sub(".aln.fasta", ".aln_added.fasta", single_gene_alignment_name)}'
gene_id = (single_gene_alignment_name.replace('.aln.fasta', ''))
seqs_with_ns_folder_gene_folder = f'{seqs_with_ns_folder}/{gene_id}'
# Create a dictionary of transcriptome hit sequences containing Ns, write sequences to file:
concatenated_hits = f'{concatenated_folder}/{gene_id}.concat.fasta' # Write new concatenated hits file
if file_exists_and_not_empty(concatenated_hits):
os.remove(concatenated_hits)
for fasta_file in glob.glob(f'{hit_folder}/{gene_id}/*'):
concatenate_small(concatenated_hits, fasta_file)
seqs_with_n_dict = defaultdict(list) # Create a dictionary of seqs that contain Ns
for seq in SeqIO.parse(concatenated_hits, 'fasta'):
n_count = seq.seq.count('N')
if n_count:
seqs_with_n_dict[gene_id].append(seq)
createfolder(seqs_with_ns_folder_gene_folder)
with open(f'{seqs_with_ns_folder_gene_folder}/{gene_id}_seqs_with_ns.fasta', 'w') as seqs_ns:
SeqIO.write(seqs_with_n_dict[gene_id], seqs_ns, 'fasta')
try:
assert file_exists_and_not_empty(single_gene_alignment_with_hits_name)
logger.debug(f' Alignment exists for {single_gene_alignment_name}, skipping...')
except AssertionError:
if no_n and file_exists_and_not_empty(concatenated_hits): # If requested, strip Ns from transcriptome hits
strip_n(concatenated_hits)
if single_reference: # i.e. if there's only a single target sequence for this gene in the target file.
align_extractions_single_reference(single_gene_alignment, single_gene_alignment_object, concatenated_hits,
mafft_threads, single_gene_alignment_with_hits_name)
elif not single_reference:
mafft_cline = (MafftCommandline(localpair=True, thread=mafft_threads, input=concatenated_hits, lop=-5.00,
lep=-0.5, lexp=-0.1, seed=single_gene_alignment))
stdout, stderr = mafft_cline()
with open(single_gene_alignment_with_hits_name, 'w') as alignment_file:
alignment_file.write(stdout)
remove_empty_seqs_aln(single_gene_alignment_with_hits_name)
finally:
with lock:
counter.value += 1
print(f'\rFinished aligning transcriptome hits for {single_gene_alignment_name}, '
f'{counter.value}/{num_files_to_process}', end='')
if seqs_with_n_dict:
return single_gene_alignment_name, seqs_with_n_dict
else:
return single_gene_alignment_name
def align_extractions_multiprocessing(alignments_folder,
output_folder,
hit_folder,
seqs_with_ns_folder,
concatenated_folder,
mafft_threads=2,
pool_threads=1,
no_n=False):
"""
Generate alignments via function <align_extractions> using multiprocessing.
"""
createfolder(output_folder)
createfolder(concatenated_folder)
logger.info('\n\n===> Adding transcriptome hits to gene alignments...')
alignments = [file for file in sorted(glob.glob(f'{alignments_folder}/*aln.fasta'))]
with ProcessPoolExecutor(max_workers=pool_threads) as pool:
manager = Manager()
lock = manager.Lock()
counter = manager.Value('i', 0)
future_results = [pool.submit(align_extractions, alignment, output_folder, hit_folder, concatenated_folder,
seqs_with_ns_folder, counter, lock, num_files_to_process=len(alignments),
mafft_threads=mafft_threads, no_n=no_n) for
alignment in alignments]
for future in future_results:
future.add_done_callback(done_callback)
wait(future_results, return_when="ALL_COMPLETED")
seqs_with_ns = []
for future in future_results:
try:
single_gene_alignment_name, seqs_with_n_dict = future.result()
seqs_with_ns.append(seqs_with_n_dict)
except ValueError:
single_gene_alignment_name = future.result()
alignment_list = [alignments for alignment in glob.glob(f'{output_folder}/*.aln_added.fasta') if
file_exists_and_not_empty(alignment)]