forked from anton-shikov/cry_processor
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cry_processor.py
1934 lines (1852 loc) · 105 KB
/
cry_processor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import subprocess
import argparse
from Bio import SeqIO, Entrez
from Bio.Seq import Seq
#from Bio.Alphabet import generic_protein, generic_dna
from Bio.SeqRecord import SeqRecord
from collections import defaultdict
import csv
import time
import os
import os.path
import sys
import re
import logging
import copy
import datetime
class CryProcessor:
def __init__(self,
query_dir,
cry_query,
hmmer_dir,
processing_flag,
hm_threads,
email,
mode,
nucl_type,
annot_flag,
kmer_size,
meta_flag,
forw,
rev,
silent_mode,
force_mode):
#initialize the logger
self.logger = logging.getLogger("cry_processor")
self.logger.setLevel(logging.INFO)
fh = logging.FileHandler("cry_processor.log")
#set the formatter for the logger
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
self.logger.addHandler(fh)
self.logger.info("Initializing...")
self.cry_query = cry_query
self.hmmer_dir = hmmer_dir
self.processing_flag = processing_flag
self.hm_threads = hm_threads
self.query_dir = query_dir
if self.cry_query:
#calculate the number of sequences (only if the fasta file is present)
if 'gfa' not in self.cry_query:
self.init_count = re.sub("b",'',
re.sub("\'",'',
str(subprocess.check_output("grep '>' {} | wc -l".format(self.cry_query),
shell =True).strip())))
self.one_dom_count = 0
self.two_dom_count = 0
self.three_dom_count = 0
self.input_file = self.cry_query.split('/')[len(self.cry_query.split('/'))-1]
self.out_name = '.'.join(self.input_file.split('.')[0:self.input_file.count('.')])
self.email = email
self.mode = mode
self.nucl_type = nucl_type
self.annot_flag = annot_flag
self.kmer_size = kmer_size
self.meta_flag = meta_flag
self.forw = forw
self.rev = rev
self.racer_flag = 0
self.hmmer_result_flag = 0
self.silent_mode = silent_mode
self.force_mode = force_mode
if not self.force_mode:
if os.path.exists(os.path.realpath(self.query_dir)):
self.query_dir = self.query_dir + "_"+ str(datetime.datetime.now()).split('.')[0].replace(' ', '_').replace(':', '_')
#creating output directories
cmd_init = subprocess.call('if [ ! -d {0} ]; \
then mkdir {0}; \
fi; \
if [ ! -d {0}/logs ]; \
then mkdir {0}/logs; \
fi'.format(os.path.realpath(
self.query_dir)),
shell=True)
def run_hmmer(self,query,out_index,model_type,dir_flag,log,hm_threads,query_dir):
"""
Runs hmmsearch on query
Args
=====
query: fasta file for performing search
out_index: postfix for .sto output file
model_type: which hmm-model to use
dir_flag: output directory for search
log: prefix for log-file
hm_threads: number of threads to use
query_dir: directory where query file is located
"""
#if self.hmmer_dir is not specified use hmmsearch from the include directory
if self.hmmer_dir:
#check the output directory structure
cmd_make_dirs = subprocess.call('cd {0}; \
if [ ! -d {1} ]; \
then mkdir {1}; \
fi'.format(os.path.join(
os.path.realpath(
query_dir)),
dir_flag),
shell=True)
#perform hmmsearch
cmd_search = subprocess.call('{0} \
-E 50 --nonull2 --max --incE 250 --domZ 0.1 --cpu {1} \
-A {2} \
{3} \
{4} >> {5}'.format(os.path.join(
os.path.realpath(
self.hmmer_dir),
"binaries",
"hmmsearch"),
hm_threads,
os.path.join(
os.path.realpath(
self.query_dir),
dir_flag,
self.out_name+
out_index),
os.path.join(
os.path.dirname
(__file__),
'data',
'models',
model_type),
os.path.realpath(
query),
os.path.join(
os.path.realpath(
self.query_dir),
"logs",
log+'.log')),
shell=True)
#converting to fasta files
cmd_fasta = subprocess.call('if [ -s {0} ];\
then {2} fasta {0} > {1};\
fi'.format(os.path.join(
os.path.realpath(
self.query_dir),
dir_flag,
self.out_name+
out_index),
os.path.join(
os.path.realpath(
self.query_dir),
dir_flag,
self.out_name+
out_index.replace('sto','fasta')),
os.path.join(os.path.realpath(
self.hmmer_dir),
"binaries","esl-reformat")),
shell=True)
# -E 50 --nonull2 --max --incE 250 --domZ 0.1
else:
cmd_make_dirs = subprocess.call('cd {0}; \
if [ ! -d {1} ]; \
then mkdir {1}; \
fi'.format(os.path.join(
os.path.realpath(
query_dir)),
dir_flag),
shell=True)
cmd_search = subprocess.call('{0} \
-E 50 --nonull2 --max --incE 250 --domZ 0.1 --cpu {1} \
-A {2} \
{3} \
{4} >> {5}'.format(
os.path.join(
os.path.dirname(
__file__),
"include",
"hmmsearch"),
hm_threads,
os.path.join(
os.path.realpath(
self.query_dir),
dir_flag,
self.out_name+
out_index),
os.path.join(
os.path.dirname(
__file__),
'data',
'models',
model_type),
os.path.realpath(
query),
os.path.join(
os.path.realpath(
self.query_dir),
"logs",
log+'.log')),
shell=True)
cmd_fasta = subprocess.call('if [ -s {0} ];\
then {2} fasta {0} > {1};\
fi'.format(os.path.join(
os.path.realpath(
self.query_dir),
dir_flag,
self.out_name+
out_index),
os.path.join(
os.path.realpath(
self.query_dir),
dir_flag,
self.out_name+
out_index.replace('sto','fasta')),
os.path.join(
os.path.dirname(
__file__),
"include",
"esl-reformat")),
shell=True)
def find_cry(self, qiuery):
"""
Launches run_hmmer function on full unprocessed toxins (Complete.hmm model in data/models)
Args
=====
query: fasta file for performing search
"""
if not self.silent_mode:
print('Searching for the unprocessed Cry toxins')
self.logger.info('Searching for the unprocessed Cry toxins')
self.run_hmmer(str(qiuery),
'_full_extracted.sto',
'Complete.hmm',
'full_toxins',
'full_extraction',
self.hm_threads,
self.query_dir)
def find_domains(self, qiuery):
"""
Launches run_hmmer function on full domains of cry-toxins (D1.hmm, D2.hmm and D3.hmm models in data/models)
Args
=====
query: fasta file for performing search
"""
# loop over domain indicies
for i in range(1,4):
if not self.silent_mode:
print('Searching for the {} domain of the Cry toxins'.format(i))
self.logger.info('Searching for the {} domain of the Cry toxins'.format(i))
self.run_hmmer(str(qiuery),
'_D{}_extracted.sto'.format(i),
'D{}.hmm'.format(i),
'domains',
'domains_extraction',
self.hm_threads,
self.query_dir)
self.run_hmmer(str(qiuery),
'_cry31.sto',
'cry31.hmm',
'domains',
'domains_extraction',
self.hm_threads,
self.query_dir)
self.run_hmmer(str(qiuery),
'_cry_58.sto',
'cry_58.hmm',
'domains',
'domains_extraction',
self.hm_threads,
self.query_dir)
self.run_hmmer(str(qiuery),
'_extra.sto',
'extra.hmm',
'domains',
'domains_extraction',
self.hm_threads,
self.query_dir)
self.run_hmmer(str(qiuery),
'_Endotoxin_M.sto',
'Endotoxin_M.hmm',
'domains',
'domains_extraction',
self.hm_threads,
self.query_dir)
self.run_hmmer(str(qiuery),
'_Endotoxin_mid.sto',
'Endotoxin_mid.hmm',
'domains',
'domains_extraction',
self.hm_threads,
self.query_dir)
self.run_hmmer(str(qiuery),
'_long_32_11.sto',
'long_32_11.hmm',
'domains',
'domains_extraction',
self.hm_threads,
self.query_dir)
self.run_hmmer(str(qiuery),
'_extra_3.sto',
'extra_3.hmm',
'domains',
'domains_extraction',
self.hm_threads,
self.query_dir)
D2_check_flag = re.sub("b",'',
re.sub("\'",'',
str(subprocess.check_output("cd {0}; \
if [ ! -s {1} ] && [ ! -s {2} ] && [ ! -s {3} ] && [ ! -s {4} ] && [ ! -s {5} ] && [ ! -s {6} ] && [ ! -s {7} ];\
then echo 'no'; \
fi".format(os.path.join(
os.path.realpath(
self.query_dir),
'domains'),
self.out_name+
'_D2_extracted.fasta',
self.out_name+
'_cry31.fasta',
self.out_name+
'_long_32_11.fasta',
self.out_name+
'_Endotoxin_mid.fasta',
self.out_name+
'_Endotoxin_M.fasta',
self.out_name+
'_extra.fasta',
self.out_name+
'_cry_58.fasta'),
shell =True).strip())))
if D2_check_flag!='no':
mearging_cmd = subprocess.call("cd {0}; ls | grep '*fasta';\
cat $(ls | grep -E '*(_D2_extracted|_cry31|_long_32_11|_Endotoxin_mid|_Endotoxin_M|_extra|_cry_58).fasta') > tmp_2.fasta; \
mv tmp_2.fasta {1}; \
".format(os.path.join(
os.path.realpath(
self.query_dir),
'domains'),
self.out_name+
'_D2_extracted.fasta'),
shell=True)
else:
making_cmd = subprocess.call("cd {0}; touch {1}; \
".format(os.path.join(
os.path.realpath(
self.query_dir),
'domains'),
self.out_name+
'_D2_extracted.fasta'),
shell=True)
D3_check_flag = re.sub("b",'',
re.sub("\'",'',
str(subprocess.check_output("cd {0}; \
if [ ! -s {1} ] && [ ! -s {2} ];\
then echo 'no'; \
fi".format(os.path.join(
os.path.realpath(
self.query_dir),
'domains'),
self.out_name+
'_D3_extracted.fasta',
self.out_name+
'_extra_3'),
shell =True).strip())))
if D3_check_flag!='no':
mearging_cmd = subprocess.call("cd {0};\
cat $(ls | grep -E '*(_D3_extracted|_extra_3).fasta') > tmp_3.fasta; \
mv tmp_3.fasta {1}; \
".format(os.path.join(
os.path.realpath(
self.query_dir),
'domains'),
self.out_name+
'_D3_extracted.fasta'),
shell=True)
else:
making_cmd = subprocess.call("cd {0}; touch {1}; \
".format(os.path.join(
os.path.realpath(
self.query_dir),
'domains'),
self.out_name+
'_D3_extracted.fasta'),
shell=True)
cleaning_cmd = subprocess.call("cd {0};\
rm $(ls | grep -E '*(_cry31|_long_32_11|_Endotoxin_mid|_Endotoxin_M|_extra|_cry_58|_extra_3).(fasta|sto)') \
".format(os.path.join(
os.path.realpath(
self.query_dir),
'domains')),
shell=True)
exist_check_flag = re.sub("b",'',
re.sub("\'",'',
str(subprocess.check_output("cd {0}; \
if [ ! -s {1} ] || [ ! -s {2} ] || [ ! -s {3} ];\
then echo 'no'; \
fi".format(os.path.join(
os.path.realpath(
self.query_dir),
'domains'),
self.out_name+
'_D1_extracted.fasta',
self.out_name+
'_D2_extracted.fasta',
self.out_name+
'_D3_extracted.fasta'),
shell =True).strip())))
if exist_check_flag == 'no':
self.hmmer_result_flag = 1
def cry_3D_ids_extractor(self):
"""
Extracts ids from query for sequences possesing 3 domains of cry toxins
"""
if not self.silent_mode:
print('Exctracting the Cry toxins with 3 domains')
self.logger.info('Exctracting the Cry toxins with 3 domains')
#dictionary of ids is used for the further extraction and processing
self.dom_dict=defaultdict(list)
for i in range(1,4):
#open all the fasta-files after hmmsearch and save them to the dictionary
for record in SeqIO.parse(os.path.join(
os.path.realpath(
self.query_dir),
'domains',
self.out_name+
'_D{}_extracted.fasta'.format(i)),
"fasta"):
#transform the sequence name by combining its id and description
if '|' in record.id:
name = record.id.split('|')[1].split('/')[0] + '|' + \
'|'.join('|'.join(record.description.split('] ')[1].split(' ')).split('_'))
else:
name = record.id.split('/')[0] + '|' + \
'|'.join('|'.join(record.description.split('] ')[1].split(' ')).split('_'))
if 'D{}'.format(i) not in self.dom_dict[name]:
self.dom_dict[name].append('D{}'.format(i))
self.one_dom_count = len([key for key in self.dom_dict if len(set(self.dom_dict[key]))==1])
self.two_dom_count = len([key for key in self.dom_dict if len(set(self.dom_dict[key]))==2])
#returning ids for the sequences with 3 domains (possesing D1,D2,D3 as dictionary items)
return([key for key in self.dom_dict if len(set(self.dom_dict[key]))>=3])
def cry_digestor(self):
"""
Performs processing toxins with 3 domains: cuts left and right flanking sequences
with saving only domains and linkers between domains
"""
if self.mode == 'do':
#domain_only mode: perform hmmsearch only on the domain hmm-models
self.find_domains(self.cry_query)
if self.hmmer_result_flag ==1:
if not self.silent_mode:
print('No toxins found')
self.logger.info('No toxins found')
#obtaining an id list with the cry_3D_ids_extractor function
else:
self.id_list = self.cry_3D_ids_extractor()
final_id_list=list()
if not self.silent_mode:
print("Performing the Cry toxins processing")
self.logger.info('Performing the Cry toxins processing')
self.coordinate_dict = defaultdict(list)
#a starting domain (depends on the -pr flag: you can extract all 3 domains by default or extract 2 and 3 domains only)
dom_start=int(self.processing_flag)
#dictioinary for checking: is needed because sometimes sequences have more than only one match after hmmersearch for one domain (maybe duplication regions?)
pre_dict=defaultdict(dict)
ids_check_set=set()
#check_flag for identical ids in the query
check_flag=0
for i in range(dom_start,4):
#iterate over fasta fles with domains
for record in SeqIO.parse(os.path.join(
os.path.realpath(
self.query_dir),
'domains',
self.out_name+
'_D{}_extracted.fasta'.format(i)),
"fasta"):
dom_list=list()
if '|' in record.id:
name = record.id.split('|')[1].split('/')[0] + '|' + \
'|'.join('|'.join(record.description.split('] ')[1].split(' ')).split('_'))
else:
name = record.id.split('/')[0] + '|' + \
'|'.join('|'.join(record.description.split('] ')[1].split(' ')).split('_'))
if name in self.id_list:
#add all the hmm-matches to pre_dict for the particular sequence
if 'D'+str(i) in pre_dict[name].keys():
#add start and stop coordinates, based on hmmsearch for the each domain
pre_dict[name]['D'+str(i)].extend(record.id.split('/')[1].split('-'))
else:
pre_dict[name]['D'+str(i)]=record.id.split('/')[1].split('-')
for name_key in pre_dict:
#processing pre_dict to get the final domains mapping
for i in range(dom_start,4):
if len(pre_dict[name_key]['D'+str(i)])==2:
#processing pre_dict to get the final domains mappings
#if it contains only two items (start and stop), we will use it
self.coordinate_dict[name_key].extend(pre_dict[name_key]['D'+str(i)])
else:
#choose the longest domain sequence if multiple mathces occur
d=0
ind=0
#get an index of the longest match after looping over all the mathes
for j in range(0,len(pre_dict[name_key]['D'+str(i)]),2):
if int(pre_dict[name_key]['D'+str(i)][j+1]) - int(pre_dict[name_key]['D'+str(i)][j]) > d:
d=int(pre_dict[name_key]['D'+str(i)][j+1]) - int(pre_dict[name_key]['D'+str(i)][j])
ind=j
self.coordinate_dict[name_key].extend(pre_dict[name_key]['D'+str(i)][ind:ind+2])
if str(self.processing_flag)=='1':
for key in self.coordinate_dict:
if int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][0])>75 and int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][2])>75 and int(self.coordinate_dict[key][5]) - int(self.coordinate_dict[key][4])>75:
if int(self.coordinate_dict[key][4]) <= int(self.coordinate_dict[key][3]) and int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][4]) <=55:
self.coordinate_dict[key][3]=int(self.coordinate_dict[key][3])-(int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][4]))-2
if int(self.coordinate_dict[key][2]) <= int(self.coordinate_dict[key][1]) and int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][2]) <=55:
self.coordinate_dict[key][2]=int(self.coordinate_dict[key][2])+(int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][2]))+2
for key in self.coordinate_dict:
#check if the sequece with all 3 domains is growing monotonically
if all(int(x)<int(y) for x, y in zip(self.coordinate_dict[key], self.coordinate_dict[key][1:])) and int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][0])>75 and int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][2])>70 and int(self.coordinate_dict[key][5]) - int(self.coordinate_dict[key][4])>70:
final_id_list.append(key)
if self.processing_flag=='2':
for key in self.coordinate_dict:
if int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][0])>75 and int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][2])>75:
if int(self.coordinate_dict[key][2]) <= int(self.coordinate_dict[key][1]) and int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][2]) <=55:
self.coordinate_dict[key][2]=int(self.coordinate_dict[key][2])+(int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][2]))+2
for key in self.coordinate_dict:
#check if the sequece with all 3 domains is growing monotonically
if all(int(x)<int(y) for x, y in zip(self.coordinate_dict[key], self.coordinate_dict[key][1:])) and int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][0])>75 and int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][2])>70:
final_id_list.append(key)
#create records for the full and processed sequences with 3 domains
new_rec_list=list()
full_rec_list=list()
dummy_dict = copy.deepcopy(self.coordinate_dict)
self.coordinate_dict = defaultdict(list)
for key in final_id_list:
self.coordinate_dict[key]=dummy_dict[key]
self.three_dom_count = len(final_id_list)
for record in SeqIO.parse(self.cry_query,"fasta"):
if record.description != record.id:
name = record.id + '|' +'|'.join('|'.join(record.description.split(' ')[1:]).split('_'))
else:
name= record.id + '|' +'|'.join('|'.join(record.description.split(' ')[0:]).split('_'))
if name in final_id_list:
#check if multiple identical ids are in the query to get warning
if record.id in ids_check_set:
check_flag=1
ids_check_set.add(record.id)
#substract 1 from the starting index because the hmmer output is 1-based
start = min([int(x) for x in self.coordinate_dict[name]])-1
stop = max([int(x) for x in self.coordinate_dict[name]])
full_rec_list.append(SeqRecord(Seq(str(record.seq)),
id=name.split('|')[0],
description=" ".join(name.split('|')[1:])))
new_rec_list.append(SeqRecord(Seq(str(record.seq[start:stop])),
id=name.split('|')[0],
description=" ".join(name.split('|')[1:])))
#save full and processed sequences
SeqIO.write(new_rec_list,
os.path.join(
os.path.realpath(
self.query_dir),
'raw_processed_{}.fasta'.format(
self.out_name)),
"fasta")
SeqIO.write(full_rec_list,
os.path.join(
os.path.realpath(
self.query_dir),
'raw_full_{}.fasta'.format(
self.out_name)),
"fasta")
if check_flag==1:
if not self.silent_mode:
print('Warning! Identical ids in the query, the uncertain mapping can occur')
self.logger.warning('Warning! Identical ids in the query, the uncertain mapping can occur')
if not self.silent_mode:
print('{} sequences recieved'.format(self.init_count))
print('{} potential Cry toxins found'.format(self.one_dom_count+self.two_dom_count+self.three_dom_count))
print('{} toxins with one domain'.format(self.one_dom_count))
print('{} toxins with two domains'.format(self.two_dom_count))
print('{} toxins with three domains'.format(self.three_dom_count))
self.logger.info('{} sequences recieved'.format(self.init_count))
self.logger.info('{} potential Cry toxins found'.format(self.one_dom_count+self.two_dom_count+self.three_dom_count))
self.logger.info('{} toxins with one domain'.format(self.one_dom_count))
self.logger.info('{} toxins with two domains'.format(self.two_dom_count))
self.logger.info('{} toxins with three domains'.format(self.three_dom_count))
if self.mode == 'fd':
self.find_cry(self.cry_query)
if self.hmmer_result_flag ==1:
if not self.silent_mode:
print('No toxins found')
self.logger.info('No toxins found')
else:
#find the domains mode: perform hmmsearch on the full model, then repeat it on domain models
#launch the search for the full potential cry-toxins
#extract the fasta-file after hmmsearch and use it as a query for the domain search
#process the hmmsearch output with sed
cmd_take_file = subprocess.call("cp {0} \
{1}; \
mv {2} \
{3}; \
sed -i 's/[0-9]*|//g' {3}; \
sed -i 's/\/[0-9]*-[0-9]*//g' {3}; \
sed -i 's/ \[subseq from]\ / /g' \
{3}".format(os.path.join(
os.path.realpath(
self.query_dir),
'full_toxins',
'{}_full_extracted.fasta'.format(
self.out_name)),
os.path.join(
os.path.realpath(
self.query_dir)),
os.path.join(
os.path.realpath(
self.query_dir),
'{}_full_extracted.fasta'.format(
self.out_name)),
os.path.join(
os.path.realpath(
self.query_dir),
'{}.fasta'.format(
self.out_name))),
shell=True)
#lauch the domain search
self.find_domains('{}'.format(
os.path.join(
os.path.realpath(
self.query_dir),
'{}.fasta'.format(
self.out_name))))
#further steps are identical to do_mode and are described above
self.id_list = self.cry_3D_ids_extractor()
final_id_list=list()
if not self.silent_mode:
print("Performing the Cry toxins processing")
self.logger.info("Performing the Cry toxins processing")
self.coordinate_dict = defaultdict(list)
pre_dict=defaultdict(dict)
ids_check_set=set()
check_flag=0
self.first_filter_count = len(list(SeqIO.parse('{}'.format(
os.path.join(
os.path.realpath(
self.query_dir),
'{}.fasta'.format(
self.out_name))),
"fasta")))
dom_start=int(self.processing_flag)
for i in range(dom_start,4):
for record in SeqIO.parse(os.path.join(
os.path.realpath(
self.query_dir),
'domains',
self.out_name+
'_D{}_extracted.fasta'.format(i)),
"fasta"):
if '|' in record.id:
name = record.id.split('|')[1].split('/')[0] + '|' +\
'|'.join('|'.join(record.description.split('] ')[1].split(' ')).split('_'))
else:
name = record.id.split('/')[0] + '|' +\
'|'.join('|'.join(record.description.split('] ')[1].split(' ')).split('_'))
if name in self.id_list:
if 'D'+str(i) in pre_dict[name].keys():
pre_dict[name]['D'+str(i)].extend(record.id.split('/')[1].split('-'))
else:
pre_dict[name]['D'+str(i)]=record.id.split('/')[1].split('-')
for name_key in pre_dict:
for i in range(dom_start,4):
if len(pre_dict[name_key]['D'+str(i)])==2:
self.coordinate_dict[name_key].extend(pre_dict[name_key]['D'+str(i)])
else:
d=0
ind=0
for j in range(0,len(pre_dict[name_key]['D'+str(i)]),2):
if int(pre_dict[name_key]['D'+str(i)][j+1]) - int(pre_dict[name_key]['D'+str(i)][j]) > d:
d=int(pre_dict[name_key]['D'+str(i)][j+1]) - int(pre_dict[name_key]['D'+str(i)][j])
ind=j
self.coordinate_dict[name_key].extend(pre_dict[name_key]['D'+str(i)][ind:ind+2])
if str(self.processing_flag)=='1':
for key in self.coordinate_dict:
if int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][0])>75 and int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][2])>75 and int(self.coordinate_dict[key][5]) - int(self.coordinate_dict[key][4])>75:
if int(self.coordinate_dict[key][4]) <= int(self.coordinate_dict[key][3]) and int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][4]) <=55:
self.coordinate_dict[key][3]=int(self.coordinate_dict[key][3])-(int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][4]))-2
if int(self.coordinate_dict[key][2]) <= int(self.coordinate_dict[key][1]) and int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][2]) <=55:
self.coordinate_dict[key][2]=int(self.coordinate_dict[key][2])+(int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][2]))+2
for key in self.coordinate_dict:
#check if the sequece with all 3 domains is growing monotonically
if all(int(x)<int(y) for x, y in zip(self.coordinate_dict[key], self.coordinate_dict[key][1:])) and int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][0])>75 and int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][2])>70 and int(self.coordinate_dict[key][5]) - int(self.coordinate_dict[key][4])>70:
final_id_list.append(key)
if self.processing_flag=='2':
for key in self.coordinate_dict:
if int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][0])>75 and int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][2])>75:
if int(self.coordinate_dict[key][2]) <= int(self.coordinate_dict[key][1]) and int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][2]) <=55:
self.coordinate_dict[key][2]=int(self.coordinate_dict[key][2])+(int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][2]))+2
for key in self.coordinate_dict:
#check if the sequece with all 3 domains is growing monotonically
if all(int(x)<int(y) for x, y in zip(self.coordinate_dict[key], self.coordinate_dict[key][1:])) and int(self.coordinate_dict[key][1]) - int(self.coordinate_dict[key][0])>75 and int(self.coordinate_dict[key][3]) - int(self.coordinate_dict[key][2])>70:
final_id_list.append(key)
new_rec_list=list()
full_rec_list=list()
dummy_dict = copy.deepcopy(self.coordinate_dict)
self.coordinate_dict = defaultdict(list)
for key in final_id_list:
self.coordinate_dict[key]=dummy_dict[key]
self.three_dom_count = len(final_id_list)
for record in SeqIO.parse('{}'.format(os.path.join(
os.path.realpath(
self.query_dir),
'{}.fasta'.format(
self.out_name))),
"fasta"):
if record.description != record.id:
name = record.id + '|' +'|'.join('|'.join(record.description.split(' ')[1:]).split('_'))
else:
name= record.id + '|' +'|'.join('|'.join(record.description.split(' ')[0:]).split('_'))
if name in final_id_list:
if record.id in ids_check_set:
check_flag=1
ids_check_set.add(record.id)
start = min([int(x) for x in self.coordinate_dict[name]])-1
stop = max([int(x) for x in self.coordinate_dict[name]])
new_rec_list.append(SeqRecord(Seq(str(record.seq[start:stop].upper())),
id=name.split('|')[0],
description=" ".join(name.split('|')[1:])))
full_rec_list.append(SeqRecord(Seq(str(record.seq)),
id=name.split('|')[0],
description=" ".join(name.split('|')[1:])))
SeqIO.write(new_rec_list,
os.path.join(
os.path.realpath(
self.query_dir),
'raw_processed_{}.fasta'.format(
self.out_name)),
"fasta")
SeqIO.write(full_rec_list,
os.path.join(
os.path.realpath(
self.query_dir),
'raw_full_{}.fasta'.format(
self.out_name)),
"fasta")
if check_flag==1:
if not self.silent_mode:
print('Warning! Identical ids in the query, the uncertain mapping can occur')
self.logger.warning('Warning! Identical ids in the query, the uncertain mapping can occur')
if not self.silent_mode:
print('{} sequences recieved'.format(self.init_count))
print('{} potential Cry toxins found'.format(self.one_dom_count+self.two_dom_count+self.three_dom_count))
print('{} toxins with one domain'.format(self.one_dom_count))
print('{} toxins with two domains'.format(self.two_dom_count))
print('{} toxins with three domains'.format(self.three_dom_count))
self.logger.info('{} sequences recieved'.format(self.init_count))
self.logger.info('{} potential Cry toxins found'.format(self.one_dom_count+self.two_dom_count+self.three_dom_count))
self.logger.info('{} toxins with one domain'.format(self.one_dom_count))
self.logger.info('{} toxins with two domains'.format(self.two_dom_count))
self.logger.info('{} toxins with three domains'.format(self.three_dom_count))
#create a file with the domain mappings for the each cry-toxin, posessing all 3 domains
if self.hmmer_result_flag !=1:
#create a mapping file only if the hmmsearch output is not empty
with open(os.path.join(
os.path.realpath(
self.query_dir),
'proteins_domain_mapping_processed_{}.bed'.format(
self.out_name)),'w') as csv_file:
my_writer = csv.writer(csv_file, delimiter='\t')
#create a bed-file for mapping to specify start and stop coordinates, id and description
#init_row = ['id','domain' ,'start', 'stop', 'description']
#my_writer.writerow(init_row)
for key in self.coordinate_dict:
#iterate over starting indicies in the dictionary of coordinates
if self.processing_flag!="2":
for i in range(0,5,2):
if i==0:
row=[key.split('|')[0],
int(self.coordinate_dict[key][i])-int(self.coordinate_dict[key][0]),
int(self.coordinate_dict[key][i+1])-int(self.coordinate_dict[key][0])-1,
'domain_{}'.format(1)+'_'+key.split('|')[0]]
else:
if i==2:
dn=2
else:
dn=3
row=[key.split('|')[0],
int(self.coordinate_dict[key][i])-int(self.coordinate_dict[key][0])-1,
int(self.coordinate_dict[key][i+1])-int(self.coordinate_dict[key][0])-1,
'domain_{}'.format(dn)+'_'+key.split('|')[0]]
my_writer.writerow(row)
else:
for i in range(0,3,2):
if i==0:
row=[key.split('|')[0],
int(self.coordinate_dict[key][i])-int(self.coordinate_dict[key][0]),
int(self.coordinate_dict[key][i+1])-int(self.coordinate_dict[key][0])-1,
'domain_{}'.format(2)+'_'+key.split('|')[0]]
else:
if i==2:
dn=3
row=[key.split('|')[0],
int(self.coordinate_dict[key][i])-int(self.coordinate_dict[key][0])-1,
int(self.coordinate_dict[key][i+1])-int(self.coordinate_dict[key][0])-1,
'domain_{}'.format(dn)+'_'+key.split('|')[0]]
my_writer.writerow(row)
#create a bed-file with the full protein mappings
with open(os.path.join(
os.path.realpath(
self.query_dir),
'proteins_domain_mapping_full_{}.bed'.format(
self.out_name)),'w') as csv_file:
my_writer = csv.writer(csv_file, delimiter='\t')
#init_row = ['id','domain' ,'start', 'stop', 'description']
#my_writer.writerow(init_row)
for key in self.coordinate_dict:
if self.processing_flag!="2":
for i in range(0,5,2):
if i==0:
row=[key.split('|')[0],
int(self.coordinate_dict[key][i]),
int(self.coordinate_dict[key][i+1])-1,
'domain_{}'.format(1)+'_'+key.split('|')[0]]
else:
if i==2:
dn=2
else:
dn=3
row=[key.split('|')[0],
int(self.coordinate_dict[key][i])-1,
int(self.coordinate_dict[key][i+1])-1,
'domain_{}'.format(dn)+'_'+key.split('|')[0]]
my_writer.writerow(row)
else:
for i in range(0,3,2):
if i==0:
row=[key.split('|')[0],
int(self.coordinate_dict[key][i]),
int(self.coordinate_dict[key][i+1])-1,
'domain_{}'.format(2)+'_'+key.split('|')[0]]
else:
if i==2:
dn=3
row=[key.split('|')[0],
int(self.coordinate_dict[key][i])-1,
int(self.coordinate_dict[key][i+1])-1,
'domain_{}'.format(dn)+'_'+key.split('|')[0]]
my_writer.writerow(row)
#save the original dictionary of coordinates for checking
with open(os.path.join(
os.path.realpath(
self.query_dir),
'coordinate_matches_{}.txt'.format(
self.out_name)),'w') as csv_file:
my_writer = csv.writer(csv_file, delimiter='\t')
for key in self.coordinate_dict:
my_writer.writerow([key]+self.coordinate_dict[key])
def annotate_raw_output(self):
"""
Performs annotating raw sequences with diamond ocer database from btnomenclature
Uses full records for annotation to get potentially new toxins
"""
#ids for toxins, differ from btnomenclature
new_records = list()
self.new_ids=dict()
un_count=0
total_count=0
#diamond should have a database file in the same directory with the query.
#copying database for pefrorming blastp
raw_full_check_flag = re.sub("b",'',
re.sub("\'",'',
str(subprocess.check_output("cd {0}; \
if [ ! -s raw_full_{1}.fasta ] ;\
then echo 'no'; \
fi".format(os.path.join(
os.path.realpath(
self.query_dir)),
self.out_name),
shell =True).strip())))
if raw_full_check_flag == 'no':
cmd_empty = subprocess.call('cd {0}; \
touch diamond_matches_{1}.txt'.format(
os.path.join(
os.path.realpath(
self.query_dir)),
self.out_name),
shell=True)
if not self.silent_mode:
print("No 3D Cry toxins found")
self.logger.info("No 3D Cry toxins found")
else:
if not self.silent_mode:
print("Annotating the raw output with diamond")
self.logger.info("Annotating the raw output with diamond")
cmd_pre_dia = subprocess.call('cd {0}; \
cp {1} .; \
touch diamond.log'.format(
os.path.join(
os.path.realpath(
self.query_dir)),
os.path.realpath(
os.path.join(
os.path.dirname(__file__),
'data',
"diamond_data",
"cry_nomenclature.dmnd"))),
shell=True)
#performing diamond blastp, save only the first hit
cmd_dia = subprocess.call('cd {0};\
{1} blastp \
-d cry_nomenclature \
-q raw_full_{2}.fasta \
-o diamond_matches_{2}.txt \
--al aligned_{2}.fa \
--un unaligned_{2}.fa \
--max-target-seqs 1 \
--log --verbose 2>> diamond.log; \
rm cry_nomenclature.dmnd; \
mv *.log logs/; \
mv *gned* logs/'.format(
os.path.join(
os.path.realpath(
self.query_dir)),
os.path.realpath(
os.path.join(
os.path.dirname(__file__),
"include",
"diamond")),
self.out_name),
shell=True)
#analyse diamond matches to get new toxins
with open(os.path.join(
os.path.realpath(
self.query_dir),
'diamond_matches_{}.txt'.format(
self.out_name)),'r') as csv_file:
my_reader = csv.reader(csv_file, delimiter='\t')
for row in my_reader:
total_count+=1
if float(row[2])<100.0:
self.new_ids[row[0]]=row[1]+'|'+ str(row[2])
un_count+=1
#extract unique sequences from the raw sequences
for init_rec in SeqIO.parse(os.path.join(
os.path.realpath(
self.query_dir),
'raw_processed_{}.fasta'.format(
self.out_name)),
"fasta"):
if init_rec.id in self.new_ids.keys():
new_records.append(SeqRecord(Seq(str(init_rec.seq)),
id=self.new_ids[init_rec.id].split('|')[0]+'(' +
self.new_ids[init_rec.id].split('|')[1]+')'+
'_'+init_rec.description.split()[0],
description=init_rec.description))
if not self.silent_mode: