-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaligntest.py
611 lines (537 loc) · 20.2 KB
/
aligntest.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
#!/usr/bin/env python
import tempfile
from Bio.Align.Applications import MuscleCommandline
from Bio import AlignIO
from io import StringIO
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
from scipy.stats import ttest_1samp
import sys
class NucleotideScoringMatrix(object):
def __init__(self, match=2, mismatch=-2, gapscore=-1):
self.match = match
self.mismatch = mismatch
self.gapscore = gapscore
def score(self, one, two):
if one == two:
return self.match
if(one == '-' or two == '-'):
return self.gapscore
return self.mismatch
class HeteroSearch(object):
def __init__(self, projenv):
self.parameters = projenv.parameters
self.SortedSeqs = projenv.SortedSeqs
self.locusLengthRange = projenv.locusLengthRange
self.msgHandle = projenv
self.MinReadNum = 5
self.MinReadRatio = 0.2
self.MinVariantRatio = 0.3
self.HeteroPvalue = 0.001
self.HetSeqs = {}
self.HetInfo = {}
def Run(self):
self.msgHandle.showMsg ('Searching for heterozygote...', "")
#stderr.write ('\nGenerating consensus sequences...')
MUSCLE = self.parameters.MuscleCMD
try:
for strain in self.SortedSeqs:
strainSeqs = self.SortedSeqs[strain]
for gene in strainSeqs:
if(gene == "unmapped"):
continue
geneSeqs = strainSeqs[gene]
lenRange = self.locusLengthRange[gene]
filteredseqs = self.__SeqFilter(geneSeqs,lenRange,self.MinReadNum)
if(filteredseqs != ""):
alignSeqs = self.__MuscleAlignment(filteredseqs, MUSCLE)
variantBases = self.__getVariants(alignSeqs, self.MinVariantRatio)
(isHet, index) = self.__isHetero(variantBases, self.HeteroPvalue)
if(isHet):
(seqN1, seqN2) = self.__getSeqGroups(alignSeqs,index)
seqs1 = self.__getSeqs(filteredseqs, seqN1)
seqs2 = self.__getSeqs(filteredseqs, seqN2)
aligns1 = self.__MuscleAlignment(seqs1, MUSCLE)
aligns2 = self.__MuscleAlignment(seqs2, MUSCLE)
cons1 = self.__AlignConsensus(aligns1)
cons2 = self.__AlignConsensus(aligns2)
gname1 = gene + "_allele1"
gname2 = gene + "_allele2"
seqrec1 = SeqRecord(Seq(cons1,generic_dna),id=strain,description=gname1)
seqrec2 = SeqRecord(Seq(cons2,generic_dna),id=strain,description=gname2)
heteSeqs = {}
heteSeqs['seq1'] = seqrec1
heteSeqs['seq2'] = seqrec2
straininfo = {}
if(strain in self.HetSeqs):
straininfo = self.HetSeqs[strain]
straininfo[gene] = heteSeqs
self.HetSeqs[strain] = straininfo
hetinfo = {}
if(strain in self.HetInfo):
hetinfo = self.HetInfo[strain]
hetinfo[gene] = 'TRUE'
self.HetInfo = hetinfo
else:
hetinfo = {}
if(strain in self.HetInfo):
hetinfo = self.HetInfo[strain]
hetinfo[gene] = 'FALSE'
self.HetInfo = hetinfo
else:
hetinfo = {}
if(strain in self.HetInfo):
hetinfo = self.HetInfo[strain]
hetinfo[gene] = "NA"
self.HetInfo = hetinfo
self.msgHandle.showMsg ('done!')
return (True, None)
except Exception as e:
return (False, e)
def __isHetero(self, variantBases, maxpvalue):
recnum = len(variantBases)
if(recnum > 0):
#print ("variantsite is %s" %variantBases[0])
#print ("variantlength is %s" %(len(variantBases[0])))
scores = []
for i in range(recnum-1):
seq1 = variantBases[i]
seq2 = variantBases[i+1]
score = alignscore(seq1, seq2)
scores.append(score)
#print ("seq1 %s - seq2 %s: %s" %(i, i+1, score))
isunique, scoreinfo = minScore(scores, self.MinReadRatio)
if(not isunique):
return (False, 0)
else:
t_statistic, p_value = ttest_1samp(scoreinfo['scores'], scoreinfo['minscore'])
print(("minscore: %s\tminindex: %s\tpvalue: %s" %(scoreinfo['minscore'],scoreinfo['minindex'],p_value)))
if(p_value <= maxpvalue):
print ("Is hetero!")
return (True, scoreinfo['minindex'])
return (False, 0)
def __MuscleAlignment(self, sortedseqs, MUSCLE):
tmpfile = tempfile.NamedTemporaryFile('w')
tmpname = tmpfile.name
for seq in sortedseqs:
tmpfile.write(seq.format("fasta"))
tmpfile.flush()
cmdline = MuscleCommandline(MUSCLE,input=tmpname)
STDOUT, STDERR = cmdline()
align = AlignIO.read(StringIO(STDOUT.decode('utf-8')), "fasta")
tmpfile.close()
return align
def __SeqFilter(self,alnseqs,lenRange,minReadNum):
if(len(alnseqs) < minReadNum):return ""
seqs = []
for alnseq in alnseqs:
seq = alnseq.TrimPrimer()
if(len(seq) < lenRange['s1'] or len(seq) > lenRange['s2']) : continue
seqs.append(seq)
if(len(seqs) < minReadNum):return ""
return seqs
def __getVariants(Aligns, ratio = 0.3):
"""Search variant nuclotide in the alignment"""
alignlen = Aligns.get_alignment_length()
lastvariant = 0
allvariant = []
variantBase = {}
recnum = len(Aligns)
for n in range(alignlen):
base_dict = {}
for i in range(recnum):
curbase = Aligns[i].seq[n]
upbase = curbase.upper()
if(curbase not in base_dict):
base_dict[curbase] = 1
else:
base_dict[curbase] += 1
filterbases = __baseFilter(base_dict, recnum, ratio)
if(len(filterbases) > 1):
for j in range(recnum):
curbase = Aligns[j].seq[n]
upbase = curbase.upper()
if(j in variantBase):
variantBase[j] += upbase
else:
variantBase[j] = upbase
return variantBase
def __baseFilter(self, basedict, seqnum, minratio):
filterdict = {}
for base in basedict:
ratio = basedict[base]/seqnum
if(ratio < minratio):
continue
filterdict[base] = basedict[base]
return filterdict
def __minScore(self, scores, ratio = 0.3):
numscores = len(scores)
startindex = int(numscores*ratio)
endindex = numscores - startindex
minscore = scores[startindex]
minindex = startindex
scoredict = {}
for i in range(startindex,endindex + 1):
if(scores[i] not in scoredict):
scoredict[scores[i]] = 1
else:
scoredict[scores[i]] += 1
if(minscore > scores[i]):
minindex = i
minscore = scores[i]
scores.pop(minindex)
scoreinfo = {}
isUnique = True
if(scoredict[minscore] > 1):
isUnique = False
scoreinfo['minscore'] = minscore
scoreinfo['minindex'] = minindex
scoreinfo['scores'] = scores
return(isUnique,scoreinfo)
def __getSeqGroups(self, alignSeqs, index):
seqcount = 0
groupA = []
groupB = []
for i in range(0,index+1):
groupA.append(alignSeqs[i].id)
for j in range(index+1,len(alignSeqs)):
groupB.append(alignSeqs[j].id)
return (groupA, groupB)
def __getSeqs(self, seqs, seqnames):
selSeqs = []
for i in range(len(seqs)):
if(seqs[i].id in seqnames):
selSeqs.append(seqs[i])
return selSeqs
def __AlignConsensus(self, alignment):
consensus = ''
con_len = alignment.get_alignment_length()
gapchar = '-'
#consuscut = self.parameters.ConsensusCut
for n in range(con_len):
base_dict = {}
num_bases = 0
for record in alignment._records:
if n < len(record.seq):
if record.seq[n] not in base_dict:
base_dict[record.seq[n]] = 1
else:
base_dict[record.seq[n]] += 1
num_bases = num_bases + 1
max_bases = []
max_size = 0
for base in base_dict:
if(base_dict[base] > max_size):
max_size = base_dict[base]
max_bases = [base]
elif(base_dict[base] == max_size):
max_bases.append(base)
if gapchar in max_bases: max_bases.remove(gapchar)
if(len(max_bases) == 1):
consensus += max_bases[0]
elif(len(max_bases) > 1):
base = self.__IUPACambiguity(sorted(max_bases))
consensus += base
return consensus
def __IUPACambiguity(self, bases):
base = ''
if(bases == ['A','G']): base = 'R'
elif(bases == ['A','C']): base = 'M'
elif(bases == ['A','T']): base = 'W'
elif(bases == ['C','T']): base = 'Y'
elif(bases == ['C','G']): base = 'S'
elif(bases == ['G','T']): base = 'K'
elif(bases == ['A','C','G']): base = 'V'
elif(bases == ['A','C','T']): base = 'H'
elif(bases == ['A','G','T']): base = 'D'
elif(bases == ['C','G','T']): base = 'B'
elif(bases == ['A','T','C','G']): base = 'N'
else:
raise ValueError ("%s not defined!" %('/'.join(bases)))
return base
def alignscore(seq1, seq2, gapscore = -1, gap_penalty=-1, gap_extension_penalty=-1):
scorematrix = NucleotideScoringMatrix(1,-1)
#(seq1t, seq2t) = trimgap(seq1, seq2)
score = 0
seqlen = len(seq1)
for i in range(seqlen):
matchscore = scorematrix.score(seq1[i],seq2[i])
score += matchscore
return score
def trimgap(seq1, seq2):
(seq1_s, seq1_e) = gaprange(seq1)
(seq2_s, seq2_e) = gaprange(seq2)
startpos = 0
endpos = 0
if(seq2_s > seq1_s):
startpos = seq2_s
else:
startpos = seq1_s
if(seq2_e < seq1_e):
endpos = seq2_e
else:
endpos = seq1_e
trimmed1 = seq1[startpos:endpos]
trimmed2 = seq2[startpos:endpos]
return (trimmed1, trimmed2)
def gaprange(seq):
startpos = 0
endpos = 0
seqlen = len(seq)
i = 0
while(seq[i] == '-'):
startpos += 1
i += 1
revseq = seq.reverse_complement()
i = 0
pos = 0
while(revseq[i] == '-'):
pos += 1
i += 1
endpos = seqlen - pos
return (startpos, endpos)
def SearchVariance(Aligns, ratio = 0.3):
"""Search variant nuclotide in the alignment"""
Nucleotides = ["a","t","c","g","n","A","T","C","G","N","-"]
alignlen = Aligns.get_alignment_length()
lastvariant = 0
allvariant = []
variantBase = {}
recnum = len(Aligns)
for n in range(alignlen):
base_dict = {}
for i in range(recnum):
curbase = Aligns[i].seq[n]
upbase = curbase.upper()
if(upbase not in Nucleotides):
raise ValueError (upbase + "is undefined\n")
if(curbase not in base_dict):
base_dict[curbase] = 1
else:
base_dict[curbase] += 1
if(n == 50):
print("AAA")
filterbases = baseFilter(base_dict, recnum, ratio)
if(len(filterbases) > 1):
for j in range(recnum):
curbase = Aligns[j].seq[n]
upbase = curbase.upper()
if(j in variantBase):
variantBase[j] += upbase
else:
variantBase[j] = upbase
return variantBase
def baseFilter(basedict, seqnum, minratio):
filterdict = {}
for base in basedict:
ratio = basedict[base]/seqnum
if(ratio < minratio):
continue
filterdict[base] = basedict[base]
return filterdict
def minScore(scores, ratio = 0.3):
numscores = len(scores)
startindex = int(numscores*ratio)
endindex = numscores - startindex
minscore = scores[startindex]
minindex = startindex
scoredict = {}
for i in range(startindex,endindex + 1):
if(scores[i] not in scoredict):
scoredict[scores[i]] = 1
else:
scoredict[scores[i]] += 1
if(minscore > scores[i]):
minindex = i
minscore = scores[i]
scores.pop(minindex)
scoreinfo = {}
isUnique = True
if(scoredict[minscore] > 1):
isUnique = False
scoreinfo['minscore'] = minscore
scoreinfo['minindex'] = minindex
scoreinfo['scores'] = scores
return(isUnique,scoreinfo)
def _AlignConsensus(self, alignment):
consensus = ''
con_len = alignment.get_alignment_length()
gapchar = '-'
#consuscut = self.parameters.ConsensusCut
for n in range(con_len):
base_dict = {}
num_bases = 0
for record in alignment._records:
if n < len(record.seq):
if record.seq[n] not in base_dict:
base_dict[record.seq[n]] = 1
else:
base_dict[record.seq[n]] += 1
num_bases = num_bases + 1
max_bases = []
max_size = 0
for base in base_dict:
if(base_dict[base] > max_size):
max_size = base_dict[base]
max_bases = [base]
elif(base_dict[base] == max_size):
max_bases.append(base)
if gapchar in max_bases: max_bases.remove(gapchar)
if(len(max_bases) == 1):
consensus += max_bases[0]
elif(len(max_bases) > 1):
base = self._IUPACambiguity(sorted(max_bases))
consensus += base
return consensus
def _IUPACambiguity(self, bases):
base = ''
if(bases == ['A','G']): base = 'R'
elif(bases == ['A','C']): base = 'M'
elif(bases == ['A','T']): base = 'W'
elif(bases == ['C','T']): base = 'Y'
elif(bases == ['C','G']): base = 'S'
elif(bases == ['G','T']): base = 'K'
elif(bases == ['A','C','G']): base = 'V'
elif(bases == ['A','C','T']): base = 'H'
elif(bases == ['A','G','T']): base = 'D'
elif(bases == ['C','G','T']): base = 'B'
elif(bases == ['A','T','C','G']): base = 'N'
else:
raise ValueError ("%s not defined!" %('/'.join(bases)))
return base
def getSeqGroups(alignSeqs, index):
groupA = []
groupB = []
for i in range(0,index+1):
groupA.append(alignSeqs[i].id)
for j in range(index+1,len(alignSeqs)):
groupB.append(alignSeqs[j].id)
return (groupA, groupB)
def __MuscleAlignment(sortedseqs, MUSCLE):
tmpfile = tempfile.NamedTemporaryFile('w')
tmpname = tmpfile.name
for seq in sortedseqs:
tmpfile.write(seq.format("fasta"))
tmpfile.flush()
cmdline = MuscleCommandline(MUSCLE,input=tmpname)
STDOUT, STDERR = cmdline()
align = AlignIO.read(StringIO(STDOUT.decode('utf-8')), "fasta")
tmpfile.close()
return align
def __isConsIden(seq1,seq2,MUSCLE,MinHetVariants):
NuCoding = ['A','T','C','G']
conSeqs = []
conSeqs.append(seq1)
conSeqs.append(seq2)
align = __MuscleAlignment(conSeqs, MUSCLE)
trimSeq1, trimSeq2 = __trimGap(align[0].seq, align[1].seq)
if(str(trimSeq1) == str(trimSeq2)):
return True
vCount = 0
for i in range(len(trimSeq1)):
if(trimSeq1[i] != trimSeq2[i]):
if(trimSeq1[i] != '-' and trimSeq2[i] != '-'):
if((trimSeq1[i] in NuCoding) and (trimSeq2[i] in NuCoding)):
vCount += 1
elif((trimSeq1[i] in NuCoding) and (trimSeq2[i] not in NuCoding)):
bases = __IUPARevCambiguity(trimSeq2[i])
if(trimSeq1[i] not in bases):
vCount += 1
elif((trimSeq1[i] not in NuCoding) and (trimSeq2[i] in NuCoding)):
bases = __IUPARevCambiguity(trimSeq1[i])
if(trimSeq2[i] not in bases):
vCount += 1
vCount += __gapcount(trimSeq1)
vCount += __gapcount(trimSeq2)
if(vCount <= MinHetVariants):
return True
else:
return False
def __gapcount(seq):
gaps = re.findall(r'-(-+)',str(seq))
gapcount = 0
for i in range(len(gaps)):
gaplen = len(gaps[i]) + 1
gapcount += gaplen
return gapcount
def __trimGap(seq1, seq2):
(seq1_s, seq1_e) = __gapRange(seq1)
(seq2_s, seq2_e) = __gapRange(seq2)
startpos = 0
endpos = 0
if(seq2_s > seq1_s):
startpos = seq2_s
else:
startpos = seq1_s
if(seq2_e < seq1_e):
endpos = seq2_e
else:
endpos = seq1_e
trimmed1 = seq1[startpos:endpos]
trimmed2 = seq2[startpos:endpos]
return (trimmed1, trimmed2)
def __gapRange(seq):
startpos = 0
endpos = 0
seqlen = len(seq)
i = 0
while(seq[i] == '-'):
startpos += 1
i += 1
revseq = seq.reverse_complement()
i = 0
pos = 0
while(revseq[i] == '-'):
pos += 1
i += 1
endpos = seqlen - pos
return (startpos, endpos)
def __IUPARevCambiguity(base):
bases = []
if(base == 'R'): bases = ['A','G']
elif(base == 'M'): bases = ['A','C']
elif(base == 'W'): bases = ['A','T']
elif(base == 'Y'): bases = ['C','T']
elif(base == 'S'): bases = ['C','G']
elif(base == 'K'): bases = ['G','T']
elif(base == 'V'): bases = ['A','C','G']
elif(base == 'H'): bases = ['A','C','T']
elif(base == 'D'): bases = ['A','G','T']
elif(base == 'B'): bases = ['C','G','T']
elif(base == 'N'): bases = ['A','T','C','G']
else:
raise ValueError ("%s not defined!" %('/'.join(bases)))
return bases
if(__name__ == '__main__'):
infile = sys.argv[1]
#import tempfile
#from Bio.Align.Applications import MuscleCommandline
#from io import StringIO
#from Bio.SeqRecord import SeqRecord
#from Bio.Seq import Seq
#from Bio.Alphabet import generic_dna
aligns = AlignIO.read(open(infile, 'rU'), "fasta")
variantBases = SearchVariance(aligns)
recnum = len(variantBases)
if(recnum > 0):
print(("variantsite is %s" %variantBases[0]))
print(("variantlength is %s" %(len(variantBases[0]))))
scores = []
for i in range(recnum-1):
seq1 = variantBases[i]
seq2 = variantBases[i+1]
score = alignscore(seq1, seq2)
scores.append(score)
print(("seq1 %s - seq2 %s: %s" %(i, i+1, score)))
isunique, scoreinfo = minScore(scores, 0.2)
if(not isunique):
print ("Not hetero!")
else:
t_statistic, p_value = ttest_1samp(scoreinfo['scores'], scoreinfo['minscore'])
print(("minscore: %s\tminindex: %s\tpvalue: %s" %(scoreinfo['minscore'],scoreinfo['minindex'],p_value)))
if(p_value < 0.001):
print ("Is hetero!")
seqgroupA, seqgroupB = getSeqGroups(aligns, scoreinfo['minindex'])
print (seqgroupA)
print (seqgroupB)