-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathis_analysis.py
1503 lines (1342 loc) · 56.4 KB
/
is_analysis.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
import subprocess, shlex
import string
import operator
import re
import constants
import tools
import concurrent.futures
import os.path
import itertools
import ssw_wrap
import sys
import datetime
# Return mInput4ssw
## mInput4ssw: [input4orfHits, ..., input4orfHits]
## input4orfHits: [input4orfhit, ..., input4orfhit]
# mInput4ssw: [input4orfhit, ..., input4orfhit]
# input4orfhit: (familyName, orfStr, seq1, seq2, minScore, minLen)
# familyName: the profile HMM model of which is used to search protein database
# orfStr: string, orf == ('0000941.1', 20, 303, '+') -> orfStr == '0000941.1_20_303_+'
#
# mOrfHits: {seqid: orfHits, ..., seqid: orfHits}
# orfHits: [orfhit, ..., orfhit]
# orfhit: (orf, familyName, best_1_domain_E-value, full_sequence_E-value, overlap_number)
# orf: (seqid, begin, end, strand)
# mDna: {seqid: (org, fileid, sequence), ..., seqid: (org, fileid, sequence)}
# sequence: string
#
def prepare4ssw2findIRbyDNAbyFar(mOrfHits, mDna):
mInput4ssw = []
mboundary = {}
for seqid in mOrfHits:
if len(mOrfHits[seqid]) == 0:
continue
DNAlen = len(mDna[seqid][-1])
for orfHit in mOrfHits[seqid]:
familyName = orfHit[1]
maxDist4ter2orf = constants.maxDist4ter2orf
minDist4ter2orf = constants.minDist4ter2orf
orf = orfHit[0]
orfLeftPos, orfRightPos, strand = orf[1:]
start1, end1, start2, end2 = pseudoSeqBoundary_v4(orfLeftPos, orfRightPos,
maxDist4ter2orf, minDist4ter2orf)
# Set start as the first bp if distance between left end and the nearest ORF is
# less than maxDist4ter2orf.
if start1 < 1:
start1 = 1
if end2 > DNAlen:
end2 = DNAlen
# The strand does not matter when extract two terminal sequences to align, namely,
# which sequence is the first sequence in pairwise alignement does not make sense.
lSeq = mDna[seqid][-1][start1-1: end1]
rSeq = tools.complementDNA(mDna[seqid][-1][start2-1: end2], '1')[::-1]
minScore = 0.0
# familyName example: 'IS200/IS605_4|IS200/IS605|IS1341|ISCARN12|',
# 'IS30_0', 'IS110_25|IS110||ISLIN1|'
min4tir = constants.min4tir
#min4tir = constants.optmin4tir
if '|' in familyName:
familyCluster = familyName.split('|',1)[0]
else:
familyCluster = familyName
family, cluster = familyCluster.rsplit('_', 1)
if familyCluster == 'IS200/IS605_8':
minLen = min4tir[familyCluster]
else:
minLen = min4tir[family]
# transformat orf to a string, for example,
# orf == ('gi|256374160|ref|NC_013093.1|', 20, 303, '+')
# -> orfStr == 'gi|256374160|ref|NC_013093.1|_20_303_+'
# So, orfStr can be used an ID like isName in other called sub-functions
orfStr = '_'.join((orf[0], str(orf[1]), str(orf[2]), orf[3]))
mInput4ssw.append((familyName, orfStr, lSeq, rSeq, minScore, minLen))
mboundary[orfStr] = (start1, end1, start2, end2)
#mInput4ssw.append(input4orfHits)
return (mInput4ssw, mboundary)
# check the intersection between the current upsteam and downstream tir search windows
# and the neighboring tpase ORFs, and then probably shrink the tir search windows to
# avoid the insersection with the neighboring tpase ORFs.
#
# orfhitsNeighbors: {orf: orfhitneighbors, ..., orfhitneighbors}
# orfhitneighbors: [before, orfhit, after], before/after is None or orfhit
# orfhit: (orf, familyName, best_1_domain_E-value, full_sequence_E-value, ncopy4tpase, raworfhits)
# orf: (seqid, begin, end, strand)
def tirwindowIntersectORF(start1, end1, start2, end2,
orfhit,
orfhitsNeighbors, minDist4ter2orf):
orf = orfhit[0]
orfBegin, orfEnd = orf[1:3]
before = orfhitsNeighbors[orf][0]
after = orfhitsNeighbors[orf][1]
start1New, end1New, start2New, end2New = start1, end1, start2, end2
if before != None and orf[3] == before[0][3] and start1 <= before[0][2]:
start1New = before[0][2] + 1
#end1New = end1 - (start1-start1New)
print('hello, before', before)
print('shrink the boundary of tir search region around orfhit {}, start1 ({}) to {}'.format(
orfhit, start1, start1New))
if after != None and orf[3] == after[0][3] and end2 >= after[0][1]:
end2New = after[0][1] - 1
#start2New = start2 - (end2-end2New)
print('hello, after', after)
print('shrink the boundary of tir search region around orfhit {}, end2 ({}) to {}'.format(
orfhit, end2, end2New))
return (start1New, end1New, start2New, end2New)
# mDNA: {accid: (org, fileid, sequence), ..., accid: (org, fileid, sequence)}
#
# morfhits: {seqid: orfhits, ...}
# orfhits: [orfhit, ...]
# orfhit: (orf, familyName, best_1_domain_E-value, full_sequence_E-value, ncopy4tpase, raworfhits)
# orf: (seqid, begin, end, strand)
# raworfhits: {'orfhits4tpase':orfhits4tpase}
# orfhits4tpase: [] or [orfhit4tpase, ...]
# orfhit4tpase: (orf, familyName, best_1_domain_E-value, full_sequence_E-value, ncopy4tpase)
#
# orfhitsNeighbors: {orf: orfhitneighbors, ..., orfhitneighbors}
# orfhitneighbors: [before, orfhit, after], before/after is None or orfhit
#
def prepare4ssw2findIRbyDNAbyFar4orfhits(morfhits, mDna, maxDist4ter2orf, minDist4ter2orf,
morfhitsNeighbors):
mInput4ssw = []
mboundary = {}
for seqid, orfhits in morfhits.items():
if len(orfhits) == 0:
continue
orfhitsNeighbors = morfhitsNeighbors[seqid]
DNAlen = len(mDna[seqid][-1])
for orfhit in orfhits:
orfHit = orfhit
familyName = orfHit[1]
orf = orfhit[0]
orfBegin, orfEnd = orf[1:3]
orfLen = orfEnd - orfBegin + 1
# familyName example: 'IS200/IS605_4|IS200/IS605|IS1341|ISCARN12|',
# 'IS30_0', 'IS110_25|IS110||ISLIN1|'
if '|' in familyName:
familyCluster = familyName.split('|',1)[0]
else:
familyCluster = familyName
family, cluster = familyCluster.rsplit('_', 1)
#if familyCluster == 'IS200/IS605_8':
# minMax4tir = constants.minMax4tir[familyCluster]
#else:
# minMax4tir = constants.minMax4tir[family]
minMax4tir = constants.minMax4tir[family]
if constants.useOPTtir == True:
minLen = minMax4tir[2]
else:
minLen = minMax4tir[0]
ncopy4tpase = orfHit[4]
virtualORF = False
if ncopy4tpase > 1:
virtualORF = True
# consider the identified aligned-region as a virtual ORF
qstart, qend = orfBegin, orfEnd
# if aligned region spans two or more Tpases, eg. composite transposon,
# the current hit in the aligned region is trimmed to the tpase ORF.
if constants.splitAlign2orf == True:
if ((before != None and qstart <= before[0][2]) or
(after != None and qend >= after[0][1])):
print('split ncopy4is={} qstart={} qend={} orf={} before={} after={}'.format(
ncopy4is, qstart, qend, orf, before, after))
virtualORF = False
if virtualORF == True:
dist = minMax4tir[1]
#dist = minMax4tir[1] + minMax4dr[1]
#start1, end1, start2, end2 = qstart, orfBegin, orfEnd, qend
maxDist = 0
minDist = -dist
start1, end1, start2, end2 = pseudoSeqBoundary_v4(qstart, qend, maxDist, minDist)
else:
start1, end1, start2, end2 = pseudoSeqBoundary_v4(orfBegin, orfEnd,
maxDist4ter2orf, minDist4ter2orf)
'''
if ncopy4tpase <= 1:
start1, end1, start2, end2 = tirwindowIntersectORF(
start1, end1, start2, end2,
orfhit, orfhitsNeighbors, minDist4ter2orf)
'''
'''
if end1 >= start2:
end1 = int((end1+start2)/2)
start2 = end1 + 1
'''
# check DNA termini to assure that tir is within DNA termini
if start1 < 1:
start1 = 1
if start1 > end1:
end1 = 1
if end2 > DNAlen:
end2 = DNAlen
if start2 > end2:
start2 = DNAlen
# check the sequencial order of tir search boundaries and set the tir search window of 1 bp
# to prevent SSW alignment from returning fake tir.
if not (start1 < end1 < start2 < end2):
#e = 'Error, invalid tir search window (org={} fastafile={} seq={}): {}-{} {}-{} around ORF {}'.format(
# mDna[seqid][0], mDna[seqid][1], seqid, start1, end1, start2, end2, orf)
#raise RuntimeError(e)
e = 'No tir will be found in the invalid tir search window (org={} fastafile={}): {}-{} {}-{} around ORF {}'.format(
mDna[seqid][0], mDna[seqid][1], start1, end1, start2, end2, orfhit)
print(e)
# Set a tir search windows the 1-bp-long termini of ORF,
# which will later prevent alignment algorithm from returning any tir.
start1 = end1 = orf[1]
start2 = end2 = orf[2]
# The strand does not matter when extracting two terminal sequences to align, namely,
# which sequence is the first sequence in pairwise alignement does not make sense.
lSeq = mDna[seqid][-1][start1-1: end1]
rSeq = tools.complementDNA(mDna[seqid][-1][start2-1: end2], '1')[::-1]
minScore = 0.0
# transformat orf to a string, for example,
# orf == ('gi|256374160|ref|NC_013093.1|', 20, 303, '+')
# -> orfStr == 'gi|256374160|ref|NC_013093.1|_20_303_+'
# So, orfStr can be used an ID like isName in other called sub-functions
orfStr = '_'.join((orf[0], str(orf[1]), str(orf[2]), orf[3]))
mInput4ssw.append((familyName, orfStr, lSeq, rSeq, minScore, minLen))
mboundary[orfStr] = (start1, end1, start2, end2)
return (mInput4ssw, mboundary)
# Prepare sequences for alignment to search for multipe-copy full-length IS elements.
def prepare4ssw2findIScopyByDNA(hits, dna):
mInput4ssw = []
mboundary = {}
if len(hits) == 0:
return (mInput4ssw, mboundary)
hitPairs = itertools.combinations(hits, 2)
'''
for hitpair in hitPairs:
input4ssw, boundary = prepare4ssw2findIScopyByDNA4hitPair((hitpair, dna))
mInput4ssw.append(input4ssw)
mboundary[boundary[0]] = boundary[1]
'''
nthread = constants.nthread
# for +/+ or -/- strands comparison of each hit pair
with concurrent.futures.ThreadPoolExecutor(max_workers = nthread) as executor:
future2pairs = {executor.submit(prepare4ssw2findIScopyByDNA4hitPair, (pair, dna)): pair for pair in hitPairs}
for future in concurrent.futures.as_completed(future2pairs):
pair = future2pairs[future]
try:
input4ssw, boundary = future.result()
except Exception as exc:
print('{} generated an exception: {}'.format(pair, exc))
else:
# for +/+ alignment
# seq2 is the normal strand of the 2nd sequence.
#
mInput4ssw.append(input4ssw)
# input4ssw: [tirSeqs, orfStr, seq1, seq2, minScore, minLen]
# for +/- alignment
# seq2 is the reversed complementary sequence of the 2nd sequence.
# seq2 = tools.complementDNA(dna[start2-1: end2], '1')[::-1]
#
input4sswCopy = input4ssw[:]
input4sswCopy[3] = tools.complementDNA(input4sswCopy[3], '1')[::-1]
mInput4ssw.append(input4sswCopy)
mboundary[boundary[0]] = boundary[1]
return (mInput4ssw, mboundary)
# Search ORF copy, then we can check if TIRs in two copies are same or not.
# Attach tir sequences info to the returned data.
#def prepare4ssw2findIScopyByDNA4hitPair((hitPair, dna)):
def prepare4ssw2findIScopyByDNA4hitPair(input):
hitPair, dna = input
'''
# Option1:
# 1) Search full IS element copy, then we can check if TIRs in two copies are same or not.
# Use the boundary of the first TIR of hit as the boundary of full-length IS element
# if multiple TIRs are available, else use the boundary of the ORF of hit.
if len(hitPair[0]['tirs']) > 0 and len(hitPair[0]['tirs'][0]) > 0:
start1 = hitPair[0]['tirs'][0][-6]
end1 = hitPair[0]['tirs'][0][-3]
tirSeqs = list(hitPair[0]['tirs'][0][-2:])
else:
start1, end1 = hitPair[0]['orf'][1:3]
tirSeqs = ['', '']
if len(hitPair[1]['tirs']) > 0 and len(hitPair[1]['tirs'][0]) > 0:
start2 = hitPair[1]['tirs'][0][-6]
end2 = hitPair[1]['tirs'][0][-3]
tirSeqs.extend(hitPair[1]['tirs'][0][-2:])
else:
start2, end2 = hitPair[1]['orf'][1:3]
tirSeqs.extend(['',''])
'''
# Option2:
# 2) Search ORF copy, then we can check if TIRs in two copies are same or not.
start1, end1 = hitPair[0]['orf'][1:3]
start2, end2 = hitPair[1]['orf'][1:3]
if len(hitPair[0]['tirs']) > 0 and len(hitPair[0]['tirs'][0]) > 0:
tirSeqs = list(hitPair[0]['tirs'][0][-2:])
else:
tirSeqs = ['', '']
if len(hitPair[1]['tirs']) > 0 and len(hitPair[1]['tirs'][0]) > 0:
tirSeqs.extend(hitPair[1]['tirs'][0][-2:])
else:
tirSeqs.extend(['',''])
# Use orf of the hit as IS element ID
orf1 = hitPair[0]['orf']
orf2 = hitPair[1]['orf']
#
# OptionA: IS element is strand-specific DNA element.
# 1) compare only '+' strands, +/+ or -/-
seq1 = dna[start1-1: end1]
seq2 = dna[start2-1: end2]
#
# OptionB: IS element is strand-nonspecific DNA element
# 2) compare both '+' strands and '-' strands, namely, (+/+ and +/-) or (-/- and +/+)
#seq1 = dna[start1-1: end1]
#seq21 = dna[start2-1: end2]
#seq22 = tools.complementDNA(seq21, '1')[::-1]
# Option0:
# minLen = min(seq1, seq2)/2
#minScore, minLen = 0.0, int(min(len(seq1), len(seq2))/2)
#
# Option1:
# minLen = min(seq1, seq2) * sim4iso
minScore, minLen = 0.0, int(min(len(seq1),len(seq2)) * constants.sim4iso)
#
# Option2:
# minLen = min(orf1Len, orf2Len) * sim4iso
#orf1Len = hitPair[0]['orf'][2] - hitPair[0]['orf'][1] + 1
#orf2Len = hitPair[1]['orf'][2] - hitPair[1]['orf'][1] + 1
#minScore, minLen = 0.0, int(min(orf1Len, orf2Len) * constants.sim4iso)
# transformat orf to a string, for example,
# orf == ('0000941.1', 20, 303, '+') -> orfStr == '0000941.1_20_303_+'
# So, orfStr can be used an ID like isName in other called sub-functions
orfStr1 = '_'.join((orf1[0], str(orf1[1]), str(orf1[2]), orf1[3]))
orfStr2 = '_'.join((orf2[0], str(orf2[1]), str(orf2[2]), orf2[3]))
orfStr = orfStr1 + '|' + orfStr2
# transformat tir aligned sequences to a string, for example,
# tir1 for orfstr1
# CCCTTTGCTTCGCAAAGGCCCTCTC
# |||*||||||||| |||||||||||
# CCCCTTGCTTCGC-AAGGCCCTCTC
# tir2 for orfstr2
# CCCTTTGCTTCGC
# |||*|||||||||
# CCCCTTGCTTCGC
#
# tirSeqs = 'CCCTTTGCTTCGCAAAGGCCCTCTC|CCCCTTGCTTCGC-AAGGCCCTCTC|CCCTTTGCTTCGC|CCCCTTGCTTCGC'
# or tirSeqs = '||CCCTTTGCTTCGC|CCCCTTGCTTCGC'
# or tirSeqs = 'CCCTTTGCTTCGCAAAGGCCCTCTC|CCCCTTGCTTCGC-AAGGCCCTCTC||'
# So, tirSeqs can be used to find full IS copies with identical tir sequences.
#tirSeqs = '|'.join(tirSeqs)
#
# tirSeqs = 'CCCTTTGCTTCGCAAAGGCCCTCTC|CCCCTTGCTTCGCAAGGCCCTCTC|CCCTTTGCTTCGC|CCCCTTGCTTCGC'
# or tirSeqs = '||CCCTTTGCTTCGC|CCCCTTGCTTCGC'
# or tirSeqs = 'CCCTTTGCTTCGCAAAGGCCCTCTC|CCCCTTGCTTCGCAAGGCCCTCTC||'
tirSeqs = '|'.join(tirSeqs).replace('-', '')
# Data items correspondence bwteen TIR searching and IS copy searching.
# familyName, isName = tirSeqs, orfStr, in order that isName, namely, orfStr, is an unique ID
input4ssw = [tirSeqs, orfStr, seq1, seq2, minScore, minLen]
boundary = ((orf1, orf2), (start1, end1, start2, end2))
return (input4ssw, boundary)
# Based on comparing two full IS elements with TIRs, find the copies of IS element in same DNA sequence.
def prepare4ssw2findIScopyByDNA4hitPairByTIR(input):
hitPair, dna = input
# Use the boundary of the first TIR of hit as the boundary of full-length IS element if TIR is available,
# else use the boundary of the ORF of hit.
if len(hitPair[0]['tirs']) > 0 and len(hitPair[0]['tirs'][0]) > 0:
start1 = hitPair[0]['tirs'][0][-6]
end1 = hitPair[0]['tirs'][0][-3]
else:
start1, end1 = hitPair[0]['orf'][1:3]
if len(hitPair[1]['tirs']) > 0 and len(hitPair[1]['tirs'][0]) > 0:
start2 = hitPair[1]['tirs'][0][-6]
end2 = hitPair[1]['tirs'][0][-3]
else:
start2, end2 = hitPair[1]['orf'][1:3]
# Use orf of the hit as IS element ID
orf1 = hitPair[0]['orf']
orf2 = hitPair[1]['orf']
if orf1[3] == '+':
seq1 = dna[start1-1: end1]
else:
seq1 = tools.complementDNA(dna[start1-1: end1], '1')[::-1]
if orf2[3] == '+':
seq2 = dna[start2-1: end2]
else:
seq2 = tools.complementDNA(dna[start2-1: end2], '1')[::-1]
# Option1:
# minLen = min(seq1, seq2)/2
#minScore, minLen = 0.0, int(min(len(seq1), len(seq2))/2)
#
# Option2:
# minLen = min(seq1, seq2) * sim4iso
#minScore, minLen = 0.0, int(min(len(seq1),len(seq2)) * constants.sim4iso)
#
# Option3:
# minLen = min(orf1Len, orf2Len) * sim4iso
orf1Len = hitPair[0]['orf'][2] - hitPair[0]['orf'][1] + 1
orf2Len = hitPair[1]['orf'][2] - hitPair[1]['orf'][1] + 1
minScore, minLen = 0.0, int(min(orf1Len, orf2Len) * constants.sim4iso)
# transformat orf to a string, for example,
# orf == ('0000941.1', 20, 303, '+') -> orfStr == '0000941.1_20_303_+'
# So, orfStr can be used an ID like isName in other called sub-functions
orfStr1 = '_'.join((orf1[0], str(orf1[1]), str(orf1[2]), orf1[3]))
orfStr2 = '_'.join((orf2[0], str(orf2[1]), str(orf2[2]), orf2[3]))
orfStr = orfStr1 + '|' + orfStr2
# familyName, isName = orfStr, orfStr, in order that isName, namely, orfStr, is an unique ID
input4ssw = (orfStr, orfStr, seq1, seq2, minScore, minLen)
boundary = ((orf1, orf2), (start1, end1, start2, end2))
return (input4ssw, boundary)
# Note: finding IR requires sharp values for gap and mismatch comparing with finding homology sequence
# as the two short sequences of IR usually have much higher identity than common homology sequences
# Return: filters = [filter, .., filter]
# filter: (gap, gapextend, match, mismatch)
def buildFilter4ssw(gap, gapextend, match, mismatch):
# gapopen: default 2 (refer to consistants.py)
gapRange = range(gap - 1, gap + 12, 1)
#gapRange = range(gap - 1, gap + 8, 1)
#gapRange = range(gap - 1, gap + 4, 1)
#gapRange = range(gap - 0, gap + 2, 1)
# gapextend: default 1
gapextendRange = range(gapextend - 0, gapextend + 12, 1)
#gapextendRange = range(gapextend - 0, gapextend + 8, 1)
#gapextendRange = range(gapextend - 0, gapextend + 4, 1)
#gapextendRange = range(gapextend - 0, gapextend + 2, 1)
# match: default 2
matchRange = range(match - 1, match + 12, 1)
#matchRange = range(match - 1, match + 8, 1)
#matchRange = range(match - 1, match + 4, 1)
#matchRange = range(match - 0, match + 2, 1)
# mismatch: default 2
#mismatchRange = range(mismatch - 1, mismatch + 13, 1)
mismatchRange = range(mismatch - 1, mismatch + 8, 1)
#mismatchRange = range(mismatch - 1, mismatch + 4, 1)
#mismatchRange = range(mismatch - 0, mismatch + 2, 1)
filters = []
for gap in gapRange:
for gapextend in gapextendRange:
for match in matchRange:
if (gap + gapextend) < match:
continue
for mismatch in mismatchRange:
if mismatch*2 < match:
continue
filter = (gap, gapextend, match, mismatch)
filters.append(filter)
return filters
# Return group of TIRs with the greatest irScore.
# TIRs: [(TIR1, filter1), ..., (TIRn, filtern)]
#
# elementTIR: [(TIR1, filter1), ..., (TIRn, filtern)], TIR information for one IS element
# TIR: [familyName, isName, ir]
def keepBestTIR_v3(elementTIR):
for score, g in itertools.groupby(
sorted(elementTIR, key = lambda x: tools.irScore(x[0][2]), reverse = True),
key = lambda x: tools.irScore(x[0][2])):
return list(g)
# Return the group of TIRs: [(TIR1, filter1), ..., (TIRn, filtern)]
# list(item): [(TIR1, filter1), ..., (TIRn, filtern)]
#
# elementTIR: [(TIR1, filter1), ..., (TIRn, filtern)], TIR information for one IS element
# TIR: [familyName, isName, ir]
def keepBestTIR_v2(elementTIR):
# sort by nGaps/irLen all possible TIRs for one IS
for nGaps, g in itertools.groupby(
sorted(elementTIR, key = lambda x: x[0][2][3]/x[0][2][2]),
key = lambda x: x[0][2][3]/x[0][2][2]):
#return list(g)
# Sorted and grouped by irId/irLen, then get the TIR with greatest irId/irLen.
# list(g): [(TIR1, filter1), ..., (TIRn, filtern)]
for irId, item in itertools.groupby(
sorted(g, key = lambda x: x[0][2][1]/x[0][2][2], reverse = True),
key = lambda x: x[0][2][1]/x[0][2][2]):
# Return the best TIRs with least nGaps/irLen and greatest irId/irLen
return list(item)
# Return the group of TIRs with least nGaps: [(TIR1, filter1), ..., (TIRn, filtern)]
# list(item): [(TIR1, filter1), ..., (TIRn, filtern)]
# Note: TIR1 and TIRn have same nGaps and irId but may have different sequence alignments.
# For example, ir1 and ir2 have the same nGaps and irId but might have different irLen and
# start1/end1/start2/end2 and seq1/seq2.
#
# elementTIR: iterator returned by itertools.groupby, TIR information for one IS element
def keepBestTIR(elementTIR):
# sort by nGaps all possible TIRs for one IS
for nGaps, g in itertools.groupby(
sorted(elementTIR, key = lambda x: x[0][2][3]),
key = lambda x: x[0][2][3]):
return list(g)
# Return bestTIR which is the best matched TIR with the best irScore comparing with other matched TIRs
# if there is any other matched TIR
# Note: the bestTIR may be found under multiple filter conditions
#
# TIRfilters: [(TIR_1, filter_1), ..., (TIR_i, filter_j), ...]
# TIR: [familyName, isName, ir]
#
# TIRs: [element1TIR, ..., elementnTIR]
# elementTIR: [(TIR1, filter1), ..., (TIRn, filtern)]
# TIR: [familyName, isName, ir]
# ir: [score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2]
#
def checkTIRseq(TIRfilters):
bestTIR = []
#isNames = []
elements = []
for k, g in itertools.groupby(
# sort and group by isName
sorted(TIRfilters, key = lambda x: x[0][1]),
lambda x: x[0][1]):
#isNames.append(k)
elements.append(list(g))
for elementTIR in elements:
# keep the best TIRs which have same irScore but might have different alignments under different filters
#
elementTIR = keepBestTIR_v3(elementTIR)
# elementTIR: [(TIR1, filter1), ..., (TIRn, filtern)]
# Note:
# TIR1 and TIRn have same irScore but may have different sequence alignments. For example,
# ir1 and ir2 have the same nGaps and irId and irLen but might
# have different seq1/seq2.
#
# get all ISs, each of which keeps only the best TIR group
if len(elementTIR[0][0][2]) > 0:
bestTIR.append(elementTIR)
return bestTIR
# Return bestTIR which is the best matched TIR with least gaps comparing with other matched TIRs if there is any other matched TIR
# Note: the bestTIR may be found under multiple filter conditions
#
# TIRfilters: [(TIR_1, filter_1), ..., (TIR_i, filter_j), ...]
# TIR: [familyName, isName, ir]
#
# TIRs: [element1TIR, ..., elementnTIR]
# elementTIR: [familyName, isName, ir]
# ir: [score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2]
#
def checkTIRseq_v1(TIRfilters):
bestTIR = []
#isNames = []
elements = []
for k, g in itertools.groupby(sorted(TIRfilters, key = lambda x: x[0][1]), lambda x: x[0][1]):
#isNames.append(k)
elements.append(list(g))
for elementTIR in elements:
# keep the best TIRs with same nGaps and irId and different alignment paths under different filters
#
# Given one IS, group by nGaps all possible TIRs and then get best TIR group (same sequence under one or more filters)
elementTIR = keepBestTIR(elementTIR)
#
# elementTIR: [(TIR1, filter1), ..., (TIRn, filtern)]
# Note: TIR1 and TIRn have same nGaps and irId and irLen but may have different sequence alignments.
# For example, ir1 and ir2 have the same nGaps and irId and irLen but might have different start1/end1/start2/end2 and seq1/seq2.
#
# get all ISs, each of which keeps only the best TIR group
bestTIR.append(elementTIR)
return bestTIR
# filterPerformance: [(filter, perf, TIRs), ..., (filter, perf, TIRs)]
# filter: (gapopen, gapextend, match, mismatch)
# perf: (nmatch, ndismatch, ndiscard, nIS)
# TIRs: [TIR, ..., TIR]
# TIR: [familyName, isName, ir]
def outputPerformanceBySSW(filterPerformance):
fmtWaterPerfStr = '{:>7} {:>9} {:>5} {:>8} {:>9} {:>12} {:>9}'
print(fmtWaterPerfStr.format('gapOpen', 'gapExtend', 'match', 'mismatch', 'matchedIS', 'notMatchedIS', 'discardIS'))
print('-' * 50)
for item in filterPerformance:
gap, gapextend, match, mismatch = item[0]
matched, notMatched, discard, nIS = item[1]
print(fmtWaterPerfStr.format(gap, gapextend, match, mismatch, matched, notMatched, discard))
# filterPer: {filter: [nIS, {isName, ..., isName}], ..., filter: [nIS, {isName, ..., isName}]}
def outputPerf_v2(filterPerf):
fmtPerfStr = '{:>7} {:>9} {:>5} {:>8} {:<}'
print(fmtPerfStr.format('gapOpen', 'gapExtend', 'match', 'mismatch', 'matchedISwithBestTIR'))
print('-' * 50)
for filter, value in sorted(filterPerf.items(), key = lambda x: x[1][0], reverse = True):
gap, gapextend, match, mismatch = filter
print(fmtPerfStr.format(gap, gapextend, match, mismatch, value[0]))
# filterPerf: {filter: nIS, ..., filter: nIS}
def outputPerf(filterPerf):
fmtPerfStr = '{:>7} {:>9} {:>5} {:>8} {:<}'
print(fmtPerfStr.format('gapOpen', 'gapExtend', 'match', 'mismatch', 'matchedISwithBestTIR'))
print('-' * 50)
for filter, num in sorted(filterPerf.items(), key = operator.itemgetter(1), reverse = True):
gap, gapextend, match, mismatch = filter
print(fmtPerfStr.format(gap, gapextend, match, mismatch, num))
# find the IS elements which have TIR found under filters other than best filter
#
# filterPer: {filter: [nIS, {isName, ..., isName}], ..., filter: [nIS, {isName, ..., isName}]}
# filter: (gapopen, gapextend, match, mismatch)
#
# bestTIRfilters: [element1TIRgroup, ..., elementnTIRgroup]
# elementTIRgroup: [(TIR, filter), ..., (TIR, filter)]
#
def TIRbyNonbestfilter_v2(filterPerf, bestTIRfilters):
# get matched TIR info under the best filter
isNamesByBestFilter = (sorted(filterPerf.values(), key = operator.itemgetter(0)))[-1][1]
# get best TIR info under one or more filters
isNamesByFilters = {item[0][0][1] for item in bestTIRfilters}
diffNames = sorted(isNamesByFilters - isNamesByBestFilter)
print('matched ISs under any filter other than the best filter: {}={}-{}\n{}'.format( len(diffNames),
len(isNamesByFilters),
len(isNamesByBestFilter),
diffNames))
print('best TIRs found by filters other than best filter')
print('output ONE of the filters producing the best TIR of the IS element')
print('-' * 50)
for item in bestTIRfilters:
# item[0][0][1]: isName
if item[0][0][1] in diffNames:
# get filters
#for TIRfilter in item:
# gap, gapextend, matrixFile = TIRfilter[1]
# match, mismatch = tools.resolveMatrixFileName(matrixFile)
filters = [TIRfilter[1] for TIRfilter in item]
# output all filters producing the best TIR of the IS element
#print('{} {} {}:'.format(item[0][0][0], item[0][0][1], filters))
#
# output one of the filters producing the best TIR of the IS element
print('{} {} {}:'.format(item[0][0][0], item[0][0][1], filters[0]))
start1, end1, start2, end2, seq1, seq2 = item[0][0][2][-6:]
print('{:>6} {} {:<6}\n{:6} {} {:6}\n{:>6} {} {:<6}'.format(
start1, seq1, end1,
' ', tools.buildMatchLine(seq1, seq2), ' ',
end2, seq2, start2))
# find the IS elements which have TIR found under filters other than best filter
#
# filterPerformance: [(filter, perf, TIRs), ..., (filter, perf, TIRs)]
# filter: (gapopen, gapextend, match, mismatch)
# perf: (nmatch, ndismatch, ndiscard, nIS)
# TIRs: [TIR, ..., TIR]
# TIR: [familyName, isName, ir]
#
# bestTIRfilters: [element1TIRgroup, ..., elementnTIRgroup]
# elementTIRgroup: [(TIR, filter), ..., (TIR, filter)]
#
def TIRbyNonbestfilter(filterPerformance, bestTIRfilters):
# get matched TIR info under the best filter
isNamesByBestFilter = {item[1] for item in filterPerformance[0][2]}
# get best TIR info under one or more filters
isNamesByFilters = {item[0][0][1] for item in bestTIRfilters}
diffNames = sorted(isNamesByFilters - isNamesByBestFilter)
print('matched ISs under any filter other than the best filter: {}={}-{}\n{}'.format( len(diffNames),
len(isNamesByFilters),
len(isNamesByBestFilter),
diffNames))
print('matched TIR found by filters other than best filter')
print('output the first filter producing the best TIR of the IS element')
print('-' * 50)
for item in bestTIRfilters:
# item[0][0][1]: isName
if item[0][0][1] in diffNames:
# get filters
#for TIRfilter in item:
# gap, gapextend, matrixFile = TIRfilter[1]
# match, mismatch = tools.resolveMatrixFileName(matrixFile)
filters = [TIRfilter[1] for TIRfilter in item]
# Option1: output all filters producing the best TIR of the IS element
print('{} {} {}:'.format(item[0][0][0], item[0][0][1], filters))
# Option2: output the first filter producing the best TIR of the IS element
#print('{} {} {}:'.format(item[0][0][0], item[0][0][1], filters[0]))
start1, end1, start2, end2, seq1, seq2 = item[0][0][2][-6:]
matchLine = tools.buildMatchLine(seq1, seq2)
print('{:>6} {} {:<6}\n{:6} {} {:6}\n{:>6} {} {:<6}'.format(
start1, seq1, end1,
' ', matchLine, ' ',
end2, seq2, start2))
# Combine all matched bestTIRs (bestMatchedTIRfilters) and other bestTIRs which are from bestTIRfilters
# but not found in bestMatchedTIRfilters, return the combined TIRfilters.
# bestTIRfilters: [element1TIRgroup, ..., elementnTIRgroup]
# elementTIRgroup: [(TIR, filter), ..., (TIR, filter)]
# filter: (gapopen, gapextend, match, mismatch)
# TIR: [familyName, isName, ir]
# ir: [score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2]
def combineBestTIRfilters(bestMatchedTIRfilters, bestTIRfilters):
TIRfilters = []
for item in bestTIRfilters:
isName = item[0][1]
for itemMatched in bestMatchedTIRfilters:
isNameMatched = itemMatched[0][1]
if isNameMatched == isName:
break
else:
TIRfilters.append(item)
return bestMatchedTIRfilters + TIRfilters
# Calculate TIRs in all IS elements under the specific filter condition
#
#def getPerformanceByFilterBySSW(args2concurrent):
# mfamilyFeatures, mInput4ssw, filter = args2concurrent
def getPerformanceByFilterBySSW(mfamilyFeatures, mInput4ssw, filter):
bestIRs = findIRbySSW(mInput4ssw, filter)
"""
# Shorten each ir to the reasonable length based on constants.maxLenIR
IRs = []
# bestIRs: [IR, ..., IR]
# IR: [familyName, isName, ir]
for IR in bestIRs:
ir = tools.shortenIR(IR[2])
IRs.append([IR[0], IR[1], ir])
"""
IRs = bestIRs
# compare IRs found by SSW with IRs found in IS dataset
#perf, TIRs = compareIRbyISfinder(IRs, mfamilyFeatures)
#
# Compare the predicted IRs with IRs from isfinder, and return the IRs matched by records in ISfinder
perf, matchedTIRs = compareIRbyISfinder_v2(IRs, mfamilyFeatures)
return (perf, matchedTIRs, IRs)
# Calculate performance for each filter
# Return perf: {filter: [nIS, {isNames, ..., isNames}]}
# nIS: len({isNames, ..., isNames}), number of IS element with the best TIR which has the best irScore
# comparing with other TIRs if other TIRs available.
#
# TIRfilters: [element1TIRgroup, ..., elementnTIRgroup]
# elementTIRgroup: [(TIR, filter), ..., (TIR, filter)]
# filter: (gapopen, gapextend, match, mismatch)
# TIR: [familyName, isName, ir]
# ir: [score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2]
def calculatePerf_v2(TIRfilters):
perf = {}
for item in TIRfilters:
isName = item[0][0][1]
for tirfilter in item:
if tirfilter[1] in perf:
perf[tirfilter[1]][0] += 1
perf[tirfilter[1]][1].add(isName)
else:
value = [1, {isName}]
perf[tirfilter[1]] = value
return perf
# Calculate performance for each filter
# Return perf: {filter: nIS}
# nIS: number of IS element with the best TIR which has the best irScore comparing with other TIRs if other TIRs available.
# TIRfilters: [element1TIRgroup, ..., elementnTIRgroup]
# elementTIRgroup: [(TIR, filter), ..., (TIR, filter)]
# filter: (gapopen, gapextend, match, mismatch)
# TIR: [familyName, isName, ir]
# ir: [score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2]
def calculatePerf(TIRfilters):
perf = {}
for item in TIRfilters:
for tirfilter in item:
if tirfilter[1] in perf:
perf[tirfilter[1]] += 1
else:
perf[tirfilter[1]] = 1
return perf
# Return mTIR where only unique tirs among the best TIRs for each IS will be kept,
# Note: there are probably multiple different best TIRs (with identical irScore)
# found by local alignment algorithm.
# mTIR: {isName: (familyName, isName, tirs), ..., isName: (familyName, isName, tirs)}
# tirs: [tir, ..., tir]
# tir: [irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2], ir without score attached
#
# args for function:
# bestTIRfilters: [element1_TIRgroup, ..., elementn_TIRgroup],
# best matched TIRs which can be found under one specific filter or multiple different filters
# elementTIRgroup: [(TIR1, filter1), ..., (TIRn, filtern)]
# TIR: [familyName, isName, ir]
# ir: (score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2)
def independentTIR(bestTIRfilters):
mTIR = {}
# isTirfilters: multiple tirs for one IS element
for isTirfilters in bestTIRfilters:
tirs = []
familyName, isName = isTirfilters[0][0][:2]
# check multiple tirs for each IS element
# tirfilter: one tir
for tirfilter in isTirfilters:
# keep alignment score for each ir
#ir = tirfilter[0][2]
# remove alignment score for each ir
tir = tirfilter[0][2][1:]
tirs.append(tuple(tir))
# remove duplicate ir for each IS
tirs = set(tirs)
mTIR[isName] = (familyName, isName, tirs)
return mTIR
def independentTIRwithScore(bestTIRfilters):
mTIR = {}
# isTirfilters: multiple tirs for one IS element
for isTirfilters in bestTIRfilters:
tirs = []
familyName, isName = isTirfilters[0][0][:2]
# check multiple tirs for each IS element
# tirfilter: one tir
for tirfilter in isTirfilters:
# keep alignment score for each ir
tir = tirfilter[0][2]
tirs.append(tuple(tir))
# remove duplicate ir for each IS
tirs = set(tirs)
mTIR[isName] = (familyName, isName, tirs)
return mTIR
# Convert boundary numbering in short sequence segment to boundary numbering in original full sequence
# mTIR: {isName: (familyName, isName, tirs), ..., isName: (familyName, isName, tirs)}
# tirs: [tir, ..., tir]
# tir: (irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2), ir without score attached
# or
# (score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2), ir with score attached
def restoreBoundary4tir(mTIR, mboundary):
new_mTIR = {}
for isName in mTIR:
# actual boundary
bdstart1, bdend2 = mboundary[isName][0], mboundary[isName][-1]
# pure boundary is used to define tir boundary found by SSW
# Note: SSW consume two short sequences and define boundaries of two sequences
# as 1, Length1 and 1, Length2. When to identify TIR, we use Length1 = Length2
p_bdstart1 = 1
p_bdstart2 = 1
tirs = (mTIR[isName])[-1]
new_tirs = []
for tir in tirs:
p_start1, p_end1, p_start2, p_end2 = tir[-6:-2]
# start1 = bdstart1 + move1 and move1 = p_start1 - p_bdstart1
start1 = bdstart1 + (p_start1 - p_bdstart1)
# end1 - start1 = p_end1 - p_start1
end1 = start1 + (p_end1 - p_start1)
# end2 = bdend2 - move2 and move2 = p_start2 - p_bdstart2
end2 = bdend2 - (p_start2 - p_bdstart2)
# end2 - start2 = p_end2 - p_start2
start2 = end2 - (p_end2 - p_start2)
if len(tir) == 10:
# with alignment score
new_tir = (tir[0], tir[1], tir[2], tir[3],
start1, end1, start2, end2,
tir[-2], tir[-1])
else:
# without alignment score
new_tir = (tir[0], tir[1], tir[2],
start1, end1, start2, end2,
tir[-2], tir[-1])
new_tirs.append(new_tir)
new_tirs.sort(key = tools.irScore, reverse = True)
new_mTIR[isName] = (mTIR[isName][0], mTIR[isName][1], new_tirs)
return new_mTIR
# Define the boundary of two sub-sequences to be concatenated into one pseudo sequence.
# Note: IR does not always starts from terminus though it is true for most IS elements.
#
# orf: (left, right), maximal and maximal distances from the left terminus genome sequence to the most left
# and the most right ORFs, respectively.
# distIR2Orf: (leftMax, leftMin, rightmin, rightMax), the longest and the shortest distances from the potential IS element
# to the most left ORF and those from the most right ORF to the potential IS element, respectively,
# where the IRs lie out of ORFs. The negative value of left or right means that IR is within ORF.
#
def pseudoSeqBoundary(orf, distIR2Orf):
bdStart1 = orf[0] - distIR2Orf[0]
bdEnd1 = orf[0] - distIR2Orf[1]
bdStart2 = orf[1] + distIR2Orf[2]
bdEnd2 = orf[1] + distIR2Orf[3]
return (bdStart1, bdEnd1, bdStart2, bdEnd2)
# orfLeftPos, orfRightPos: the most left and right positions of ORFs
# irLong: allowed maximal length of IR
def pseudoSeqBoundary_v3(orfLeftPos, orfRightPos, irLong):
bdEnd1 = orfLeftPos - 1
bdStart1 = orfLeftPos - irLong
bdStart2 = orfRightPos + 1
bdEnd2 = orfRightPos + irLong
return (bdStart1, bdEnd1, bdStart2, bdEnd2)
# orfLeftPos, orfRightPos: the most left and right positions of ORFs.
# maxDist4ter2orf, minDist4ter2orf: allowed maximum and minimum distance between ends of
# IS element and the nearest ORFs in the same IS element.
def pseudoSeqBoundary_v4(orfLeftPos, orfRightPos, maxDist4ter2orf, minDist4ter2orf):
bdEnd1 = orfLeftPos - minDist4ter2orf
bdStart1 = orfLeftPos - maxDist4ter2orf
bdStart2 = orfRightPos + minDist4ter2orf
bdEnd2 = orfRightPos + maxDist4ter2orf
return (bdStart1, bdEnd1, bdStart2, bdEnd2)
# Return ir
# ir: [score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2]
# seq1, seq2: 'ATCG', only aligned sequence without gap included
# align: PyAlignRes object for alignment result description, which is returend by ssw_wrap.Aligner.align()
# cigarPair: [(4, 'M'), (2, 'I'), (8, 'M'), (1, 'D'), (10, 'M'), (6, 'S')]
# Note: for details of cigar sting, Please check the document "The SAM Format Specification",
# http://samtools.github.io/hts-specs/SAMv1.pdf, particularly the "An example" section and
# "CIGAR: CIGAR string" section.
def getIRbySSWnoGap(seq1, seq2, align, cigarPair):
score = align.score
start1, end1 = align.ref_begin + 1, align.ref_end + 1
# seq2 is the reverse complementary sequence of right end of full seq
#start2, end2 = align.query_end + 1, align.query_begin + 1
start2, end2 = align.query_begin + 1, align.query_end + 1
nGaps = 0
irId = 0
# length of seq2
irLen = align.query_end - align.query_begin + 1
index1, index2 = 0, 0
# process only the aligned sequence area defined by
# seq1[align.ref_begin: align.ref_end+1] and seq2[align.query_begin: align.query_end+1]
seq1 = seq1[align.ref_begin: align.ref_end+1]
seq2 = seq2[align.query_begin: align.query_end+1]
for pair in cigarPair:
if pair[1] == 'I':
nGaps += pair[0]
index2 += pair[0]
elif pair[1] == 'D':
nGaps += pair[0]
irLen += pair[0]
index1 += pair[0]
elif pair[1] == 'M':
s1 = seq1[index1: index1+pair[0]]
s2 = seq2[index2: index2+pair[0]]
for c1, c2 in zip(s1, s2):
if c1 == c2:
irId += 1
index1 += pair[0]
index2 += pair[0]