-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathScript2.py
More file actions
1723 lines (1480 loc) · 71.7 KB
/
Script2.py
File metadata and controls
1723 lines (1480 loc) · 71.7 KB
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
from time import sleep as sl
import os
import shutil
import itertools
import sys
from os import path
from Bio import SeqIO
import re
from copy import deepcopy
import time
from allele_MLST_caller import IO,wrappers,utils
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
def hsp_filter_ok(hsp,length,fraction_snps_diff):
ncount = 0
for pos in range(hsp.align_length-1):
if hsp.query[pos] == "N" or hsp.sbjct[pos] == "N":
ncount +=1
if hsp.align_length > length:
if (float(hsp.identities+hsp.gaps+ncount) / hsp.align_length) > fraction_snps_diff:
return True
return False
def make_intact_allele_fasta(scheme_fastas,dbname,all_alleles,allele_subset_dict,scheme):
"""
:param scheme_fastas: fasta file paths for scheme of interest
:param dbname: output fasta path
:param all_alleles
:param allele_subset_dict
:param scheme
:return:fasta file with all intact alleles derived from fasta files of loci making up a scheme
also return dict of {locus:(list of intact alleles,list of all alleles)}
"""
alleles_dict = {}
ref_alleles = {}
allele_seqs = {}
outseqs = []
c=0
all = 0
for fname in scheme_fastas:
t=0
infile = SeqIO.parse(fname,"fasta")
intact = []
allalleles = []
locus = fname.split("/")[-1].replace(".fasta","")
for allele in infile:
# if t ==1:print(allele,all_alleles)
allele_seqs[allele.id] = str(allele.seq)
all_alleles2 = bool(all_alleles)
if not all_alleles:
# print(allele_subset_dict[scheme][locus])
allele_nos = list(set(allele_subset_dict[scheme][locus]))
allele_nos = [x.split(":")[-1] for x in allele_nos]
if allele_nos[0] == "0" and len(allele_nos) == 1:
all_alleles2 = True
if "-" not in allele.id and allele.id != "0":
#outseqs.append(allele)
intactno = allele.id.split(":")[-1]
if all_alleles2:
outseqs.append(allele)
else:
if allele.id in allele_subset_dict[scheme][locus]:
outseqs.append(allele)
intact.append(intactno)
allalleles.append(intactno)
c+=1
all+=1
else:
alleleno = allele.id.split(":")[-1]
# intac = allele.id.split(":")[-1].split("_")[0][1:]
# intact.append(intac)
allalleles.append(alleleno)
all+=1
if allele.id.split(":")[-1] == "1":
ref_alleles[locus] = str(allele.seq)
# outseqs.append(allele)
# intact.append("1")
# allalleles.append("1")
alleles_dict[locus] = (intact,allalleles)
#FIXME srites out temporary fasta file for BLASTING against for each scheme
SeqIO.write(outseqs,dbname,"fasta")
return alleles_dict, ref_alleles, allele_seqs
def call_indels(locus,hsp,indels_calls):
unknown_allele = hsp.query
ref_allele = hsp.sbjct
matches = hsp.match
refstart = hsp.sbjct_start
refend = hsp.sbjct_end
if int(hsp.sbjct_start) > int(hsp.sbjct_end):
unknown_allele = utils.reverse_complement(unknown_allele)
ref_allele = utils.reverse_complement(ref_allele)
matches = matches[::-1]
refstart, refend = refend, refstart
intact_nucs = ["A", "T", "G", "C", "a", "t", "c", "g"]
for i in range(len(unknown_allele)):
if matches[i] == " ":
if unknown_allele[i] == "-" and ref_allele[i] in intact_nucs:
pos = i - ref_allele[:i].count("-")
pos_rel_to_ref_allele = pos + refstart - 1
d = (ref_allele[i], str(pos_rel_to_ref_allele), "del")
if locus not in indels_calls:
indels_calls[locus] = []
indels_calls[locus].append(d)
# TODO INDEL REMOVE Below replaces deletion in unknown allele with reference nucleotides to IGNORE DELETIONS
elif unknown_allele[i] in intact_nucs and ref_allele[i] == "-":
pos = i - ref_allele[:i].count("-")
pos_rel_to_ref_allele = pos + refstart - 1
ins = ("ins", str(pos_rel_to_ref_allele), unknown_allele[i])
if locus not in indels_calls:
indels_calls[locus] = []
indels_calls[locus].append(ins)
# TODO INDEL REMOVE No addition of unknown allele seq if insertion in new allele
return indels_calls
def get_exactmatches(blasthits,partial_hit,allele_sizes,hit_locations,indels,ref_called_alleles,hsp_thresh):
"""
:param blasthits: parsed blast output as list of qury seq results
:param partial_hit:list of loci, when an exact hit is found it is removed from list - resulting in a list of loci still to be examined
:param allele_sizes: allele lengths of reference alleles
:param hit_locations
:return: alleles that match exactly for length with no gaps and 100% identity - one for each locus - alleles with Ns are ignored
"""
#TODO CKHECK IF NECESSARY make so if perfect hit to 2 alleles (because of 2 alleles w diff sizes) store both and select hit with largest score - also check that 2 hits are in same locus otherwise 2 diff alleles in one strain - call as 0
exacthits = 0
totalhits = 0
perfect_hit_ls = {}
for result in blasthits:
contig_hit = result.query.split(" ")[0]
for alignment in result.alignments:
allele_hit = alignment.hit_def
locus = alignment.hit_def.split(":")[0]
if locus not in ref_called_alleles:
for hsp in alignment.hsps:
# if "STMMW_44761" in alignment.title:
# if hsp.align_length > 50:
# locus = alignment.hit_def.split(":")[0]
# print(locus, allele_sizes[alignment.hit_def])
# print("test1", (int(hsp.identities) + int(hsp.gaps)), int(hsp.align_length))
# print("test2", int(hsp.gaps))
# print("test3", (len(hsp.sbjct) - hsp.sbjct.count("-")), int(allele_sizes[alignment.hit_def]))
# print_blasthsp(result, alignment, hsp, "")
# sl(0.3)
if hsp_filter_ok(hsp, 30, hsp_thresh):
if int(hsp.identities) == int(hsp.align_length) and int(hsp.gaps) == 0 and int(hsp.align_length) == int(allele_sizes[alignment.hit_def]):
# if testlocus in alignment.title:
# print("perfect_hit")
# locus = alignment.hit_def.split("-")[0]
# print(locus, allele_sizes[alignment.hit_def])
# print_blasthsp(result, alignment, hsp, "")
perfect_hit_allele = alignment.title.split(" ")[-1]
perfect_hit_locus = perfect_hit_allele.split(":")[0]
if perfect_hit_locus not in perfect_hit_ls:
perfect_hit_ls[perfect_hit_locus] = [(hsp,allele_hit,contig_hit,perfect_hit_allele)]
else:
perfect_hit_ls[perfect_hit_locus].append((hsp,allele_hit,contig_hit,perfect_hit_allele))
# print(perfect_hit_locus)
# if perfect_hit_locus not in partial_hit:
# if perfect_hit[perfect_hit_locus] != perfect_hit_allele:
# perfect_hit[perfect_hit_locus] = "0"
# #if second or more hits in genome match first perfect hit then leave as first hit call
# #Multiple perfect hits in genome with different alleles - don't call ie.e call as allele 0
# else:
# perfect_hit[perfect_hit_locus] = perfect_hit_allele
# partial_hit.remove(perfect_hit_locus)
exacthits +=1
totalhits += 1
hit_locations[result.query.split(" ")[0]].append((hsp.query_start,hsp.query_end,1.00))
elif (int(hsp.identities)+int(hsp.gaps)) == int(hsp.align_length) and int(hsp.gaps) > 0 and (len(hsp.sbjct)-hsp.sbjct.count("-")) == int(allele_sizes[alignment.hit_def]):
# TODO INDEL REMOVE this elif ignores gaps that are not caused by Ns: effectively if allele matches based on SNPs then matched - ignores indels
#TODO record dels that are ignored here
# if testlocus in alignment.title:
# print("passed check")
# locus = alignment.hit_def.split("-")[0]
# print(locus, allele_sizes[alignment.hit_def])
# print_blasthsp(result, alignment, hsp, "")
if "N" not in hsp.query:
perfect_hit_allele = alignment.title.split(" ")[-1]
perfect_hit_locus = perfect_hit_allele.split(":")[0]
if perfect_hit_locus not in perfect_hit_ls:
perfect_hit_ls[perfect_hit_locus] = [(hsp, allele_hit, contig_hit,perfect_hit_allele)]
else:
perfect_hit_ls[perfect_hit_locus].append((hsp, allele_hit, contig_hit,perfect_hit_allele))
# print(perfect_hit_locus)
# if perfect_hit_locus not in partial_hit:
# if perfect_hit[perfect_hit_locus] != perfect_hit_allele:
# perfect_hit[perfect_hit_locus] = "0"
# # if second or more hits in genome match first perfect hit then leave as first hit call
# # Multiple perfect hits in genome with different alleles - don't call ie.e call as allele 0
# else:
# perfect_hit[perfect_hit_locus] = perfect_hit_allele
# partial_hit.remove(perfect_hit_locus)
exacthits += 1
totalhits += 1
hit_locations[result.query.split(" ")[0]].append((hsp.query_start, hsp.query_end, 1.00))
else:
totalhits += 1
elif hsp.identities > (hsp.align_length*0.5) and hsp.identities < hsp.align_length:
# if testlocus in alignment.title:
# print("passed_to_partial")
# locus = alignment.hit_def.split("-")[0]
# print(locus, allele_sizes[alignment.hit_def])
# print_blasthsp(result, alignment, hsp, "")
totalhits +=1
perfect_hit = {}
for locus in ref_called_alleles:
if locus in partial_hit:
perfect_hit[locus] = locus + ":"+ ref_called_alleles[locus]
partial_hit.remove(locus)
for locus in perfect_hit_ls:
if locus in allele_sizes:
if len(perfect_hit_ls[locus]) == 1:
indels = call_indels(locus,perfect_hit_ls[locus][0][0],indels)
perfect_hit[locus] = perfect_hit_ls[locus][0][3]
partial_hit.remove(locus)
elif len(perfect_hit_ls[locus]) > 1:
ls_of_contigs = [x[2] for x in perfect_hit_ls[locus]]
num_contigs = len(set(ls_of_contigs))
if num_contigs > 1:
partial_hit.remove(locus) ## by removing from partial hit and not recording perfect hit this locus is assigned 0 by default
print("perfect_hits 2 contigs",locus)
else:
for hit in perfect_hit_ls[locus]:
# check if hit shares allele start and end nos if none do then do nothing (will remain in partial hits and be assigned new allele)
hsp = hit[0]
st = hsp.sbjct_start
en = hsp.sbjct_end
if hsp.sbjct_start > hsp.sbjct_end:
st = hsp.sbjct_end
en = hsp.sbjct_start
if st == 1 and en == allele_sizes[locus]:
if locus in perfect_hit:
if allele_sizes[locus+":"+hit[3]] > allele_sizes[locus+":"+perfect_hit[locus]]:
## if two hits on same contig likely overlapping hits with different sizes - pick larger hit
perfect_hit[locus]=hit[3]
indels = call_indels(locus, hit[0], indels)
else:
perfect_hit[locus] = hit[3]
indels = call_indels(locus, hit[0], indels)
partial_hit.remove(locus)
# print("exact hits: " + str(exacthits) + ", total hits: " + str(totalhits) + ", remaining loci to check: " + str(len(partial_hit)))
# if testlocus in partial_hit:
# print("error is after exact match")
# if "STMMW_40231" in partial_hit:
# print("partial")
return partial_hit, perfect_hit,hit_locations,indels
def check_for_multiple_ol_partial_hsps(hspls,hsp_thresh):
##TODO NOTE cutoff for overlap elimination of partial hsps is currently 0.6 - could change / make variable to adjust
# may be an issue with pairwise comparison callin g
#get list of hsps with start end and
## if 2 or more hsps pass filter but overlap by more that 60% call as 0
hspls = [x[0] for x in hspls]
filterpass = []
for hsp in hspls:
if hsp_filter_ok(hsp, 100, hsp_thresh):
filterpass.append(hsp)
for a, b in itertools.combinations(filterpass, 2):
if a.align_length >= b.align_length:
longer = a
shorter = b
else:
longer = b
shorter = a
longerst = longer.sbjct_start
longeren = longer.sbjct_end
if longer.sbjct_start > longer.sbjct_end:
longerst = longer.sbjct_end
longeren = longer.sbjct_start
shorterst = shorter.sbjct_start
shorteren = shorter.sbjct_end
if shorter.sbjct_start > shorter.sbjct_end:
shorterst = shorter.sbjct_end
shorteren = shorter.sbjct_start
if longerst <= shorterst <= longeren <= shorteren:
if float(longeren - shorterst) >= float(0.6*longer.align_length):
return "overlap"
elif shorterst <= longerst <= shorteren <= longeren:
if float(shorteren - longerst) >= float(0.6 * longer.align_length):
return "overlap"
elif longerst <= shorterst <= shorteren <= longeren:
if float(shorter.align_length) >= float(0.6 * longer.align_length):
return "overlap"
return "no overlap"
def remove_hsps_entirely_within_others(hspls,locus,hsp_thresh):
"""
:param hspls:
:param reflen:
:return:
"""
range_d = {}
range_d_new = {}
for tup in hspls:
hsp = tup[0]
if hsp_filter_ok(hsp,30,hsp_thresh):
# print(tup[1])
# print('alignment length:', hsp.align_length)
# print('identities:', hsp.identities)
# print('gaps:', hsp.gaps)
# print('ref_allele_len', str(reflen))
# print('query start', hsp.query_start)
# print('query end: ', hsp.query_end)
# print('subject start', hsp.sbjct_start)
# print('subject end: ', hsp.sbjct_end)
# print(hsp.query)
# print(hsp.match)
# print(hsp.sbjct, "\n")
sst = 0
send = 0
if hsp.sbjct_start > hsp.sbjct_end:
sst = hsp.sbjct_end
send = hsp.sbjct_start
else:
sst = hsp.sbjct_start
send = hsp.sbjct_end
range_d[(sst,send)] = tup
# if new range is entirely within existing one ignore
# if new range entirely encompases existing one, remove existing and add new
# otherwise add range
remove = []
for existing_range in range_d:
for test_range in range_d:
exst = existing_range[0]
exend = existing_range[1]
testst = test_range[0]
testend = test_range[1]
if exst <= testst and exend >= testend and existing_range != test_range:
remove.append(test_range)
nhspls = []
for rang in range_d:
if rang not in remove:
range_d_new[rang] = range_d[rang]
nhspls.append(range_d[rang])
if len(nhspls) > 1:
#TODONE write section to remove middle hsps like this:[(1, 220), (134, 285), (169, 498)] - i.e. remove (134, 285)
r2_rangelist = []
for rang in range_d_new:
r2_rangelist.append(rang)
r2_rangelist = sorted(r2_rangelist, key=lambda tup: tup[0])
overlaps = []
for r1 in r2_rangelist:
list1_remove_r1 = [x for x in r2_rangelist if x != r1]
for r2 in list1_remove_r1:
if r1[1] > r2[0] and r1[1] < r2[1] and r1[0] < r2[0]:
overlaps.append((r1, r2))
remove = []
for ol in overlaps:
for rang in r2_rangelist:
if rang not in ol:
if ol[0][0] < rang[0] and rang[1] < ol[1][1]:
remove.append(rang)
outls = []
testls = []
for x in r2_rangelist:
if x not in remove:
outls.append(range_d[x])
testls.append(x)
return outls
else:
return nhspls
def remove_indels_from_hsp(hsp):
"""
:param hsp:
:return:
"""
hsp1 = hsp
orient = "+"
unknown_allele = hsp1.query
ref_allele = hsp1.sbjct
matches = hsp1.match
refstart = hsp1.sbjct_start
refend = hsp1.sbjct_end
# re-orient matches so positions are always in direction of reference allele
if int(hsp1.sbjct_start) > int(hsp1.sbjct_end):
orient = "-"
unknown_allele = utils.reverse_complement(unknown_allele)
ref_allele = utils.reverse_complement(ref_allele)
matches = matches[::-1]
refstart, refend = refend, refstart
seq = ""
intact_nucs = ["A", "T", "G", "C", "a", "t", "c", "g"]
for i in range(len(unknown_allele)):
if matches[i] == " ":
if unknown_allele[i] in intact_nucs and ref_allele[i] in intact_nucs:
seq += unknown_allele[i]
elif unknown_allele[i] == "-" and ref_allele[i] in intact_nucs:
# TODO INDEL REMOVE Below replaces deletion in unknown allele with reference nucleotides to IGNORE DELETIONS
seq += ref_allele[i]
elif unknown_allele[i] in intact_nucs and ref_allele[i] == "-":
continue
# TODO INDEL REMOVE No addition of unknown allele seq if insertion in new allele
# seq+=unknown_allele[i]
elif unknown_allele[i] == "N":
seq += "N"
else:
seq += unknown_allele[i]
return seq
def check_ends_for_snps(hsplis,full_subj,query,locus,qgenome):
#TODONE fix so that correct nucleotides are pulled across - also check that indels don't mess with this calc
nhspls = []
for hsp in hsplis:
contig = hsp[1]
allele = hsp[2]
# print(contig,allele,query)
thsp = hsp[0]
nhsp = hsp[0]
if query == "":
contig2 = contig.split(" ")[0]
contigseq = qgenome[contig2]
subseq = full_subj
else:
# print(full_subj)
contig = contig.replace("reconstructed_allele","")
contigseq = full_subj[contig]
subseq = query
trial = 0
if thsp.sbjct_start > thsp.sbjct_end:
if thsp.sbjct_end == 2:
if thsp.query_end < len(contigseq):
q_snp = contigseq[thsp.query_end] # TODONE had error here see 23-2-18 notes - 2-3-18 DONE
else:
q_snp = "N" # if only final nucleotide is deleted from allele add N TODO indel record this as a del when dels are included for this and next 3 instances
s_snp = utils.reverse_complement(subseq[0])
nhsp.align_length = nhsp.align_length + 1
nhsp.match = nhsp.match + " "
nhsp.query = nhsp.query + q_snp
nhsp.sbjct = nhsp.sbjct + s_snp
nhsp.sbjct_end = nhsp.sbjct_end-1
nhsp.query_end = nhsp.query_end+1
if thsp.sbjct_start == len(subseq)-1:
# trial = 1
if thsp.query_start-2 >= 0:
q_snp = contigseq[thsp.query_start-2]
else:
q_snp = "N"
s_snp = utils.reverse_complement(subseq[-1])
nhsp.align_length = nhsp.align_length + 1
nhsp.match = " " + nhsp.match
nhsp.query = q_snp + nhsp.query
nhsp.sbjct = s_snp + nhsp.sbjct
nhsp.sbjct_start = nhsp.sbjct_start+1
nhsp.query_start = nhsp.query_start-1
else:
if thsp.sbjct_start == 2:
if thsp.query_start-2 >= 0:
q_snp = contigseq[thsp.query_start-2]
else:
q_snp = "N"
s_snp = subseq[0]
nhsp.align_length = nhsp.align_length + 1
nhsp.match = " " + nhsp.match
nhsp.query = q_snp + nhsp.query
nhsp.sbjct = s_snp + nhsp.sbjct
nhsp.sbjct_start = nhsp.sbjct_start-1
nhsp.query_start = nhsp.query_start-1
if thsp.sbjct_end == len(subseq)-1:
try:
if thsp.query_end < len(contigseq):
q_snp = contigseq[thsp.query_end]
else:
q_snp = "N"
s_snp = subseq[-1]
nhsp.align_length = nhsp.align_length + 1
nhsp.match = nhsp.match + " "
nhsp.query = nhsp.query + q_snp
nhsp.sbjct = nhsp.sbjct + s_snp
nhsp.sbjct_end = nhsp.sbjct_end+1
nhsp.query_end = nhsp.query_end+1
except:
print(locus,"query > subject")
# print(locus)
# print_blasthsp("", "", nhsp, "")
# print(subseq)
# print(contigseq)
nhspls.append((nhsp,contig,allele))
'''
blast hits structure:
list of results
result attributes: >>>'alignments'<<<, 'application', 'blast_cutoff', 'database', 'database_length', 'database_letters', 'database_name', 'database_sequences', 'date', 'descriptions', 'dropoff_1st_pass', 'effective_database_length', 'effective_hsp_length', 'effective_query_length', 'effective_search_space', 'effective_search_space_used', 'expect', 'filter', 'frameshift', 'gap_penalties', 'gap_trigger', 'gap_x_dropoff', 'gap_x_dropoff_final', 'gapped', 'hsps_gapped', 'hsps_no_gap', 'hsps_prelim_gapped', 'hsps_prelim_gapped_attemped', 'ka_params', 'ka_params_gap', 'matrix', 'multiple_alignment', 'num_good_extends', 'num_hits', 'num_letters_in_database', 'num_seqs_better_e', 'num_sequences', 'num_sequences_in_database', 'posted_date', 'query', 'query_id', 'query_length', 'query_letters', 'reference', 'sc_match', 'sc_mismatch', 'threshold', 'version', 'window_size']
alignment attributes: 'accession', 'hit_def', 'hit_id', >>>'hsps'<<<, 'length', 'title']
hsp attributes: 'align_length', 'bits', 'expect', 'frame', 'gaps', 'identities', 'match', 'num_alignments', 'positives', 'query', 'query_end', 'query_start', 'sbjct', 'sbjct_end', 'sbjct_start', 'score', 'strand'
'''
return nhspls
def get_partial_match_query_region(blast_results,partial_matches,sizes,ref_alleles,qgenome,hsp_ident):
"""
:param blast_results: 1st round blast results
:param partial_matches: loci without exact matches
:return: partials dictionary {locus:list of tuples} tuple -> (hsp matching reference allele,query contig where match was found)
Also writes fasta file of these hits for each locus to be used to blast all alleles of the locus
"""
# print(partial_matches)
partials = {}
for result in blast_results:
for alignment in result.alignments:
alignment_locus = alignment.hit_def.rsplit(":")[0]
if alignment_locus in partial_matches and alignment.hit_def == alignment_locus+":1":
for hsp in alignment.hsps:
# if alignment_locus == testlocus:
# print("-1 is present",hsp.align_length)
# if testlocus in alignment_locus:
# print("\n\n")
# print(alignment.hit_def)
# # print('allele size:',sizes[alignment_locus+"-1"])
# print('alignment length:', hsp.align_length)
# print('identities:', hsp.identities)
# print('gaps:', hsp.gaps)
# print('query contig', result.query)
# print('query start', hsp.query_start)
# print('query end: ', hsp.query_end)
# print('subject start', hsp.sbjct_start)
# print('subject end: ', hsp.sbjct_end)
# print(hsp.query)
# print(hsp.match)
# print(hsp.sbjct)
if alignment_locus not in partials:
partials[alignment_locus] = [(hsp,result.query,alignment.hit_def)]
else:
partials[alignment_locus].append((hsp,result.query,alignment.hit_def))
# for queries with non intact hit to ref allele check other hits to see if remainder of locus is present before calling deletion - could be caused by assembly error or repetitive insertion
# need to deal with split matches that overlap - STMMW_45221-1 in current example 100 gene scheme
rmlis = []
partials2 = {}
hitref = {}
for locus in partials:
hsplis = []
c = 1
## if 2 or more hsps pass filter but overlap by more that 60% call as 0
if len(partials[locus]) > 1:
olcheck = check_for_multiple_ol_partial_hsps(partials[locus],hsp_ident)
if olcheck == "overlap":
rmlis.append(locus)
# print("hits overlap by >60%",locus)
# for hit in partials[locus]:
# print(hit[0],"\n\n\n")
else:
locuspartials = remove_hsps_entirely_within_others(partials[locus],0,hsp_ident)
else:
locuspartials = partials[locus]
olcheck = "no overlap"
if olcheck =="no overlap":
locuspartials2 = check_ends_for_snps(locuspartials, ref_alleles[locus],"",locus,qgenome)
partials2[locus] = locuspartials
# if testlocus == locus:
# for hsp in partials2[locus]:
# # print(hsp)
# print_blasthsp("", "", hsp[0], "")
if len(locuspartials2) == 0:
rmlis.append(locus)
# if len(partials[locus]) > 0 and len(locuspartials) == 0:
# print(locus)
# hsp = partials[locus][0][0]
# print_blasthsp("","",hsp,"")
# print(len(partials[locus]))
# print(len(locuspartials))
# for hsp in locuspartials:
# hs = hsp[0].query.replace("-","")
# hitref[locus+"_hit_no_"+str(c)] = hs
# hitseq = Seq(hs)
# # hitseq = only_nucs(hitseq)
# s = SeqRecord.SeqRecord(hitseq,locus+"_hit_no_"+str(c),description="")
# hsplis.append(s)
# c+=1
# if len(locuspartials) != 0:
# SeqIO.write(hsplis,"tmp/"+locus+"_hits.fasta","fasta")
npartials = {}
for locus in partials2:
if locus not in rmlis:
npartials[locus] = partials2[locus]
# if locus == "STMMW_44761":
# for p in npartials[locus]:
# print(p[0])
# if "STMMW_40231" in npartials:
# print(npartials["STMMW_40231"])
return npartials,hitref
def get_combined_hsp_coverage_of_ref_allele(reflen,hspls,hsp_thresh):
range_lis = []
for tup in hspls:
hsp = tup[0]
if hsp_filter_ok(hsp,30,hsp_thresh):
if hsp.sbjct_start > hsp.sbjct_end:
range_lis.append((hsp.sbjct_end, hsp.sbjct_start))
else:
range_lis.append((hsp.sbjct_start,hsp.sbjct_end))
mrange_lis = utils.merge_intervals(range_lis)
tot_covered = 0
for hit in mrange_lis:
tot_covered += hit[1]-hit[0]
fraction_covered = float(tot_covered)/float(reflen)
return fraction_covered
def check_ends_split_contigs(hsp_start_tup,hsp_end_tup,reflen,alleleseq):
start_contig = hsp_start_tup[1]
end_contig = hsp_end_tup[1]
start_hsp = hsp_start_tup[0]
end_hsp = hsp_end_tup[0]
#start hsp
new_qstart = 0
new_qend = 0
sstart = start_hsp.sbjct_start
send = start_hsp.sbjct_end
qstart = start_hsp.query_start
qend = start_hsp.query_end
added_start = ""
if int(sstart) > int(send):
added_start = "N" * (int(reflen) - int(sstart))
# new_qstart = int(qstart) - (reflen - int(sstart))
# added_st = start_contig[new_qstart:int(qstart) - 1]
# if added_st.count("N") == len(added_st):
# added_start = reverse_complement(added_st)
# else:
# added_start = "N"*len(added_st)
else:
added_start = "N"*int(sstart-1)
# new_qstart = int(qstart) - int(sstart)
# added_st = start_contig[new_qstart:int(qstart) - 1]
# if added_st.count("N") == len(added_st):
# added_start = added_st
# else:
# added_start = "N"*len(added_st)
#end_hsp
sstart2 = end_hsp.sbjct_start
send2 = end_hsp.sbjct_end
qstart2 = end_hsp.query_start
qend2 = end_hsp.query_end
added_end = ""
if int(sstart2) > int(send2):
added_end = "N" * (int(send) - 1)
# new_qend = int(qend2) + int(send2) - 1
# added_e = end_contig[int(qend2):new_qend - 1]
# if added_e.count("N") == len(added_e):
# added_end = reverse_complement(added_e)
# else:
# added_end = "N"*len(added_e)
elif int(sstart2) < int(send2):
added_end = "N" * (reflen - int(send))
# new_qend = int(qend2) + (reflen - int(send2) - 1)
# added_e = end_contig[int(qend2):new_qend - 1]
# if added_e.count("N") == len(added_e):
# added_end = added_e
# else:
# added_end = "N"*len(added_e)
full_allele = added_start + alleleseq + added_end
return full_allele, added_start, added_end
def check_split_over_contigs(hspls,query_genome,reflen):
"""
Check if matches are at ends of contigs (or are that last non N part of the contigs)
if so get any overlap that may have occured
:param contigs_dict: dict of {contig_name:hsp(s) for that contig}
:param query_genome:
:param reflen:
:return:
"""
range_lis = []
range_d = {}
for tup in hspls:
hsp = tup[0]
# print(tup[1])
# print('alignment length:', hsp.align_length)
# print('identities:', hsp.identities)
# print('gaps:', hsp.gaps)
# print('ref_allele_len',str(reflen))
# print('query start', hsp.query_start)
# print('query end: ', hsp.query_end)
# print('subject start', hsp.sbjct_start)
# print('subject end: ', hsp.sbjct_end)
# print(hsp.query)
# print(hsp.match)
# print(hsp.sbjct,"\n")
if hsp.sbjct_start > hsp.sbjct_end:
sst = hsp.sbjct_end
send = hsp.sbjct_start
else:
sst = hsp.sbjct_start
send = hsp.sbjct_end
t = (sst,send)
range_lis.append(t)
range_d[t] = tup
sorted_range_list = sorted(range_lis,key=lambda tup: tup[0])
hsp1 = range_d[sorted_range_list[0]][0]
newseq = hsp1.query
if hsp1.sbjct_start > hsp1.sbjct_end:
newseq = utils.reverse_complement(hsp1.query)
for rang in range(len(sorted_range_list)-1):
cur_range_end = sorted_range_list[rang][1]
next_range_start = sorted_range_list[rang+1][0]
cur_hsp = range_d[sorted_range_list[rang]][0]
next_hsp = range_d[sorted_range_list[rang+1]][0]
if cur_range_end > next_range_start-1:
overlap = cur_range_end - next_range_start
#last part of curhsp and 1st part of next hsp
cur_query = cur_hsp.query
if cur_hsp.sbjct_start > cur_hsp.sbjct_end:
cur_query = utils.reverse_complement(cur_query)
next_query = next_hsp.query
if next_hsp.sbjct_start > next_hsp.sbjct_end:
next_query = utils.reverse_complement(next_query)
end_cur = cur_query[-1*(overlap+1):]
start_next = next_query[:overlap+1]
if end_cur == start_next:
newseq += next_query[overlap+1:]
else:
return "inconsistent overlap",""
#check overlap for identity
elif cur_range_end == next_range_start-1:
add = next_hsp.query
if next_hsp.sbjct_start > next_hsp.sbjct_end:
add = utils.reverse_complement(next_hsp.query)
newseq += add
elif cur_range_end < next_range_start-1:
#add Ns in gap
missing_no = next_range_start - cur_range_end-1
nstring = "N"*missing_no
newseq += nstring
add_seq = next_hsp.query
if next_hsp.sbjct_start > next_hsp.sbjct_end:
add_seq = utils.reverse_complement(next_hsp.query)
newseq += add_seq
else:
print("\n\nPROBLEM SPLIT CONTIGS\n\n")
if len(newseq) == reflen:
return "reconstructed split",newseq
else:
st_hsp = range_d[sorted_range_list[0]]
en_hsp = range_d[sorted_range_list[-1]]
full_allele, added_start, added_end = check_ends_split_contigs(st_hsp,en_hsp,reflen,newseq)
# print("FULL ALLELE\n",full_allele,"\n\n")
return "reconstructed split w ends", full_allele
# TODONE RUN check ends - may need to modify for different hsps and contigs at ends
# - wrote check_ends_split_contigs
# TODONE see below
#first sort by start number
#if overlap check overlap region for differences
#if diff return multiple copies
#else
# if start and end are complete return allele as "pseudointact"
#if no overlap add Ns to internal
def check_all_orient(hsp_list):
"""
:param hsp_list:
:return:
"""
orient = []
for tup in hsp_list:
hsp = tup[0]
if hsp.sbjct_end < hsp.sbjct_start:
orient.append("negative")
else:
orient.append("positive")
if len(list(set(orient))) > 1:
return "mixed"
else:
return orient[0]
def check_matching_overlap(hsp1,hsp2,orient):
if orient == "positive":
ol_len = hsp1.sbjct_end - hsp2.sbjct_start
if hsp1.query[-1*ol_len:] != hsp2.query[:ol_len]:
return "nomatch",ol_len
else:
return "match",ol_len
elif orient == "negative":
ol_len = hsp1.sbjct_start - hsp2.sbjct_end
if hsp1.query[:ol_len] != hsp2.query[-1*ol_len:]:
return "nomatch",ol_len
else:
return "match",ol_len
def largest_nonn_strings(string):
"""
:param string:
:return:
"""
matches = re.findall(r"[ATGC]*",string)
mx = max([len(x) for x in matches])
return mx
def check_ends(contig,qstart,qend,sstart,send,reflen,alleleseq,locus):
"""
:param contig:
:param qstart:
:param qend:
:param sstart:
:param send:
:param reflen:
:param alleleseq:
:return:
"""
# if hit in reverse orientation have to check opposite end of hit in query genome
new_qstart = 0
new_qend = 0
added_start = ''
added_end = ''
full_allele = ""
if int(sstart) > int(send):
new_qstart = int(qstart) - (reflen - int(sstart))
new_qend = int(qend) + int(send) - 1
added_start = "N"*(int(reflen) - int(sstart))
#TODO Indel: following commented out elifs check for identity of missing region; if not Ns then assumed to be truncated allele - however when ignoring dels we can just add Ns to all of these regions becuase we treat dels and N regions the same
# added_st = contig[new_qstart:int(qstart) - 1]
# if added_st.count("N") == len(added_st):
# added_start = reverse_complement(added_st)
# else:
# added_start = "N"*(int(reflen) - int(sstart))
# print("len of added start", int(reflen) - int(sstart))
added_end = "N"*(int(send)-1)
# added_e = contig[int(qend):new_qend - 1]
# if added_e.count("N") == len(added_e):
# added_end = reverse_complement(added_e)
# else:
# added_end = "N"*(int(send)-1)
# print("len of added end",int(send)-1)
full_allele = added_end + alleleseq + added_start
elif int(sstart) < int(send):
new_qstart = int(qstart) - int(sstart)
new_qend = int(qend) + (reflen - int(send) - 1)
added_start = "N"*int(sstart-1)
# added_st = contig[new_qstart:int(qstart) - 1]
# if added_st.count("N") == len(added_st):
# added_start = added_st
# else:
# added_start = "N"*int(sstart-1)
added_end = "N"*(reflen - int(send))
# added_e = contig[int(qend):new_qend - 1]
# if added_e.count("N") == len(added_e):
# added_end = added_e
# else:
# added_end = "N"*(reflen - int(send))
full_allele = added_start + alleleseq + added_end
# if locus == testlocus:
# print(added_start)
# print(added_end)
# TODOFIXED: check that this last section actually does something
# if missing flanking region is not all Ns then use original query hit edge - allows for rearrangements/deletions where flanking regions are really gone
# full_allele = added_start + alleleseq + added_end
return full_allele,added_start,added_end
def check_mid(contig,hspls,q_genome,wordsize,reflen,locus):
"""
use word length ratio as cutoff for allowing non-N letters in restored gap sequence(i.e. if word length is 12. non-N sequence chunk can be a max of 18 before mid regions is called something else)
:param contig:
:param hspls:
:param q_genome:
:return:
"""
orient = check_all_orient(hspls)
# if locus == testlocus:
# for hsp in hspls:
# print(hsp)
if orient == "mixed":
# TODO work out what to do with mixed orientation, currently call as 0
return "mixed_orientation"
else:
#TODONE work out possible issue with orientation being messed up
ordered_by_query = []
order = {}
for tup in hspls:
hsp = tup[0]
order[hsp.query_start] = hsp
# if locus == testlocus:
# print_blasthsp("","",hsp,"")
sorted_hsps = sorted(map(int, order.keys()))
# hsp1 = order[sorted_hsps[0]]
full_allele = remove_indels_from_hsp(order[sorted_hsps[0]])#order[sorted_hsps[0]].query
sstart = order[sorted_hsps[0]].sbjct_start
send = order[sorted_hsps[-1]].sbjct_end
qstart = order[sorted_hsps[0]].query_start
qend = order[sorted_hsps[-1]].query_start
if orient == "positive":
for start in range(len(sorted_hsps)-1):
hsp = order[sorted_hsps[start]]
hspnext = order[sorted_hsps[start+1]]
mid_section_st = int(hsp.query_end)
mid_section_en = int(hspnext.query_start)
if mid_section_en < mid_section_st:
olcheck, ollen = check_matching_overlap(hsp, hspnext, "negative")
add = q_genome[contig][hspnext.query_start+ollen:hspnext.query_end-1]
full_allele = full_allele + add
# mid_section_seq = "N"*(hspnext.sbjct_start-hsp.sbjct_end-1)
else:
mid_section_seq = "N"*(hspnext.sbjct_start-hsp.sbjct_end-1)
# mid_section_seq = q_genome[contig][mid_section_st:mid_section_en-1]
# if locus == testlocus:
# print(order[sorted_hsps[start+1]])