-
Notifications
You must be signed in to change notification settings - Fork 4
/
allele_calling.py
executable file
·2484 lines (1954 loc) · 132 KB
/
allele_calling.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 argparse
import sys
import io
import os
import re
import statistics
import logging
from logging.handlers import RotatingFileHandler
from datetime import datetime
import glob
import pickle
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
from Bio import Seq
from Bio import pairwise2
from Bio.pairwise2 import format_alignment
from Bio.Blast.Applications import NcbiblastnCommandline
from io import StringIO
from Bio.Blast import NCBIXML
import pandas as pd
import shutil
from progressbar import ProgressBar
from utils.taranis_utils import *
import math
import csv
import plotly.graph_objects as go
def check_blast (reference_allele, sample_files, db_name, logger) : ## N
for s_file in sample_files:
f_name = os.path.basename(s_file).split('.')
dir_name = os.path.dirname(s_file)
blast_dir = os.path.join(dir_name, db_name,f_name[0])
blast_db = os.path.join(blast_dir,f_name[0])
if not os.path.exists(blast_dir) :
logger.error('Blast db folder for sample %s does not exist', f_name)
return False
cline = NcbiblastnCommandline(db=blast_db, evalue=0.001, outfmt=5, max_target_seqs=10, max_hsps=10,num_threads=1, query=reference_allele)
out, err = cline()
psiblast_xml = StringIO(out)
blast_records = NCBIXML.parse(psiblast_xml)
for blast_record in blast_records:
locationcontigs = []
for alignment in blast_record.alignments:
# select the best match
for match in alignment.hsps:
alleleMatchid = int((blast_record.query_id.split("_"))[-1])
return True
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · #
# Parse samples and core genes schema fasta files to dictionary #
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · #
def parsing_fasta_file_to_dict (fasta_file, logger):
fasta_dict = {}
fasta_dict_ordered = {}
for contig in SeqIO.parse(fasta_file, "fasta"):
fasta_dict[str(contig.id)] = str(contig.seq.upper())
logger.debug('file %s parsed to dictionary', fasta_file)
for key in sorted(list(fasta_dict.keys())):
fasta_dict_ordered[key] = fasta_dict[key]
return fasta_dict_ordered
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · #
# Get core genes schema info before allele calling analysis #
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · #
#def prepare_core_gene (core_gene_file_list, store_dir, ref_alleles_dir, logger):
def prepare_core_gene (core_gene_file_list, store_dir, ref_alleles_dir, genus, species, usegenus, logger):
## Initialize dict for keeping id-allele, quality, length variability, length statistics and annotation info for each schema core gene
alleles_in_locus_dict = {}
schema_quality = {}
annotation_core_dict = {}
schema_variability = {}
schema_statistics = {}
## Process each schema core gene
blast_dir = os.path.join(store_dir,'blastdb')
logger.info('start preparation of core genes files')
for fasta_file in core_gene_file_list:
f_name = os.path.basename(fasta_file).split('.')
# Parse core gene fasta file and keep id-sequence info in dictionary
fasta_file_parsed_dict = parsing_fasta_file_to_dict(fasta_file, logger)
if f_name[0] not in alleles_in_locus_dict.keys():
alleles_in_locus_dict[f_name[0]] = {}
alleles_in_locus_dict[f_name[0]] = fasta_file_parsed_dict
# dump fasta file into pickle file
#with open (file_list[-1],'wb') as f:
# pickle.dump(fasta_file_parsed_dict, f)
# Get core gene alleles quality
locus_quality = check_core_gene_quality(fasta_file, logger)
if f_name[0] not in schema_quality.keys():
schema_quality[f_name[0]] = {}
schema_quality[f_name[0]] = locus_quality
# Get gene and product annotation for core gene using reference allele(s)
ref_allele = os.path.join(ref_alleles_dir, f_name[0] + '.fasta')
gene_annot, product_annot = get_gene_annotation (ref_allele, store_dir, genus, species, usegenus, logger)
#gene_annot, product_annot = get_gene_annotation (ref_allele, store_dir, logger)
if f_name[0] not in annotation_core_dict.keys():
annotation_core_dict[f_name[0]] = {}
annotation_core_dict[f_name[0]] = [gene_annot, product_annot]
# Get core gene alleles length to keep length variability and statistics info
alleles_len = []
for allele in fasta_file_parsed_dict :
alleles_len.append(len(fasta_file_parsed_dict[allele]))
#alleles_in_locus = list (SeqIO.parse(fasta_file, "fasta")) ## parse
#for allele in alleles_in_locus : ## parse
#alleles_len.append(len(str(allele.seq))) ## parse
schema_variability[f_name[0]]=list(set(alleles_len))
if len(alleles_len) == 1:
stdev = 0
else:
stdev = statistics.stdev(alleles_len)
schema_statistics[f_name[0]]=[statistics.mean(alleles_len), stdev, min(alleles_len), max(alleles_len)]
return alleles_in_locus_dict, annotation_core_dict, schema_variability, schema_statistics, schema_quality
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · #
# Get Prodigal training file from reference genome for samples gene prediction #
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · #
def prodigal_training(reference_genome_file, prodigal_dir, logger):
f_name = os.path.basename(reference_genome_file).split('.')[0]
prodigal_train_dir = os.path.join(prodigal_dir, 'training')
output_prodigal_train_dir = os.path.join(prodigal_train_dir, f_name + '.trn')
if not os.path.exists(prodigal_train_dir):
try:
os.makedirs(prodigal_train_dir)
logger.debug('Created prodigal directory for training file %s', f_name)
except:
logger.info('Cannot create prodigal directory for training file %s', f_name)
print ('Error when creating the directory %s for training file', prodigal_train_dir)
exit(0)
prodigal_command = ['prodigal' , '-i', reference_genome_file, '-t', output_prodigal_train_dir]
prodigal_result = subprocess.run(prodigal_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# if prodigal_result.stderr:
# logger.error('cannot create training file for %s', f_name)
# logger.error('prodigal returning error code %s', prodigal_result.stderr)
# return False
else:
logger.info('Skeeping prodigal training file creation for %s, as it has already been created', f_name)
return output_prodigal_train_dir
# · * · * · * · * · * · * · * · * · * #
# Get Prodigal sample gene prediction #
# · * · * · * · * · * · * · * · * · * #
def prodigal_prediction(file_name, prodigal_dir, prodigal_train_dir, logger):
f_name = '.'.join(os.path.basename(file_name).split('.')[:-1])
prodigal_dir_sample = os.path.join(prodigal_dir,f_name)
output_prodigal_coord = os.path.join(prodigal_dir_sample, f_name + '_coord.gff') ## no
output_prodigal_prot = os.path.join(prodigal_dir_sample, f_name + '_prot.faa') ## no
output_prodigal_dna = os.path.join(prodigal_dir_sample, f_name + '_dna.faa')
if not os.path.exists(prodigal_dir_sample):
try:
os.makedirs(prodigal_dir_sample)
logger.debug('Created prodigal directory for Core Gene %s', f_name)
except:
logger.info('Cannot create prodigal directory for Core Gene %s' , f_name)
print ('Error when creating the directory %s for prodigal genes prediction', prodigal_dir_sample)
exit(0)
prodigal_command = ['prodigal' , '-i', file_name , '-t', prodigal_train_dir, '-f', 'gff', '-o', output_prodigal_coord, '-a', output_prodigal_prot, '-d', output_prodigal_dna]
prodigal_result = subprocess.run(prodigal_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# if prodigal_result.stderr:
# logger.error('cannot predict genes for %s ', f_name)
# logger.error('prodigal returning error code %s', prodigal_result.stderr)
#return False
else:
logger.info('Skeeping prodigal genes prediction for %s, as it has already been made', f_name)
return True
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * #
# Get Prodigal predicted gene sequence equivalent to BLAST result matching bad quality allele or to no Exact Match BLAST result in allele calling analysis #
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * #
def get_prodigal_sequence(blast_sseq, contig_blast_id, prodigal_directory, sample_name, blast_parameters, logger):
prodigal_directory_sample = os.path.join(prodigal_directory, sample_name)
genes_file = os.path.join(prodigal_directory_sample, sample_name + '_dna.faa')
## Create directory for storing prodigal genes prediction per contig BLAST databases
blastdb_per_contig_directory = 'blastdb_per_contig'
full_path_blastdb_per_contig = os.path.join(prodigal_directory_sample, blastdb_per_contig_directory)
if not os.path.exists(full_path_blastdb_per_contig):
try:
os.makedirs(full_path_blastdb_per_contig)
logger.info('Directory %s has been created', full_path_blastdb_per_contig)
except:
print ('Cannot create the directory ', full_path_blastdb_per_contig)
logger.info('Directory %s cannot be created', full_path_blastdb_per_contig)
exit (0)
## Create directory for storing prodigal genes prediction sequences per contig
prodigal_genes_per_contig_directory = 'prodigal_genes_per_contig'
full_path_prodigal_genes_per_contig = os.path.join(prodigal_directory_sample, prodigal_genes_per_contig_directory)
if not os.path.exists(full_path_prodigal_genes_per_contig):
try:
os.makedirs(full_path_prodigal_genes_per_contig)
logger.info('Directory %s has been created', full_path_prodigal_genes_per_contig)
except:
print ('Cannot create the directory ', full_path_prodigal_genes_per_contig)
logger.info('Directory %s cannot be created', full_path_prodigal_genes_per_contig)
exit (0)
## Parse prodigal genes prediction fasta file
predicted_genes = SeqIO.parse(genes_file, "fasta")
## Create fasta file containing Prodigal predicted genes sequences for X contig in sample
contig_genes_path = os.path.join(full_path_prodigal_genes_per_contig, contig_blast_id + '.fasta')
with open (contig_genes_path, 'w') as out_fh:
for rec in predicted_genes:
contig_prodigal_id = '_'.join((rec.id).split("_")[:-1])
if contig_prodigal_id == contig_blast_id:
out_fh.write ('>' + str(rec.description) + '\n' + str(rec.seq) + '\n')
## Create local BLAST database for Prodigal predicted genes sequences for X contig in sample
if not create_blastdb(contig_genes_path, full_path_blastdb_per_contig, 'nucl', logger):
print('Error when creating the blastdb for samples files. Check log file for more information. \n ')
return False
## Local BLAST Prodigal predicted genes sequences database VS BLAST sequence obtained in sample in allele calling analysis
blast_db_name = os.path.join(full_path_blastdb_per_contig, contig_blast_id, contig_blast_id)
cline = NcbiblastnCommandline(db=blast_db_name, evalue=0.001, perc_identity = 90, outfmt= blast_parameters, max_target_seqs=10, max_hsps=10, num_threads=1)
out, err = cline(stdin = blast_sseq)
out_lines = out.splitlines()
bigger_bitscore = 0
if len (out_lines) > 0 :
for line in out_lines :
values = line.split('\t')
if float(values[8]) > bigger_bitscore:
qseqid , sseqid , pident , qlen , s_length , mismatch , r_gapopen , r_evalue , bitscore , sstart , send , qstart , qend ,sseq , qseq = values
bigger_bitscore = float(bitscore)
## Get complete Prodigal sequence matching allele calling BLAST sequence using ID
predicted_genes_in_contig = SeqIO.parse(contig_genes_path, "fasta")
for rec in predicted_genes_in_contig:
if rec.id == sseqid:
predicted_gene_sequence = str(rec.seq)
start_prodigal = str(rec.description.split( '#')[1])
end_prodigal = str(rec.description.split('#')[2])
break
## Sequence not found by Prodigal when there are no BLAST results matching allele calling BLAST sequence
if len (out_lines) == 0:
predicted_gene_sequence = 'Sequence not found by Prodigal'
start_prodigal = '-'
end_prodigal = '-'
return predicted_gene_sequence, start_prodigal, end_prodigal ### start_prodigal y end_prodigal para report prodigal
# · * · * · * · * · * · * · * · * · * · * · * · * #
# Get samples info before allele calling analysis #
# · * · * · * · * · * · * · * · * · * · * · * · * #
def prepare_samples(sample_file_list, store_dir, reference_genome_file, logger):
## Initialize dictionary for keeping id-contig
contigs_in_sample_dict = {}
## Paths for samples blastdb, Prodigal genes prediction and BLAST results
blast_dir = os.path.join(store_dir,'blastdb')
prodigal_dir = os.path.join(store_dir,'prodigal')
blast_results_seq_dir = os.path.join(store_dir,'blast_results', 'blast_results_seq')
## Get training file for Prodigal genes prediction
output_prodigal_train_dir = prodigal_training(reference_genome_file, prodigal_dir, logger)
if not output_prodigal_train_dir:
print('Error when creating training file for genes prediction. Check log file for more information. \n ')
return False
for fasta_file in sample_file_list:
f_name = '.'.join(os.path.basename(fasta_file).split('.')[:-1])
# Get samples id-contig dictionary
fasta_file_parsed_dict = parsing_fasta_file_to_dict(fasta_file, logger)
if f_name not in contigs_in_sample_dict.keys():
contigs_in_sample_dict[f_name] = {}
contigs_in_sample_dict[f_name] = fasta_file_parsed_dict
# dump fasta file into pickle file
#with open (file_list[-1],'wb') as f: # generación de diccionarios de contigs para cada muestra
# pickle.dump(fasta_file_parsed_dict, f)
# Create directory for storing BLAST results using reference allele(s)
blast_results_seq_per_sample_dir = os.path.join(blast_results_seq_dir, f_name)
if not os.path.exists(blast_results_seq_per_sample_dir):
try:
os.makedirs(blast_results_seq_per_sample_dir)
logger.debug('Created blast results directory for sample %s', f_name)
except:
logger.info('Cannot create blast results directory for sample %s', f_name)
print ('Error when creating the directory for blast results', blast_results_seq_per_sample_dir)
exit(0)
# Prodigal genes prediction for each sample
if not prodigal_prediction(fasta_file, prodigal_dir, output_prodigal_train_dir, logger):
print('Error when predicting genes for samples files. Check log file for more information. \n ')
return False
# Create local BLAST db for each sample fasta file
if not create_blastdb(fasta_file, blast_dir, 'nucl', logger):
print('Error when creating the blastdb for samples files. Check log file for more information. \n ')
return False
return contigs_in_sample_dict
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * #
# Get established length thresholds for allele tagging in allele calling analysis #
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * #
def length_thresholds(core_name, schema_statistics, percent): ### logger
locus_mean = int(schema_statistics[core_name][0])
if percent != "SD":
max_length_threshold = math.ceil(locus_mean + ((locus_mean * float(percent)) / 100))
min_length_threshold = math.floor(locus_mean - ((locus_mean * float(percent)) / 100))
else:
percent = float(schema_statistics[core_name][1])
max_length_threshold = math.ceil(locus_mean + (locus_mean * percent))
min_length_threshold = math.floor(locus_mean - (locus_mean * percent))
return max_length_threshold, min_length_threshold
# · * · * · * · * · * · * · * · * · * · * · #
# Convert dna sequence to protein sequence #
# · * · * · * · * · * · * · * · * · * · * · #
def convert_to_protein (sequence) :
seq = Seq.Seq(sequence)
protein = str(seq.translate())
return protein
# · * · * · * · * · * · * · * · * · * · * · * · * · * #
# Get SNPs between BLAST sequence and matching allele #
# · * · * · * · * · * · * · * · * · * · * · * · * · * #
def get_snp (sample, query) :
prot_annotation = {'S': 'polar' ,'T': 'polar' ,'Y': 'polar' ,'Q': 'polar' ,'N': 'polar' ,'C': 'polar' ,'S': 'polar' ,
'F': 'nonpolar' ,'L': 'nonpolar','I': 'nonpolar','M': 'nonpolar','P': 'nonpolar','V': 'nonpolar','A': 'nonpolar','W': 'nonpolar','G': 'nonpolar',
'D' : 'acidic', 'E' :'acidic',
'H': 'basic' , 'K': 'basic' , 'R' : 'basic',
'-': '-----', '*' : 'Stop codon'}
snp_list = []
sample = sample.replace('-','')
#length = max(len(sample), len(query))
length = len(query)
# normalize the length of the sample for the iteration
if len(sample) < length :
need_to_add = length - len(sample)
sample = sample + need_to_add * '-'
# convert to Seq class to translate to protein
seq_sample = Seq.Seq(sample)
seq_query = Seq.Seq(query)
for index in range(length):
if seq_query[index] != seq_sample[index] :
triple_index = index - (index % 3)
codon_seq = seq_sample[triple_index : triple_index + 3]
codon_que = seq_query[triple_index : triple_index + 3]
if not '-' in str(codon_seq) :
prot_seq = str(codon_seq.translate())
prot_que = str(codon_que.translate())
else:
prot_seq = '-'
prot_que = str(seq_query[triple_index: ].translate())
if prot_annotation[prot_que[0]] == prot_annotation[prot_seq[0]] :
missense_synonym = 'Synonymous'
elif prot_seq == '*' :
missense_synonym = 'Nonsense'
else:
missense_synonym = 'Missense'
#snp_list.append([str(index+1),str(seq_sample[index]) + '/' + str(seq_query[index]), str(codon_seq) + '/'+ str(codon_que),
snp_list.append([str(index+1),str(seq_query[index]) + '/' + str(seq_sample[index]), str(codon_que) + '/'+ str(codon_seq),
# when one of the sequence ends but not the other we will translate the remain sequence to proteins
# in that case we will only annotate the first protein. Using [0] as key of the dictionary annotation
prot_que + '/' + prot_seq, missense_synonym, prot_annotation[prot_que[0]] + ' / ' + prot_annotation[prot_seq[0]]])
if '-' in str(codon_seq) :
break
return snp_list
def nucleotide_to_protein_alignment (sample_seq, query_seq ) : ### Sustituido por get_alignment
aligment = []
sample_prot = convert_to_protein(sample_seq)
query_prot = convert_to_protein(query_seq)
minimun_length = min(len(sample_prot), len(query_prot))
for i in range(minimun_length):
if sample_prot[i] == query_prot[i] :
aligment.append('|')
else:
aligment.append(' ')
protein_alignment = [['sample', sample_prot],['match', ''.join(aligment)], ['schema', query_prot]]
return protein_alignment
def get_alignment_for_indels (blast_db_name, qseq) : ### Sustituido por get_alignment
#match_alignment =[]
cline = NcbiblastnCommandline(db=blast_db_name, evalue=0.001, perc_identity = 80, outfmt= 5, max_target_seqs=10, max_hsps=10,num_threads=1)
out, err = cline(stdin = qseq)
psiblast_xml = StringIO(out)
blast_records = NCBIXML.parse(psiblast_xml)
for blast_record in blast_records:
for alignment in blast_record.alignments:
for match in alignment.hsps:
match_alignment = [['sample', match.sbjct],['match', match.match], ['schema',match.query]]
return match_alignment
def get_alignment_for_deletions (sample_seq, query_seq): ### Sustituido por get_alignment
index_found = False
alignments = pairwise2.align.globalxx(sample_seq, query_seq)
for index in range(len(alignments)) :
if alignments[index][4] == len(query_seq) :
index_found = True
break
if not index_found :
index = 0
values = format_alignment(*alignments[index]).split('\n')
match_alignment = [['sample', values[0]],['match', values[1]], ['schema',values[2]]]
return match_alignment
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * #
# Get DNA and protein alignment between the final sequence found in the sample and the matching allele #
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * #
def get_alignment (sample_seq, query_seq, reward, penalty, gapopen, gapextend, seq_type = "dna"):
## If sequences alignment type desired is "protein" convert dna sequences to protein
if seq_type == "protein":
sample_seq = convert_to_protein(sample_seq)
query_seq = convert_to_protein(query_seq)
## Get dna/protein alignment between final sequence found and matching allele
# arguments pairwise2.align.globalms: match, mismatch, gap opening, gap extending
alignments = pairwise2.align.localms(sample_seq, query_seq, reward, penalty, -gapopen, -gapextend)
values = format_alignment(*alignments[0]).split('\n')
match_alignment = [['sample', values[0]],['match', values[1]], ['schema',values[2]]]
return match_alignment
# · * · * · * · * · * · * · * · * #
# Tag LNF cases and keep LNF info #
# · * · * · * · * · * · * · * · * #
def lnf_tpr_tag(core_name, sample_name, alleles_in_locus_dict, samples_matrix_dict, lnf_tpr_dict, schema_statistics, locus_alleles_path, qseqid, pident, s_length, new_sequence_length, perc_identity_ref, coverage, schema_quality, annotation_core_dict, count_dict, logger):
gene_annot, product_annot = annotation_core_dict[core_name]
if qseqid == '-':
samples_matrix_dict[sample_name].append('LNF')
tag_report = 'LNF'
matching_allele_length = '-'
else:
if new_sequence_length == '-':
samples_matrix_dict[sample_name].append('LNF_' + str(qseqid))
tag_report = 'LNF'
else:
samples_matrix_dict[sample_name].append('TPR_' + str(qseqid))
tag_report = 'TPR'
matching_allele_seq = alleles_in_locus_dict[core_name][qseqid]
matching_allele_length = len(matching_allele_seq)
#alleles_in_locus = list (SeqIO.parse(locus_alleles_path, "fasta")) ## parse
#for allele in alleles_in_locus : ## parse
#if allele.id == qseqid : ## parse
#break ## parse
#matching_allele_seq = str(allele.seq) ## parse
#matching_allele_length = len(matching_allele_seq) ## parse
if pident == '-':
# (los dos BLAST sin resultado)
coverage_blast = '-'
coverage_new_sequence = '-'
add_info = 'Locus not found'
logger.info('Locus not found at sample %s, for gene %s', sample_name, core_name)
# Get allele quality
allele_quality = '-'
# (recuento tags para plot)
count_dict[sample_name]['not_found'] += 1
count_dict[sample_name]['total'] += 1
elif 90 > float(pident):
# (BLAST 90 sin resultado y BLAST 70 con resultado)
coverage_blast = '-'
coverage_new_sequence = '-'
add_info = 'BLAST sequence ID under threshold: {}%'.format(perc_identity_ref)
logger.info('BLAST sequence ID %s under threshold at sample %s, for gene %s', pident, sample_name, core_name)
# Get allele quality
allele_quality = '-'
# (recuento tags para plot)
count_dict[sample_name]['low_id'] += 1
count_dict[sample_name]['total'] += 1
elif 90 <= float(pident) and new_sequence_length == '-':
# (BLAST 90 con resultado, bajo coverage BLAST)
locus_mean = int(schema_statistics[core_name][0])
coverage_blast = int(s_length) / locus_mean
#coverage_blast = int(s_length) / matching_allele_length
coverage_new_sequence = '-'
if coverage_blast < 1:
add_info = 'BLAST sequence coverage under threshold: {}%'.format(coverage)
else:
add_info = 'BLAST sequence coverage above threshold: {}%'.format(coverage)
logger.info('BLAST sequence coverage %s under threshold at sample %s, for gene %s', coverage_blast, sample_name, core_name)
# Get allele quality
allele_quality = '-'
# (recuento tags para plot)
count_dict[sample_name]['low_coverage'] += 1
count_dict[sample_name]['total'] += 1
elif 90 <= float(pident) and new_sequence_length != '-':
# (BLAST 90 con resultado, buen coverage BLAST, bajo coverage new_sseq)
locus_mean = int(schema_statistics[core_name][0])
coverage_blast = int(s_length) / locus_mean * 100
#coverage_blast = int(s_length) / matching_allele_length
coverage_new_sequence = new_sequence_length / matching_allele_length * 100
if coverage_new_sequence < 1:
add_info = 'New sequence coverage under threshold: {}%'.format(coverage)
else:
add_info = 'New sequence coverage above threshold: {}%'.format(coverage)
logger.info('New sequence coverage %s under threshold at sample %s, for gene %s', coverage_new_sequence, sample_name, core_name)
# Get allele quality
allele_quality = schema_quality[core_name][qseqid]
# (recuento tags para plot)
count_dict[sample_name]['total'] += 1
for count_class in count_dict[sample_name]:
if count_class in allele_quality:
count_dict[sample_name][count_class] += 1
#if "bad_quality" in allele_quality:
# count_dict[sample_name]['bad_quality'] += 1
## Keeping LNF and TPR report info
if not core_name in lnf_tpr_dict:
lnf_tpr_dict[core_name] = {}
if not sample_name in lnf_tpr_dict[core_name]:
lnf_tpr_dict[core_name][sample_name] = []
lnf_tpr_dict[core_name][sample_name].append([gene_annot, product_annot, tag_report, qseqid, allele_quality, pident, str(coverage_blast), str(coverage_new_sequence), str(matching_allele_length), str(s_length), str(new_sequence_length), add_info]) ### Meter secuencias alelo, blast y new_sseq (si las hay)?
return True
# · * · * · * · * · * · * · * · * · * · * · * · * #
# Tag paralog and exact match cases and keep info #
# · * · * · * · * · * · * · * · * · * · * · * · * #
def paralog_exact_tag(sample_name, core_name, tag, schema_quality, matching_genes_dict, samples_matrix_dict, allele_found, tag_dict, prodigal_report, prodigal_directory, blast_parameters, annotation_core_dict, count_dict, logger):
logger.info('Found %s at sample %s for core gene %s ', tag, sample_name, core_name)
paralog_quality_count = [] # (lista para contabilizar parálogos debido a bad o good quality)
gene_annot, product_annot = annotation_core_dict[core_name]
if not sample_name in tag_dict :
tag_dict[sample_name] = {}
if not core_name in tag_dict[sample_name] :
tag_dict[sample_name][core_name]= []
if tag == 'EXACT':
allele = list(allele_found.keys())[0]
qseqid = allele_found[allele][0]
tag = qseqid
samples_matrix_dict[sample_name].append(tag)
for sequence in allele_found:
qseqid, sseqid, pident, qlen, s_length, mismatch, r_gapopen, r_evalue, bitscore, sstart, send, qstart, qend, sseq, qseq = allele_found[sequence]
sseq = sseq.replace('-', '')
# Get allele quality
allele_quality = schema_quality[core_name][qseqid]
if len(allele_found) > 1:
paralog_quality_count.append(allele_quality)
# Get prodigal gene prediction if allele quality is 'bad_quality'
if 'bad_quality' in allele_quality:
complete_predicted_seq, start_prodigal, end_prodigal = get_prodigal_sequence(sseq, sseqid, prodigal_directory, sample_name, blast_parameters, logger)
##### informe prodigal #####
prodigal_report.append([core_name, sample_name, qseqid, tag, sstart, send, start_prodigal, end_prodigal, sseq, complete_predicted_seq])
else:
complete_predicted_seq = '-'
if not sseqid in matching_genes_dict[sample_name] :
matching_genes_dict[sample_name][sseqid] = []
if sstart > send :
#matching_genes_dict[sample_name][sseqid].append([core_name, sstart, send,'-', tag])
matching_genes_dict[sample_name][sseqid].append([core_name, qseqid, sstart, send,'-', tag])
else:
#matching_genes_dict[sample_name][sseqid].append([core_name, sstart, send,'+', tag])
matching_genes_dict[sample_name][sseqid].append([core_name, qseqid, sstart, send,'+', tag])
## Keeping paralog NIPH/NIPHEM report info
if tag == 'NIPH' or tag == 'NIPHEM':
tag_dict[sample_name][core_name].append([gene_annot, product_annot, tag, pident, qseqid, allele_quality, sseqid, bitscore, sstart, send, sseq, complete_predicted_seq])
else:
tag_dict[sample_name][core_name] = [gene_annot, product_annot, qseqid, allele_quality, sseqid, s_length, sstart, send, sseq, complete_predicted_seq]
# (recuento tags para plot)
count_dict[sample_name]['total'] += 1
for count_class in count_dict[sample_name]:
if count_class in allele_quality:
if "no_start_stop" not in count_class and "no_start_stop" in allele_quality:
if count_class == "bad_quality":
count_dict[sample_name][count_class] += 1
else:
count_dict[sample_name][count_class] += 1
# (recuento tags para plot (parálogos))
if len(allele_found) > 0:
count = 0
for paralog_quality in paralog_quality_count:
count += 1
if "bad_quality" in paralog_quality:
count_dict[sample_name]['total'] += 1
for count_class in count_dict[sample_name]:
if count_class in paralog_quality:
if "no_start_stop" not in count_class and "no_start_stop" in paralog_quality:
if count_class == "bad_quality":
count_dict[sample_name][count_class] += 1
else:
next
else:
count_dict[sample_name][count_class] += 1
break
else:
if count == len(paralog_quality_count):
count_dict[sample_name]['total'] += 1
count_dict[sample_name]['good_quality'] += 1
return True
# · * · * · * · * · * · * · * · * · * · * #
# Tag INF/ASM/ALM/PLOT cases and keep info #
# · * · * · * · * · * · * · * · * · * · * #
def inf_asm_alm_tag(core_name, sample_name, tag, blast_values, allele_quality, new_sseq, matching_allele_length, tag_dict, list_tag, samples_matrix_dict, matching_genes_dict, prodigal_report, start_prodigal, end_prodigal, complete_predicted_seq, annotation_core_dict, count_dict, logger):
gene_annot, product_annot = annotation_core_dict[core_name]
qseqid, sseqid, pident, qlen, s_length, mismatch, r_gapopen, r_evalue, bitscore, sstart, send, qstart, qend, sseq, qseq = blast_values
sseq = sseq.replace('-', '')
s_length = len(sseq)
new_sequence_length = len(new_sseq)
logger.info('Found %s at sample %s for core gene %s ', tag, sample_name, core_name)
if tag == 'PLOT':
tag_allele = tag + '_' + str(qseqid)
else:
# Adding ASM/ALM/INF allele to the allele_matrix if it is not already include
if not core_name in tag_dict:
tag_dict[core_name] = []
if not new_sseq in tag_dict[core_name] :
tag_dict[core_name].append(new_sseq)
# Find the index of ASM/ALM/INF to include it in the sample matrix dict
index_tag = tag_dict[core_name].index(new_sseq)
tag_allele = tag + '_' + core_name + '_' + str(qseqid) + '_' + str(index_tag)
samples_matrix_dict[sample_name].append(tag_allele)
# Keeping INF/ASM/ALM/PLOT report info
if not core_name in list_tag :
list_tag[core_name] = {}
if not sample_name in list_tag[core_name] :
list_tag[core_name][sample_name] = {}
if tag == 'INF':
list_tag[core_name][sample_name][tag_allele] = [gene_annot, product_annot, qseqid, allele_quality, sseqid, bitscore, str(matching_allele_length), str(s_length), str(new_sequence_length), mismatch , r_gapopen, sstart, send, new_sseq, complete_predicted_seq]
# (recuento tags para plots)
count_dict[sample_name]['total'] += 1
for count_class in count_dict[sample_name]:
if count_class in allele_quality:
count_dict[sample_name][count_class] += 1
#if "bad_quality" in allele_quality:
# count_dict[sample_name]['bad_quality'] += 1
elif tag == 'PLOT':
list_tag[core_name][sample_name] = [gene_annot, product_annot, qseqid, allele_quality, sseqid, bitscore, sstart, send, sseq, new_sseq]
# (recuento tags para plots)
count_dict[sample_name]['total'] += 1
else :
if tag == 'ASM':
newsseq_vs_blastseq = 'shorter'
elif tag == 'ALM':
newsseq_vs_blastseq = 'longer'
if len(sseq) < matching_allele_length:
add_info = 'Global effect: DELETION. BLAST sequence length shorter than matching allele sequence length / Net result: ' + tag + '. Final gene sequence length ' + newsseq_vs_blastseq + ' than matching allele sequence length'
elif len(sseq) == matching_allele_length:
add_info = 'Global effect: BASE SUBSTITUTION. BLAST sequence length equal to matching allele sequence length / Net result: ' + tag + '. Final gene sequence length ' + newsseq_vs_blastseq + ' than matching allele sequence length'
elif len(sseq) > matching_allele_length:
add_info = 'Global effect: INSERTION. BLAST sequence length longer than matching allele sequence length / Net result: ' + tag + '. Final gene sequence length ' + newsseq_vs_blastseq + ' than matching allele sequence length'
list_tag[core_name][sample_name][tag_allele] = [gene_annot, product_annot, qseqid, allele_quality, sseqid, bitscore, str(matching_allele_length), str(s_length), str(new_sequence_length), mismatch , r_gapopen, sstart, send, new_sseq, add_info, complete_predicted_seq]
# (recuento tags para plots)
if tag == 'ASM':
count_dict[sample_name]['total'] += 1
for mut_type in count_dict[sample_name]:
if mut_type in add_info.lower():
count_dict[sample_name][mut_type] += 1
elif tag == 'ALM':
count_dict[sample_name]['total'] += 1
for mut_type in count_dict[sample_name]:
if mut_type in add_info.lower():
count_dict[sample_name][mut_type] += 1
if not sseqid in matching_genes_dict[sample_name] :
matching_genes_dict[sample_name][sseqid] = []
if sstart > send :
#matching_genes_dict[sample_name][sseqid].append([core_name, str(int(sstart)-new_sequence_length -1), sstart,'-', tag_allele])
matching_genes_dict[sample_name][sseqid].append([core_name, qseqid, str(int(sstart)-new_sequence_length -1), sstart,'-', tag_allele])
else:
#matching_genes_dict[sample_name][sseqid].append([core_name, sstart, str(int(sstart)+ new_sequence_length),'+', tag_allele])
matching_genes_dict[sample_name][sseqid].append([core_name, qseqid, sstart, str(int(sstart)+ new_sequence_length),'+', tag_allele])
##### informe prodigal #####
prodigal_report.append([core_name, sample_name, qseqid, tag_allele, sstart, send, start_prodigal, end_prodigal, sseq, complete_predicted_seq])
return True
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · #
# Keep best results info after BLAST using results from previous reference allele BLAST as database VS ALL alleles in locus as query in allele calling analysis #
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · * · #
def get_blast_results (sample_name, values, contigs_in_sample_dict, allele_found, logger) :
qseqid, sseqid, pident, qlen, s_length, mismatch, r_gapopen, r_evalue, bitscore, sstart, send, qstart, qend, sseq, qseq = values
## Get contig ID and BLAST sequence
sseqid_blast = "_".join(sseqid.split('_')[1:])
sseq_no_gaps = sseq.replace('-', '')
## Get start and end positions in contig searching for BLAST sequence index in contig sequence
# Get contig sequence
accession_sequence = contigs_in_sample_dict[sample_name][sseqid_blast]
#for record in sample_contigs: ## parse
#if record.id == sseqid_blast : ## parse
#break ## parse
#accession_sequence = str(record.seq) ## parse
# Try to get BLAST sequence index in contig. If index -> error because different contig sequence and BLAST sequence
# direction, obtain reverse complement BLAST sequence and try again.
try:
sseq_index_1 = int(accession_sequence.index(sseq_no_gaps)) + 1
except:
sseq_no_gaps = str(Seq.Seq(sseq_no_gaps).reverse_complement())
sseq_index_1 = int(accession_sequence.index(sseq_no_gaps)) + 1
sseq_index_2 = int(sseq_index_1) + len(sseq_no_gaps) - 1
# Assign found indexes to start and end possitions depending on BLAST sequence and allele sequence direction
if int(sstart) < int(send):
sstart_new = str(min(sseq_index_1, sseq_index_2))
send_new = str(max(sseq_index_1, sseq_index_2))
else:
sstart_new = str(max(sseq_index_1, sseq_index_2))
send_new = str(min(sseq_index_1, sseq_index_2))
## Keep BLAST results info discarding subsets
allele_is_subset = False
if len(allele_found) > 0 :
for allele_id in allele_found :
min_index = min(int(allele_found[allele_id][9]), int(allele_found[allele_id][10]))
max_index = max(int(allele_found[allele_id][9]), int(allele_found[allele_id][10]))
if int(sstart_new) in range(min_index, max_index + 1) or int(send_new) in range(min_index, max_index + 1): # if both genome locations overlap
if sseqid_blast == allele_found[allele_id][1]: # if both sequences are in the same contig
logger.info('Found allele %s that starts or ends at the same position as %s ' , qseqid, allele_id)
allele_is_subset = True
break
if len(allele_found) == 0 or not allele_is_subset :
contig_id_start = str(sseqid_blast + '_'+ sstart_new)
# Skip the allele found in the 100% identity and 100% alignment
if not contig_id_start in allele_found:
allele_found[contig_id_start] = [qseqid, sseqid_blast, pident, qlen, s_length, mismatch, r_gapopen, r_evalue, bitscore, sstart_new, send_new, '-', '-', sseq, qseq]
return True
# · * · * · * · * · * · * · * · * · * · #
# Get SNPs and ADN and protein alignment #
# · * · * · * · * · * · * · * · * · * · #
def keep_snp_alignment_info(sseq, new_sseq, matching_allele_seq, qseqid, query_direction, core_name, sample_name, reward, penalty, gapopen, gapextend, snp_dict, match_alignment_dict, protein_dict, logger):
## Check allele sequence direction
if query_direction == 'reverse':
matching_allele_seq = str(Seq.Seq(matching_allele_seq).reverse_complement())
else:
matching_allele_seq = str(matching_allele_seq)
## Get the SNP information
snp_information = get_snp(sseq, matching_allele_seq)
if len(snp_information) > 0 :
if not core_name in snp_dict :
snp_dict[core_name] = {}
if not sample_name in snp_dict[core_name] :
snp_dict[core_name][sample_name] = {}
snp_dict[core_name][sample_name][qseqid]= snp_information
## Get new sequence-allele sequence dna alignment
if not core_name in match_alignment_dict :
match_alignment_dict[core_name] = {}
if not sample_name in match_alignment_dict[core_name] :
match_alignment_dict[core_name][sample_name] = get_alignment (new_sseq, matching_allele_seq, reward, penalty, gapopen, gapextend)
## Get new sequence-allele sequence protein alignment
if not core_name in protein_dict :
protein_dict[core_name] = {}
if not sample_name in protein_dict[core_name] :
protein_dict[core_name][sample_name] = []
protein_dict[core_name][sample_name] = get_alignment (new_sseq, matching_allele_seq, reward, penalty, gapopen, gapextend, "protein")
return True
# · * · * · * · * · * · * · * · * · * · * · #
# Create allele tag summary for each sample #
# · * · * · * · * · * · * · * · * · * · * · #
def create_summary (samples_matrix_dict, logger) :
summary_dict = {}
summary_result_list = []
summary_heading_list = ['Exact match', 'INF', 'ASM', 'ALM', 'LNF', 'TPR', 'NIPH', 'NIPHEM', 'PLOT', 'ERROR']
summary_result_list.append('File\t' + '\t'.join(summary_heading_list))
for key in sorted (samples_matrix_dict) :
summary_dict[key] = {'Exact match':0, 'INF':0, 'ASM':0, 'ALM':0, 'LNF':0, 'TPR':0,'NIPH':0, 'NIPHEM':0, 'PLOT':0, 'ERROR':0}
for values in samples_matrix_dict[key] :
if 'INF_' in values :
summary_dict[key]['INF'] += 1
elif 'ASM_' in values :
summary_dict[key]['ASM'] += 1
elif 'ALM_' in values :
summary_dict[key]['ALM'] += 1
elif 'LNF' in values :
summary_dict[key]['LNF'] += 1
elif 'TPR' in values :
summary_dict[key]['TPR'] += 1
elif 'NIPH' == values :
summary_dict[key]['NIPH'] += 1
elif 'NIPHEM' == values :
summary_dict[key]['NIPHEM'] += 1
elif 'PLOT' in values :
summary_dict[key]['PLOT'] += 1
elif 'ERROR' in values :
summary_dict[key]['ERROR'] += 1
else:
try:
number = int(values)
summary_dict[key]['Exact match'] +=1
except:
if '_' in values :
tmp_value = values
try:
number = int(tmp_value[-1])
summary_dict[key]['Exact match'] +=1
except:
logger.debug('The value %s, was found when collecting summary information for the %s', values, summary_dict[key] )
else:
logger.debug('The value %s, was found when collecting summary information for the %s', values, summary_dict[key] )
summary_sample_list = []
for item in summary_heading_list :
summary_sample_list.append(str(summary_dict[key][item]))
summary_result_list.append(key + '\t' +'\t'.join(summary_sample_list))
return summary_result_list
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · #
# Get gene and product annotation for core gene using Prokka #
# · * · * · * · * · * · * · * · * · * · * · * · * · * · * · #
### (tsv para algunos locus? Utils para analyze schema?)
def get_gene_annotation (annotation_file, annotation_dir, genus, species, usegenus, logger) :
name_file = os.path.basename(annotation_file).split('.')
annotation_dir = os.path.join (annotation_dir, 'annotation', name_file[0])
if usegenus == 'true':
annotation_result = subprocess.run (['prokka', annotation_file, '--outdir', annotation_dir,
'--genus', genus, '--species', species, '--usegenus',
'--gcode', '11', '--prefix', name_file[0], '--quiet'])
elif usegenus == 'false':
annotation_result = subprocess.run (['prokka', annotation_file, '--outdir', annotation_dir,
'--genus', genus, '--species', species,
'--gcode', '11', '--prefix', name_file[0], '--quiet'])
annot_tsv = []
tsv_path = os.path.join (annotation_dir, name_file[0] + '.tsv')
try:
with open(tsv_path) as tsvfile:
tsvreader = csv.reader(tsvfile, delimiter="\t")
for line in tsvreader:
annot_tsv.append(line)
if len(annot_tsv) > 1:
gene_index = annot_tsv[0].index("gene")
product_index = annot_tsv[0].index("product")
try:
if '_' in annot_tsv[1][2]:
gene_annot = annot_tsv[1][gene_index].split('_')[0]
else:
gene_annot = annot_tsv[1][gene_index]
except:
gene_annot = 'Not found by Prokka'
try:
product_annot = annot_tsv[1][product_index]
except:
product_annot = 'Not found by Prokka'
else:
gene_annot = 'Not found by Prokka'
product_annot = 'Not found by Prokka'
except: