-
Notifications
You must be signed in to change notification settings - Fork 4
/
KIPEs3.py
2325 lines (1954 loc) · 91 KB
/
KIPEs3.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
### Boas Pucker ###
### b.pucker@tu-braunschweig.de ###
__version__ = "v3.2.6" #converted to Python3
__reference__ = "Pucker et al., 2020: https://doi.org/10.3390/plants9091103 and Rempel&Pucker, 2023: https://doi.org/10.1101/2022.06.30.498365"
__usage__ = """
KIPEs """ + __version__ + """("""+ __reference__ +""")
Usage:
python3 KIPEs3.py
--baits <FOLDER_WITH_BAIT_SEQ_FILES>
--positions <FOLDER_WITH_POSITION_FILES>|--residues
--out <OUTPUT_DIR>
--subject <SUBJECT_FILE (peptide,transcript,genomic sequences)> | --subjectdir <SUBJECT_FOLDER_WITH_SEQ_FILES>
optional:
--seqtype <TYPE_OF_SUBJECT_SEQUENCES(pep|rna|dna)>[pep]
--checks <VALIDATE_INPUT_BEFORE_RUNNING_PIPELINE (on|off)>[on]
--cpus <INT, NUMBER_OF_BLAST_THREADS>[10]
--scoreratio <FLOAT, BLAST_SCORE_RATIO_CUTOFF>[0.3]
--simcut <FLOAT, MINIMAL_BLAST_HIT_SIMILARITY_IN_PERCENT>[40.0]
--genesize <INT, SIZE_OF_GENE_FOR_GROUPING_OF_EXON_HITS>[5000]
--minsim <FLOAT, MINIMAL_SIMILARITY_IN_GLOBAL_ALIGNMENT>[0.4]
--minres <FLOAT, MINIMAL_PROPORTION_OF_CONSERVED_RESIDUES>[off]
--minreg <FLOAT, MINIMAL_PROPORTION_OF_CONSERVED_REGIONS>[off]
--pathway <TEXT_FILE_SPECIFYING_GENE_ORDER>
--possibilities <INT, NUMBER_OF_CONSIDERED_ENZYME_FUNCTIONS_PER_SEQ>[3]
--mafft <PATH_TO_MAFFT>[mafft]
--blastp <PATH_TO_AND_INCLUDING_BINARY>[blastp]
--tblastn <PATH_TO_AND_INCLUDING_BINARY>[tblastn]
--makeblastdb <PATH_TO_AND_INCLUDING_BINARY>[makeblastdb]
--fasttree <PATH_TO_FASTTREE>(recommended for tree building)
--iqtree <PATH_TO_IQ-TREE>
--forester <ACTIVATES_GENE_TREE_CONSTRUCTION>[off]
--exp <GENE_EXPRESSION_FILE_ACTIVATES_COEXPRESSION_ANALYSIS>[off]
--rcut <CORRELATION_CUTOFF>[0.3]
--pcut <P_VALUE_CUTOFF>[0.05]
--minexp <MIN_EXP_PER_GENE>[30]
bug reports and feature requests: b.pucker@tu-bs.de
Complete documentation: https://github.com/bpucker/KIPEs
"""
import os, glob, sys, time, re, math, subprocess, dendropy
from operator import itemgetter
try:
from scipy import stats
except:
sys.stdout.write( "WARNING: scipy import failed. Analysis of co-expression will not be possible. Please ensure that scipy is installed to enable this option.\n" )
sys.stdout.flush()
try:
import hashlib
except ImportError:
sys.stdout.write( "WARNING: hashlib import failed. Calculation of md5sums for inputs files not possible. Please install hashlib to improve the documentation quality.\n" )
sys.stdout.flush()
# --- end of imports --- #
def generate_query( fasta, blast_query_dir, nmt ):
"""! @brief generate query file """
ID = fasta.split('/')[-1].split('.')[0]
output_file = blast_query_dir + ID + ".fasta"
with open( output_file, "w" ) as out:
with open( fasta, "r" ) as f:
counter = 1
nmt.write( f.readline().strip()[1:].replace( "\t", " " ) + '\t' ) #remove header
line = f.readline()
seq = []
while line:
if line[0] == ">":
out.write( '>' + ID + "_%_" + str( counter ).zfill( 3 ) + '\n' + "".join( seq ) + '\n' )
nmt.write( ID + "_%_" + str( counter ).zfill( 3 ) + '\n' + line.strip()[1:].replace( "\t", " " ) + "\t" )
counter += 1
seq = []
else:
seq.append( line.strip() )
line = f.readline()
out.write( '>' + ID + "_%_" + str( counter ).zfill( 3 ) + '\n' + "".join( seq ) + '\n' )
nmt.write( ID + "_%_" + str( counter ).zfill( 3 ) + '\n' )
return output_file
def load_self_BLAST_hit_scores( self_blast_result_file ):
"""! @brief load self BLAST hit scores """
self_BLAST_hit_scores = {}
with open( self_blast_result_file, "r" ) as f:
line = f.readline()
while line:
parts = line.strip().split('\t')
try:
self_BLAST_hit_scores[ parts[0] ]
except KeyError:
self_BLAST_hit_scores.update( { parts[0]: float( parts[-1] ) } )
line = f.readline()
return self_BLAST_hit_scores
def load_BLAST_results( blast_result_file, self_scores, score_ratio_cutoff, similarity_cutoff, possibility_cutoff ):
"""! @brief load BLAST results """
valid_blast_hits = {}
with open( blast_result_file, "r" ) as f:
line = f.readline()
while line:
parts = line.strip().split('\t')
if float( parts[2] ) > similarity_cutoff: #similarity is sufficient
if float( parts[-1] ) > score_ratio_cutoff * self_scores[ parts[0] ]: #substantial part of query is matched
try:
valid_blast_hits[ parts[1] ].append( { 'gene': parts[0].split('_%_')[0], 'score': float( parts[-1] ) } )
except KeyError:
valid_blast_hits.update( { parts[1]: [ { 'gene': parts[0].split('_%_')[0], 'score': float( parts[-1] ) } ] } )
line = f.readline()
# --- reduce BLAST hit number to given number of candidate possibilities ---- #
final_valid_blast_hits = {}
for key in list(valid_blast_hits.keys()):
hits = sorted( valid_blast_hits[ key ], key=itemgetter( 'score' ) )[::-1]
genes = []
for hit in hits:
if hit['gene'] not in genes:
if len( genes ) < possibility_cutoff:
genes.append( hit['gene'] )
final_valid_blast_hits.update( { key: genes } )
return final_valid_blast_hits
def find_sisters_in_tree( tree_file, all_seq_IDs_in_tree ):
"""! @brief find sister clade in phylogenetic tree
@note This function is based on the MYB_annotator: https://doi.org/10.1101/2021.10.16.464636
"""
if len( all_seq_IDs_in_tree ) > 0:
# --- find node objects of reference genes --- #
tree = dendropy.Tree.get_from_path( tree_file, "newick" )
pdm = dendropy.PhylogeneticDistanceMatrix.from_tree( tree )
my_mean_nearest_taxon_distance = pdm.mean_nearest_taxon_distance()
ref_node_objects = []
new_node_objects = []
for node in tree.taxon_namespace:
if node.label == "CANDIDATE":
new_node_objects.append( node )
else:
ref_node_objects.append( node )
data = []
t1 = new_node_objects[0]
for t2 in ref_node_objects: #calculate distance to all other sequences in tree
edge_distance = pdm.path_edge_count( t1, t2)
patr_distance = pdm.patristic_distance( t1, t2 )
data.append( { 'ref_gene': (t2.label).split('-%-')[0], 'edge': edge_distance, 'patr': patr_distance } )
sisters = []
for entry in sorted( data, key=itemgetter('edge', 'patr') ):
if entry['ref_gene'] not in sisters:
sisters.append( entry['ref_gene'] )
return sisters #returns a sorted list of reference gene function names (closest homolog first)
else:
sys.stdout.write( "ERROR: " + tree_file + "\n" )
sys.stdout.flush()
return []
def alignment_trimming( aln_file, cln_aln_file, occupancy ):
"""! @brief remove all alignment columns with insufficient occupancy """
alignment = load_alignment( aln_file, {} )
# --- if there is an alignment (expected case)
if len( list(alignment.keys()) ) > 0:
# --- identify valid residues in aligned sequences (columns with sufficient occupancy) --- #
valid_index = []
for idx, aa in enumerate( list(alignment.values())[0] ):
counter = 0
for key in list(alignment.keys()):
if alignment[ key ][ idx ] != "-":
counter += 1
if counter / float( len( list(alignment.keys()) ) ) > occupancy:
valid_index.append( idx )
# --- generate new sequences --- #
with open( cln_aln_file, "w" ) as out:
for key in list(alignment.keys()):
seq = alignment[ key ]
new_seq = []
for idx in valid_index:
new_seq.append( seq[ idx ] )
out.write( ">" + key + '\n' + "".join( new_seq ) + '\n' )
# --- just in case the alignment file is empyt (is this possible?) ---#
else:
with open( cln_aln_file, "w" ) as out:
out.write( "" )
def tree_based_classification( blast_result_file, self_scores, score_ratio_cutoff, similarity_cutoff, tree_tmp, treemethod, fasttree, iqtree, mafft, peps, ref_seqs, possibility_cutoff ):
"""! @brief load BLAST results """
final_results = {}
# --- get all valid seqs --- #
valid_blast_hits = {}
with open( blast_result_file, "r" ) as f:
line = f.readline()
while line:
parts = line.strip().split('\t')
if float( parts[2] ) > similarity_cutoff: #similarity is sufficient
if float( parts[-1] ) > score_ratio_cutoff * self_scores[ parts[0] ]: #substantial part of query is matched
try:
valid_blast_hits[ parts[1] ].append( { 'id': parts[0], 'score': float( parts[-1] ), 'gene': parts[0].split('_%_')[0] } )
except KeyError:
valid_blast_hits.update( { parts[1]: [ { 'id': parts[0], 'score': float( parts[-1] ), 'gene': parts[0].split('_%_')[0] } ] } )
line = f.readline()
# --- prepare refseq data --- #
ref_seq_seqs = {}
ref_seq_ID_to_gene_mapping = {}
for value in list(ref_seqs.values()):
for entry in value:
ref_seq_seqs.update( { entry['id']: entry['seq'] } ) #id or name?
ref_seq_ID_to_gene_mapping.update( { entry['id']: entry['gene'] } )
# --- process all valid BLAST results --- #
for key in list(valid_blast_hits.keys()):
if len( valid_blast_hits[ key ] ) == 1:
final_results.update( { key: [ valid_blast_hits[ key ][0]['gene'] ] } )
else:
# --- build tree --- #
seq_file = tree_tmp + key + ".fasta"
all_seq_IDs_in_tree = []
with open( seq_file, "w" ) as out:
out.write( '>CANDIDATE\n' + peps[ key ] + '\n' )
for each in valid_blast_hits[ key ]:
out.write( '>' + each['id'].replace('_',"-") + '\n' + ref_seq_seqs[ each['id'] ] + '\n' )
all_seq_IDs_in_tree.append( each['id'].replace('_',"-") )
aln_file = seq_file + ".aln"
p = subprocess.Popen( args= " ".join( [ mafft, seq_file, ">", aln_file, "2>", aln_file+".err" ] ), shell=True )
p.communicate()
cln_aln_file = aln_file + ".cln"
occupancy = 0.3 #could be implemented as option later
alignment_trimming( aln_file, cln_aln_file, occupancy )
tree_file = cln_aln_file + ".tree"
if treemethod == "fasttree": #construct tree with FastTree2
p = subprocess.Popen( args= " ".join( [ fasttree, "-wag -nosupport <", cln_aln_file, ">", tree_file, "2>", tree_file+".err" ] ), shell=True )
p.communicate()
elif treemethod == "iqtree": #construct tree with IQ-TREE
tmp_tree_file = cln_aln_file + ".treefile" #".treefile" is appended to provided alignment file name
p = subprocess.Popen( args= iqtree + " -nt 1 -s " + cln_aln_file, shell=True ) #bootstrapping: -alrt 1000 -bb 1000
p.communicate()
p = subprocess.Popen( args= "mv " + tmp_tree_file + " " + tree_file, shell=True )
p.communicate()
# --- find reference seqs sister --- #
sisters = find_sisters_in_tree( tree_file, all_seq_IDs_in_tree )
if len( sisters ) > 0:
genes = []
for s, sister in enumerate( sisters ):
if s < possibility_cutoff:
genes.append( sister ) #sister.split('_%_')[0]
final_results.update( { key: genes } )
return final_results
def load_sequences( fasta_file ):
"""! @brief load candidate gene IDs from file """
sequences = {}
with open( fasta_file ) as f:
header = f.readline()[1:].strip()
# if " " in header:
# header = header.split(' ')[0]
# if "\t" in header:
# header = header.split('\t')[0]
seq = []
line = f.readline()
while line:
if line[0] == '>':
sequences.update( { header: "".join( seq ) } )
header = line.strip()[1:]
# if " " in header:
# header = header.split(' ')[0]
# if "\t" in header:
# header = header.split('\t')[0]
seq = []
else:
seq.append( line.strip() )
line = f.readline()
sequences.update( { header: "".join( seq ) } )
return sequences
def load_ref_seqs( query_file, name_mapping_table ):
"""! @brief load all reference sequences """
mapping_table = {}
with open( name_mapping_table, "r" ) as f:
line = f.readline()
while line:
parts = line.strip().split('\t')
mapping_table.update( { parts[1]: parts[0] } )
line = f.readline()
# --- load sequences --- #
seqs = load_sequences( query_file )
ref_seqs = {}
for key in list(seqs.keys()):
gene = key.split('_%_')[0]
try:
ref_seqs[ gene ].append( { 'id': key, 'gene': gene, 'seq': seqs[ key ], 'name': mapping_table[ key ] } )
except KeyError:
ref_seqs.update( { gene: [ { 'id': key, 'gene': gene, 'seq': seqs[ key ], 'name': mapping_table[ key ] } ] } )
return ref_seqs
def load_alignment( aln_file, tmp_mapping ):
"""! @brief load alignment and replace query IDs by real sequence names """
sequences = {}
with open( aln_file ) as f:
header = f.readline()[1:].strip()
try:
header = tmp_mapping[ header ]
except KeyError:
pass
seq = []
line = f.readline()
while line:
if line[0] == '>':
sequences.update( { header: "".join( seq ) } )
header = line.strip()[1:]
try:
header = tmp_mapping[ header ]
except KeyError:
pass
seq = []
else:
seq.append( line.strip() )
line = f.readline()
sequences.update( { header: "".join( seq ) } )
return sequences
def calculate_similarity( seq1, seq2 ):
"""! @brief calculate similarity of two sequences with seq2 as reference """
counter = 0
for idx, aa in enumerate( seq1 ):
if aa == seq2[ idx ] and aa != "-":
counter += 1
ref_len = float( len( seq2 ) - seq2.count( "-" ) )
return counter / ref_len
def calculate_sim_matrix_per_gene( query_names_by_gene, candidates_by_gene, alignment_per_candidate ):
"""! @brief calculate alignment-based similarity matrix per gene """
sim_matrix_per_gene = {}
#sim_matrix_per_gene: { 'CHS': { 'candidate1': { 'q1': xx, 'q2': xx, 'q3': xxx, ... }, 'candidate2': { ... }, .... }, 'CHI': { ... }, ... }
#query_names_by_gene: { 'CHS': [ q1, q2, ... ], 'CHI': [...], ... }
#candidates_by_gene: { 'CHS': [ candidate1, candidate2, ... ], 'CHI': [...], ... }
#alignment_per_candidate: { 'candidate1': { 'candidate1': xxxxx, 'q1': xxxxxx, 'q2': xxxxx, ... }, 'candidate2': {...}, .... }
for gene in list(candidates_by_gene.keys()):
gene_sim_matrix = {}
for candidate in candidates_by_gene[ gene ]:
candiate_sim_matrix = {}
for query in query_names_by_gene[ gene ]:
try:
sim = calculate_similarity( alignment_per_candidate[ candidate ][ gene ][ candidate ], alignment_per_candidate[ candidate ][ gene ][ query ] )
except KeyError:
sim = 0
candiate_sim_matrix.update( { query: sim } )
gene_sim_matrix.update( { candidate: candiate_sim_matrix } )
sim_matrix_per_gene.update( { gene: gene_sim_matrix } )
return sim_matrix_per_gene
def generate_global_alignments( mafft, peps, blast_hits, tmp_dir, ref_seqs ):
"""! @brief generate and load global alignments, calculate similarity matrix """
alignment_per_candidate = {}
candidates_by_gene = {}
for candidate in list(blast_hits.keys()):
genes = blast_hits[ candidate ]
for gene in genes:
try:
candidates_by_gene[ gene ].append( candidate )
except KeyError:
candidates_by_gene.update( { gene: [ candidate ] } )
tmp_mapping = {}
tmp_seq_file = tmp_dir + candidate + ".fasta"
aln_file = tmp_dir + candidate + ".fasta.aln"
# --- prepare multiple FASTA file --- #
with open( tmp_seq_file, "w" ) as out:
out.write( '>' + candidate + '\n' + peps[ candidate ] + '\n' )
for ref in ref_seqs[ gene ]:
out.write( '>' + ref['id'] + '\n' + ref['seq'] + '\n' )
tmp_mapping.update( { ref['id']: ref['name'] } )
# --- run alignment --- #
p = subprocess.Popen( args= mafft + " " + tmp_seq_file + " > " + aln_file + " 2> " + aln_file+".err", shell=True )
p.communicate()
try:
alignment_per_candidate[ candidate ].update( { gene: load_alignment( aln_file, tmp_mapping ) } )
except KeyError:
alignment_per_candidate.update( { candidate: { gene: load_alignment( aln_file, tmp_mapping ) } } )
# --- get all query sequence names per gene --- #
query_names_by_gene = {}
for ref in [ x for sublist in list(ref_seqs.values()) for x in sublist]: #walk through all query sequences
try:
query_names_by_gene[ ref['gene'] ].append( ref['name'] )
except KeyError:
query_names_by_gene.update( { ref['gene']: [ ref['name'] ] } )
# --- calculate similarity matrix per gene --- #
sim_matrix_per_gene = calculate_sim_matrix_per_gene( query_names_by_gene, candidates_by_gene, alignment_per_candidate )
return alignment_per_candidate, sim_matrix_per_gene, candidates_by_gene
def generate_sim_matrix_output_files( sim_matrix_folder, sim_matrix_per_gene, subject_name_mapping_table ):
"""! @brief generate one output file per gene """
sim_per_pep = {}
for gene in list(sim_matrix_per_gene.keys()):
output_file = sim_matrix_folder + gene + "_sim_matrix.txt"
with open( output_file, "w" ) as out:
data = sim_matrix_per_gene[ gene ] #similarity matrices for all candidates
queries = sorted( list(data.values())[0].keys() )
out.write( "\t".join( [ "candidate" ] + queries ) + '\n' )
for candidate in sorted( data.keys() ):
new_line = [ subject_name_mapping_table[ candidate ] ]
for query in queries:
new_line.append( 100.0*data[ candidate ][ query ] )
try:
sim_per_pep[ candidate ].update( { gene: sum( new_line[1:] ) / len( new_line[1:] ) } )
except KeyError:
sim_per_pep.update( { candidate: { gene: sum( new_line[1:] ) / len( new_line[1:] ) } } )
out.write( "\t".join( map( str, new_line ) ) + '\n' )
return sim_per_pep
def load_pos_data_per_gene( pos_data_files ):
"""! @brief load conserved residue positions from given data file """
pos_per_gene = {}
regions_per_gene = {}
for filename in pos_data_files:
gene = filename.split('/')[-1].split('.')[0]
with open( filename, "r" ) as f:
#SEQ_NAME
#R X,Y,Z 1
#R X2
#R X3
# ...
#R X10
#D DOMAIN_SEQ START END
#D DOMAIN_SEQ START END
#...
regions = []
residues = []
line = f.readline()
while line:
if line[0] != "#":
if line[0] == "!":
ref_seq = line.strip()[1:]
else:
parts = line.strip().split('\t')
if len( parts ) > 0:
if parts[0] == "D":
if len( parts ) > 3:
if len( parts ) > 4:
comment = "".join( parts[4:] )
else:
comment = ""
regions.append( { 'name': parts[1], 'start': int( parts[2] ), 'end': int( parts[3] ), 'comment': comment } )
elif parts[0] == "R":
if "," in parts[1]:
res = parts[1].split(',')
else:
res = [ parts[1] ]
if len( parts ) > 3:
comment = "".join( parts[3:] )
else:
comment = ""
residues.append( { 'aa': res, 'pos': int( parts[2] ), 'comment': comment } )
line = f.readline()
regions_per_gene.update( { gene: { 'seq': ref_seq, 'regions': regions } } )
pos_per_gene.update( { gene: { 'seq': ref_seq, 'residues': residues } } )
return pos_per_gene, regions_per_gene
def get_alignment_pos( ref_aln, target_index ):
"""! @brief get index in alignment based on target """
index = -1
counter = 0
while counter < len( ref_aln ):
if ref_aln[ counter ] != "-":
index += 1
if index == target_index:
return counter
counter += 1
return "ERROR: target index exceeds sequence length!"
def check_alignment_for_cons_res( can_aln, ref_aln, residues ):
"""! @brief inspect alignment of candidate at conserved residue positions """
results = []
extra_results = []
for res in residues:
alignment_pos = get_alignment_pos( ref_aln, res['pos']-1 )
if can_aln[ alignment_pos ] == "-":
results.append( "-" )
extra_results.append( "-" )
else:
results.append( can_aln[ alignment_pos ] in res['aa'] ) #multiple different amino acids might be permitted at one position
extra_results.append( can_aln[ alignment_pos ] )
return results, extra_results
def check_cons_res( cons_res_matrix_folder, pos_data_per_gene, alignment_per_candidate, candidates_by_gene, subject_name_mapping_table ):
"""! @brief check all candidate sequences for conserved residues and generate result tables """
cons_pos_per_pep = {}
cons_pos_per_pep_extra = {}
for gene in list(candidates_by_gene.keys()):
candidates = candidates_by_gene[ gene ]
try:
info = pos_data_per_gene[ gene ]
output_file = cons_res_matrix_folder + gene + "_conserved_residues.txt"
residues = sorted( info['residues'], key=itemgetter('pos') )
with open( output_file, "w" ) as out:
header = [ "candidate" ]
for each in residues:
header.append( "/".join( each['aa'] ) + str( each['pos'] ) )
out.write( "\t".join( header ) + '\n' )
for candidate in candidates:
can_aln = alignment_per_candidate[ candidate ][ gene ][ candidate ]
ref_aln = alignment_per_candidate[ candidate ][ gene ][ info['seq'] ]
results, extra_results = check_alignment_for_cons_res( can_aln, ref_aln, residues )
out.write( "\t".join( map( str, [ subject_name_mapping_table[ candidate ] ] + results ) ) + '\n' )
try:
if len( results ) > 0:
cons_pos_per_pep[ candidate ].update( { gene: 100.0* results.count( True ) / len( results ) } )
cons_pos_per_pep_extra[ candidate ].update( { gene: extra_results } )
else:
cons_pos_per_pep[ candidate ].update( { gene: 0.0 } )
cons_pos_per_pep_extra[ candidate ].update( { gene: extra_results } )
except KeyError:
if len( results ) > 0:
cons_pos_per_pep.update( { candidate: { gene: 100.0* results.count( True ) / len( results ) } } )
cons_pos_per_pep_extra.update( { candidate: { gene: extra_results } } )
else:
cons_pos_per_pep.update( { candidate: { gene: 0.0 } } )
cons_pos_per_pep_extra.update( { candidate: { gene: extra_results } } )
except KeyError:
sys.stdout.write( "ERROR: no information (conserved residues) available about gene: " + gene + "\n" )
sys.stdout.flush()
return cons_pos_per_pep, cons_pos_per_pep_extra
def check_alignment_for_cons_reg( can_aln, ref_aln, regions ):
"""! @brief check conserved regions """
results = []
for reg in regions:
alignment_start_pos = get_alignment_pos( ref_aln, reg['start']-1 )
alignment_end_pos = get_alignment_pos( ref_aln, reg['end']-1 )
#calculate similarity
ref = ref_aln[ alignment_start_pos:alignment_end_pos+1 ]
can = can_aln[ alignment_start_pos:alignment_end_pos+1 ]
results.append( 100.0*calculate_similarity( can, ref ) )
return results
def check_cons_reg( cons_reg_matrix_folder, regions_per_gene, alignment_per_candidate, candidates_by_gene, subject_name_mapping_table ):
"""! @brief check all candidate sequences for conserved residues and generate result tables """
cons_reg_per_pep = {}
for gene in list(candidates_by_gene.keys()):
candidates = candidates_by_gene[ gene ]
try:
info = regions_per_gene[ gene ]
output_file = cons_reg_matrix_folder + gene + "_conserved_residues.txt"
regions = sorted( info['regions'], key=itemgetter('start') )
with open( output_file, "w" ) as out:
header = [ "candidate" ]
for each in regions:
header.append( each['name'] + "," + str( each['start'] ) + "-" + str( each['end'] ) )
out.write( "\t".join( header ) + '\n' )
for candidate in candidates:
can_aln = alignment_per_candidate[ candidate ][ gene ][ candidate ]
ref_aln = alignment_per_candidate[ candidate ][ gene ][ info['seq'] ]
results = check_alignment_for_cons_reg( can_aln, ref_aln, regions )
out.write( "\t".join( map( str, [ subject_name_mapping_table[ candidate ] ] + results ) ) + '\n' )
try:
try:
cons_reg_per_pep[ candidate ].update( { gene: sum( results ) / len( results ) } )
except ZeroDivisionError:
cons_reg_per_pep[ candidate ].update( { gene: 0.0 } )
except KeyError:
try:
cons_reg_per_pep.update( { candidate: { gene: sum( results ) / len( results ) } } )
except ZeroDivisionError:
cons_reg_per_pep.update( { candidate: { gene: 0.0 } } )
except KeyError:
sys.stdout.write( "ERROR: no information (conserved regions) available about gene: " + gene + "\n" )
sys.stdout.flush()
return cons_reg_per_pep
def generate_subject_file( peptide_file, subject_name_file, subject_file ):
"""! @brief rename all subject sequences at input """
with open( peptide_file, "w" ) as out:
with open( subject_name_file, "w" ) as out2:
with open( subject_file, "r" ) as f:
counter = 1
out2.write( f.readline().strip()[1:].replace( "\t", " " ).replace( "\u2000", " " ) + '\t' ) #remove header
line = f.readline()
seq = []
while line:
if line[0] == ">":
out.write( '>X' + str( counter ) + '\n' + "".join( seq ) + '\n' )
out2.write( "X" + str( counter ) + '\n' + line.strip()[1:].replace( "\t", " " ).replace( "\u2000", " " ) + "\t" )
counter += 1
seq = []
else:
seq.append( line.strip() )
line = f.readline()
out.write( '>X' + str( counter ) + '\n' + "".join( seq ) + '\n' )
out2.write( "X" + str( counter ) + '\n' )
def load_subject_name_mapping_table( subject_name_file ):
"""! @brief load subject name mapping table """
mapping_table = {}
with open( subject_name_file, "r" ) as f:
line = f.readline()
while line:
parts = line.strip().split('\t')
mapping_table.update( { parts[1]: parts[0] } )
line = f.readline()
return mapping_table
# --- functions to handle RNA (transcriptome sequence) input --- #
def translate( seq, genetic_code ):
"""! @brief translates the given nucleotide sequence into peptide and splits at each star (stop codon) """
seq = seq.upper()
peptide = []
for i in range( int( len( seq ) / 3.0 ) ):
codon = seq[i*3:i*3+3]
try:
peptide.append( genetic_code[ codon ] )
except:
peptide.append( "*" )
return "".join( peptide )
def revcomp( seq ):
"""! @brief construct reverse complement of sequence """
new_seq = []
bases = { 'a':'t', 't':'a', 'c':'g', 'g':'c' }
for nt in seq.lower():
try:
new_seq.append( bases[nt] )
except:
new_seq.append( 'n' )
return ''.join( new_seq[::-1] ).upper()
def translator( input_file, min_len_cutoff ):
"""! @brief translate all sequences in given file in all frames """
genetic_code = { 'CTT': 'L', 'ATG': 'M', 'AAG': 'K', 'AAA': 'K', 'ATC': 'I',
'AAC': 'N', 'ATA': 'I', 'AGG': 'R', 'CCT': 'P', 'ACT': 'T',
'AGC': 'S', 'ACA': 'T', 'AGA': 'R', 'CAT': 'H', 'AAT': 'N',
'ATT': 'I', 'CTG': 'L', 'CTA': 'L', 'CTC': 'L', 'CAC': 'H',
'ACG': 'T', 'CCG': 'P', 'AGT': 'S', 'CAG': 'Q', 'CAA': 'Q',
'CCC': 'P', 'TAG': '*', 'TAT': 'Y', 'GGT': 'G', 'TGT': 'C',
'CGA': 'R', 'CCA': 'P', 'TCT': 'S', 'GAT': 'D', 'CGG': 'R',
'TTT': 'F', 'TGC': 'C', 'GGG': 'G', 'TGA': '*', 'GGA': 'G',
'TGG': 'W', 'GGC': 'G', 'TAC': 'Y', 'GAG': 'E', 'TCG': 'S',
'TTA': 'L', 'GAC': 'D', 'TCC': 'S', 'GAA': 'E', 'TCA': 'S',
'GCA': 'A', 'GTA': 'V', 'GCC': 'A', 'GTC': 'V', 'GCG': 'A',
'GTG': 'V', 'TTC': 'F', 'GTT': 'V', 'GCT': 'A', 'ACC': 'T',
'TTG': 'L', 'CGT': 'R', 'TAA': '*', 'CGC': 'R'
}
sequences = load_sequences( input_file )
peptides = []
for seq in list(sequences.values()):
# --- translate in all frames --- #
frame1 = translate( seq, genetic_code ).split('*')
frame2 = translate( seq[1:], genetic_code ).split('*')
frame3 = translate( seq[2:], genetic_code ).split('*')
rev_seq = revcomp( seq )
frame4 = translate( rev_seq, genetic_code ).split('*')
frame5 = translate( rev_seq[1:], genetic_code ).split('*')
frame6 = translate( rev_seq[2:], genetic_code ).split('*')
# --- pick all peps over length cutoff --- #
for p in frame1+frame2+frame3+frame4+frame5+frame6:
if len( p ) >= min_len_cutoff:
peptides.append( p )
return peptides
def translate_to_generate_pep_file( peptide_file, subject_name_file, subject, min_len_cutoff ):
"""! @brief run in silico translation to generate proper input """
#peptide_file needs to be final output
#mapping table (subject_name_file) needs two columns with identical names
#subject contains input sequences
peptides = translator( subject, min_len_cutoff )
with open( peptide_file, "w" ) as out:
with open( subject_name_file, "w" ) as out2:
for idx, pep in enumerate( peptides ):
out.write( '>X' + str( idx ) + '\n' + pep + '\n' )
out2.write( "X" + str( idx ) + '\t' + "X" + str( idx ) + '\n' )
# --- functions to handle DNA (genome sequence) input --- #
def get_subject_overlap( existing_parts, parts ):
"""! @brief overlap calculator """
start, end = int( parts[6] ), int( parts[7] )
for each in existing_parts:
if each['chr'] == parts[1]:
if each['sstart'] < end:
if each['send'] > start:
return True #overlap with existing HSPs detected
return False #no overlap with existing HSPs
def adjust_input_file( input_file, output_file, name_mapping_table_file ):
"""! @brief generate clean input file """
seqs = load_sequences( input_file )
with open( output_file, "w" ) as out:
with open( name_mapping_table_file, "w" ) as out2:
for kidx, key in enumerate( seqs.keys() ):
out.write( '>Z' + str( kidx+1 ) + '\n' + seqs[ key ].upper() + '\n' )
out.write( '>Z' + str( kidx+1 ) + '_revcomp\n' + revcomp( seqs[ key ] ).upper() + '\n' )
out2.write( key + '\t' + 'Z' + str( kidx+1 ) + '\tZ' + str( kidx+1 ) + '_revcomp\n' )
def query_overlap( existing_parts, new_part, cutoff=3 ):
"""! @brief check for query overlap with existing parts """
overlap = 0
for xeach in existing_parts:
if xeach['qstart'] < new_part['qend']:
if xeach['qend'] > new_part['qstart']:
pos = sorted( [ xeach['qstart'], xeach['qend'], new_part['qend'], new_part['qstart'] ] )
overlap = pos[2]-pos[1]
if overlap > cutoff:
return True #significant overlap detected
return False #no significant overlap detected
def get_gene_groups( parts_per_query, max_gene_size ):
"""! @brief build gene groups based on all BLAST hits per query """
#gene: sstart, send, parts
genes = {}
for hit in parts_per_query: #go through all HSPs
best_gene = [] #list of potential genes to assign the HSP to
for key in list(genes.keys()):
gene = genes[ key ]
if not query_overlap( gene['parts'], hit ):
if hit['sstart'] < gene['send'] and hit['send'] > gene['sstart']: #new part inside gene
best_gene.append( { 'id': key, 'dist': 0 } )
else:
pos = sorted( [ hit['sstart'], gene['send'], hit['send'], gene['sstart'] ] )
dist = pos[2]-pos[1]
if dist <= max_gene_size:
best_gene.append( { 'id': key, 'dist': dist } )
if len( best_gene ) == 0:
genes.update( { len( list(genes.keys()) )+1: { 'chr': hit['chr'],
'sstart': hit['sstart'],
'send': hit['send'],
'parts': [ hit ]
} } )
else:
best_gene = sorted( best_gene, key=itemgetter('dist') )[0]['id']
genes[ best_gene ]['parts'].append( hit )
genes[ best_gene ]['sstart'] = min( [ genes[ best_gene ]['sstart'], hit['sstart'] ] )
genes[ best_gene ]['send'] = min( [ genes[ best_gene ]['send'], hit['send'] ] )
return genes
def load_blast_result( blast_result_file, max_gene_size ):
"""! @brief load BLAST results """
# --- load data per query --- #
data = {}
with open( blast_result_file, "r" ) as f:
line = f.readline()
while line:
parts = line.strip().split('\t')
if int( parts[9] ) > int( parts[8] ): #only consider fw hits
try:
if not get_subject_overlap( data[ parts[0] ], parts ): #include only hits at new places
data[ parts[0] ].append( { 'chr': parts[1],
'qstart': int( parts[6] ),
'qend': int( parts[7] ),
'sstart': int( parts[8] ),
'send': int( parts[9] ),
'score': float( parts[-1] )
} )
except KeyError:
data.update( { parts[0]: [ { 'chr': parts[1],
'qstart': int( parts[6] ),
'qend': int( parts[7] ),
'sstart': int( parts[8] ),
'send': int( parts[9] ),
'score': float( parts[-1] )
} ] } )
line = f.readline()
# --- process data per query --- #
gene_groups_per_query = {}
for query in list(data.keys()):
gene_groups_per_query.update( { query: get_gene_groups( data[ query ], max_gene_size ) } )
return gene_groups_per_query
def extend_to_start( sstart, qstart, send, seq ):
"""! @brief extend sequence to putative start M """
core_seq = seq[ sstart-1:send ]
# --- get sequence up to homolog M --- #
# include complete homologous sequence if no stop codon is present
minimal_extension = []
start = sstart-4
while start >= sstart-1 - 3*(qstart-1):
if seq[ start:start+3 ] not in [ "TAA", "TAG", "TGA" ]:
if not 'N' in seq[ start:start+3 ]:
minimal_extension.append( seq[ start:start+3 ] )
else:
return "".join( minimal_extension[::-1] ) + core_seq
else:
return "".join( minimal_extension[::-1] ) + core_seq
start -= 3
# --- try to get longer sequence --- #
# continue N-terminal part until M or stop codon is reached
# fall back to M in minimal extension if not M reached before stop codon
additional_extension = []
while start >= 0:
if seq[ start:start+3 ] not in [ "TAA", "TAG", "TGA" ]:
if not 'N' in seq[ start:start+3 ]:
additional_extension.append( seq[ start:start+3 ] )
else:
if "ATG" in additional_extension:
return "ATG" + "".join( additional_extension[:additional_extension.index('ATG') ] ) + "".join( minimal_extension[::-1] ) + core_seq
else:
if "ATG" in minimal_extension:
"ATG" + "".join( minimal_extension[:minimal_extension.index('ATG') ] ) + core_seq
else:
"".join( minimal_extension[::-1] ) + core_seq
else:
if "ATG" in additional_extension:
return "ATG" + "".join( additional_extension[:additional_extension.index('ATG') ] ) + "".join( minimal_extension[::-1] ) + core_seq
else:
if "ATG" in minimal_extension:
"ATG" + "".join( minimal_extension[:minimal_extension.index('ATG') ] ) + core_seq
else:
"".join( minimal_extension[::-1] ) + core_seq
start -= 3
return "".join( minimal_extension[::-1] ) + core_seq
def extend_to_stop( sstart, send, qlen, qend, seq ):
"""! @brief extent to stop cdon """
core_seq = seq[ sstart-1:send ]
# --- minimal extension --- #
minimal_extension = []
start = send
while start+3 < len( seq )-3:
if seq[ start:start+3 ] not in [ "TAA", "TAG", "TGA" ]:
if not 'N' in seq[ start:start+3 ]:
minimal_extension.append( seq[ start:start+3 ] )
else:
return core_seq + "".join( minimal_extension ) + seq[start:start+3]
else:
return core_seq + "".join( minimal_extension )+ seq[start:start+3]
start += 3
def get_seq_to_stop( start, seq ):
"""! @brief get additional sequence to stop codon """
extension = []
while start < len( seq )-3:
if seq[ start:start+3 ] not in [ "TAA", "TAG", "TGA" ]:
if not 'N' in seq[ start:start+3 ]:
extension.append( seq[ start:start+3 ] )
else:
return "".join( extension ) + seq[start:start+3]
else:
return "".join( extension ) + seq[start:start+3]
start += 3
def get_from_start_to_stop( sstart, qstart, send, qlen, qend, seq ):
"""! @brief get from start to stop """
core_seq = seq[ sstart-1:send ]
# --- get sequence up to homolog M --- #
# include complete homologous sequence if no stop codon is present
minimal_extension = []
start = sstart-4
while start >= sstart-1 - 3*(qstart-1):
if seq[ start:start+3 ] not in [ "TAA", "TAG", "TGA" ]:
if not 'N' in seq[ start:start+3 ]:
minimal_extension.append( seq[ start:start+3 ] )
else:
return "".join( minimal_extension[::-1] ) + core_seq + get_seq_to_stop( send, seq )
else:
return "".join( minimal_extension[::-1] ) + core_seq + get_seq_to_stop( send, seq )
start -= 3
# --- try to get longer sequence --- #
# continue N-terminal part until M or stop codon is reached
# fall back to M in minimal extension if not M reached before stop codon
additional_extension = []
while start >= 0:
if seq[ start:start+3 ] not in [ "TAA", "TAG", "TGA" ]:
if not 'N' in seq[ start:start+3 ]:
additional_extension.append( seq[ start:start+3 ] )
else:
if "ATG" in additional_extension:
return "ATG" + "".join( additional_extension[:additional_extension.index('ATG') ] ) + "".join( minimal_extension[::-1] ) + core_seq + get_seq_to_stop( send, seq )
else:
if "ATG" in minimal_extension:
"ATG" + "".join( minimal_extension[:minimal_extension.index('ATG') ] ) + core_seq
else:
"".join( minimal_extension[::-1] ) + core_seq
else:
if "ATG" in additional_extension:
return "ATG" + "".join( additional_extension[:additional_extension.index('ATG') ] ) + "".join( minimal_extension[::-1] ) + core_seq + get_seq_to_stop( send, seq )
else:
if "ATG" in minimal_extension:
"ATG" + "".join( minimal_extension[:minimal_extension.index('ATG') ] ) + core_seq + get_seq_to_stop( send, seq )
else:
"".join( minimal_extension[::-1] ) + core_seq + get_seq_to_stop( send, seq )
start -= 3
return "".join( minimal_extension[::-1] ) + core_seq + get_seq_to_stop( send, seq )
def calculate_alignment_sim( candidate, reference ):
"""! @brief calculate alignment similarity (identical residues per ref) """
counter = 0.0
for z, aa in enumerate( candidate ):
if aa != "-" and aa == reference[ z ]:
counter += 1
return counter / len( reference )
def find_missing_seq_between_hits( amino_acids, DNA, genetic_code, tmp_folder, mafft ):
"""! @brief find missing sequence between BLAST hits """
#get all blocks till GT splice site
all_GT_starts = [ m.start() for m in re.finditer( "GT", DNA ) ]
prev_GT_blocks = []
for GTidx in all_GT_starts:
if len( DNA[:GTidx] ) > 0:
prev_GT_blocks.append( DNA[:GTidx] )
#get all blocks following AG splice site
all_AG_starts = [ m.start() for m in re.finditer( "AG", DNA ) ]
following_AG_blocks = []