-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclimb.py
1890 lines (1574 loc) · 61 KB
/
climb.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
# CLIMBED
# Copyright (C) 2015, 2017 University of the Witwatersrand, Johannesburg, South Africa
# Author: Dr Trevor G. Bell, [email protected]
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#!/usr/bin/python
import sys, os, re
from Bio import SeqIO
import Bio.Seq
PROGRAM = 'CLIMBED'
VERSION = '0.4.20140211a'
BASEREFERENCE = { 'A' : 'A', 'C' : 'C', 'G' : 'G', 'T' : 'T', '-' : '-',
'AC' : 'M', 'AG' : 'R', 'AT' : 'W', 'CG' : 'S', 'CT' : 'Y', 'GT' : 'K',
'ACG' : 'V', 'ACT' : 'H', 'AGT' : 'D', 'CGT' : 'B',
'ACGT' : 'N'}
BASES = ['A', 'C', 'G', 'T']
NONBASES = ['M', 'R', 'W', 'S', 'Y', 'K', 'V', 'H', 'D', 'B', 'N', '-']
# http://en.wikipedia.org/wiki/Nucleic_acid_notation
# W and S do not change
BASECOMPLEMENT = {'A' : 'T', 'T' : 'A', 'C' : 'G', 'G' : 'C', '-' : '-', 'N' : 'N',
'K' : 'M', 'M' : 'K', 'R' : 'Y', 'Y' : 'R', 'W' : 'W', 'S' : 'S',
'B' : 'V', 'V' : 'B', 'D' : 'H', 'H' : 'D', 'X' : 'X',
'a' : 't', 't' : 'a', 'c' : 'g', 'g' : 'c', 'n' : 'n',
'k' : 'm', 'm' : 'k', 'r' : 'y', 'y' : 'r', 'w' : 'w', 's' : 's',
'b' : 'v', 'v' : 'b', 'd' : 'h', 'h' : 'd', 'x' : 'x'}
GAP = '-'
DISAMBIGUATE = { 'M' : 'AC', 'R' : 'AG', 'W' : 'AT', 'S' : 'CG', 'Y' : 'CT', 'K' : 'GT',
'V' : 'ACG', 'H' : 'ACT', 'D' : 'AGT', 'B' : 'CGT', 'N' : 'ACGT' }
QUALITYTHRESHOLD = 20
BASESTHRESHOLD = 5
GAPCOLUMNTHRESHOLD = 0.80
AMINOACIDS = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']
HIGHLIGHTAMINOACIDS = {
'Met': 'green',
'Ter': 'red',
'Xaa': 'gray',
'Xaa': 'gray',
'Ala': '#BFBFFE',
'Arg': '#FF80FE',
'Asn': '#8080FE',
'Asp': '#BFFFFE',
'Cys': '#80FFFE',
'Gln': '#9999FF',
'Glu': '#7A7ACC',
'Gly': '#FEFF80',
'His': '#B2B300',
'Ile': '#FEBFBF',
'Leu': '#CCCC00',
'Lys': '#BFFEBF',
'Phe': '#80FE80',
'Pro': '#FE8080',
'Ser': '#FF66CC',
'Thr': '#00B3B2',
'Trp': '#8FFEBF',
'Tyr': '#FEFFBF',
'Val': '#80FE80'
}
SEROPATTERNS = { 'KR...' : 'adr', 'KKP..' : 'adw2', 'KKT..' : 'adw3', 'KK[I|L]..' : 'adw4', 'RR...' : 'ayr',
'RKT..' : 'ayw3', 'RK[I|L]..' : 'ayw4', 'RKPA.' : 'ayw1', 'RKP[^A][^S]' : 'ayw2', 'RKP[^A]S' : 'ayw4' }
SEROGROUP = { 'K' : '(ad)', 'R' : '(ay)' }
GENOTYPES = {'adw2CGTCA[T|Y|C]...C[A|C]' : 'A1',
'ayw1CGTCA[T|Y|C]...C[A|C]' : 'A1',
'adw2CGGCAC...CG' : 'A2',
'ayw1CGTCA[T|Y|C]...CG' : 'A3',
'ayw1CG.......CG' : 'A4',
'adw.TT.......T.' : 'B1/B2/B3/B6',
'ayw.TT.......T.' : 'B3/B4/B5',
'adrTT.......C.' : 'C1/C2',
'ayrTT.......C.' : 'C1/C2',
'adrCG.......C.' : 'C3',
'ayrCG.......C.' : 'C3',
'ayw.TT.......T.' : 'C4',
'adw2CG.......T.' : 'C5',
'ayw[^4]CG.......T.' : 'D',
'ayw4CG.......T.' : 'E',
'adw4TT.......T.' : 'F1/F4',
'adw4TT.......C.' : 'F2/F3/H',
'adw2CG....TAAT.' : 'G' }
HIGHLIGHTSEROTYPES = {
'(ad)' : '#FEFF80',
'(ay)' : '#7A7ACC',
'Unknown' : 'gray',
'adr' : '#FEFFBF',
'adw2' : '#80FE80',
'adw3' : '#B2B300',
'adw4' : '#BFBFFE',
'ayr' : '#FF80FE',
'ayw1' : '#80FFFE',
'ayw2' : '#FF66CC',
'ayw3' : '#9999FF',
'ayw4' : '#BFFFFE'
}
S_START = '[A|a][T|t|C|c|G|g][G|g][G|g][A|a][G|A|C|S|g|a|c|s][A|G|R|a|g|r][A|G|R|a|g|r][C|c][A|a][C|T|c|t]'
B_START = '[A|a|C|c|T|t][T|t|C|c][G|g|A|a][C|T|c|t][A|a][A|a][C|c][T|t][T|t][T|t][T|t][T|t][C|c][A|a][C|c][C|c][T|t][C|c][T|t][G|g]'
TEMPFOLDER = '/tmp/'
MAX_FRAGMENTS = 12
if __name__ == '__main__':
interactive = True
else:
interactive = False
def motd():
divider = '-' * 40 + '\n'
return divider + 'This is %s %s\n\nDependencies:\n\tBioPython from http://www.biopython.org\n\tABIFReader.py from http://www.interactive-biosoftware.com/open-source/ABIFReader.py\n' % (PROGRAM, VERSION) + divider
# ---------------
def error(message):
out = 'Error [%s]: %s' % (sys._getframe(1).f_code.co_name, message)
if interactive:
sys.stderr.write(out + '\n')
else:
sys.exit(out)
def warning(message):
out = 'Warning [%s]: %s ' % (sys._getframe(1).f_code.co_name, message)
if interactive:
print (out)
else:
sys.stderr.write(out)
# ---------------
def parseList(tempcc, aa=False, mappingPos=1): # default mapping is 1:1
'''Returns a start and end value for each distinct entity'''
# For example: 1800-1810 returns 1800 and 1810
# 1820 returns 1820 and 1820
ll = tempcc.split(',')
tempNucList = []
for i in ll:
rr = i.find('-')
if rr != -1:
tt = i.split('-')
start = tt[0]
end = tt[1]
else:
start = end = i
try:
startPos = int(start)
endPos = int(end)
if aa:
startPos = startPos * 3 - 2 # start position
endPos = endPos * 3 # do not subtract 2 -- triplets
tempNucList.append([startPos - mappingPos + 1, endPos - mappingPos + 1]) # a list of the positions requested
except:
error('%s: Bad nucleotide positions' % tempcc)
return False
return tempNucList
# ---------------
def seqShow(ss):
''' Output list (from 'nuc' ('extract') or find for example) in triplet groups '''
for i in range(len(ss)):
print ss[i][0] + '\t',
# each triplet as an entry in a list:
# x = [ss[0][1][x:x+3] for x in range(0, len(ss[0][1]), 3)]
for j in range(0, len(ss[i][1]), 3):
print ss[i][1][j:j+3],
print
# ---------------
def randomStamp():
import datetime, random
return "%s%02i" % (datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d%H%M%S'), random.random()*999)
# ----------------
def contig(F, R):
'''Generate a contig from two input sequences'''
# Method requires two sequences objects which may optionally have been trimmed; objects required because quality scores are required
# Processes the first sequence in each Sequence object
from Bio.Emboss.Applications import NeedleCommandline
from Bio import AlignIO
import subprocess, sys
R.seqRevComp()
randomStampToken = randomStamp() # same token for forward and reverse files
tempOutF = TEMPFOLDER + 'tempOutF-' + randomStampToken
tempOutR = TEMPFOLDER + 'tempOutR-' + randomStampToken
F.writeFASTA(tempOutF)
R.writeFASTA(tempOutR)
# Using BioPython tools to call needle with prepared files
# Uses subprocess to pipe stdout, which avoids making a temporary output file
cline = NeedleCommandline(asequence=tempOutF, bsequence=tempOutR, gapopen=10, gapextend=0.5, stdout=True, auto=True)
child = subprocess.Popen(str(cline), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=(sys.platform!="win32"))
align = AlignIO.read(child.stdout, "emboss")
# Quality scores always preceed bases
pos1 = -1 # track the actual base position regardless of gaps
pos2 = -1
gap = '-'
cons = ''
# use a moving window around the current pair of bases
# the quality of the bases in this window will be conisidered
CW = BASESTHRESHOLD # CW ~ ContigWindow
QT = QUALITYTHRESHOLD # shorter to type and only one change here if module name is changed
pairBaseGood = 1.0
pairBaseBase = 0.75
pairBaseNon = 0.67
pairGapBase = 0.50
pairBaseBasePoor = 0.33
PairNon = 0.25
CQ = 0.0 # Contig Quality
for i in range(len(align[0].seq)):
base1 = align[0].seq[i]
base2 = align[1].seq[i]
if base1 != gap:
pos1 += 1
if base2 != gap:
pos2 += 1
qual1 = F.QS[pos1 + F.trimLeft]
qual2 = R.QS[pos2 + R.trimLeft]
window1 = [pos1 + F.trimLeft - CW, pos1 + F.trimLeft + CW]
window2 = [pos2 + R.trimLeft - CW, pos2 + R.trimLeft + CW]
if window1[0] < 0:
window1[0] = 0
if window1[1] > len(F.seq[0]['seq']):
window1[1] = len(F.seq[0]['seq'])
if window2[0] < 0:
window2[0] = 0
if window2[1] > len(R.seq[0]['seq']):
window2[1] = len(R.seq[0]['seq'])
baseWin1 = F.seq[0]['seq'][window1[0]:window1[1]+1]
baseWin2 = R.seq[0]['seq'][window2[0]:window2[1]+1]
qualWin1 = sum(F.QS[window1[0]:window1[1]+1]) // (CW * 2 + 1) # integer division
qualWin2 = sum(R.QS[window1[0]:window1[1]+1]) // (CW * 2 + 1)
# print "pos1:%03i qual1:%i base1:%s window1:%03i-%03i basewin1:%s qualwin1:%i | pos2:%03i qual2:%i base2:%s window2:%03i-%03i basewin2:%s qualwin2:%i" % (pos1, qual1, base1, window1[0], window1[1], baseWin1, qualWin1, pos2, qual2, base2, window2[0], window2[1], baseWin2, qualWin2)
# using (quality score of base (qual) OR quality score of window (window) means that
# an indiviual good quality base is never lost, but also that one poor quality base
# surrounded by good quality bases is not removed
# base1 is a gap and base2 to is not a gap and (base2 quality score OR quality score of window2 >= quality threshold)
if base1 == gap and base2 != gap and (qual2 >= QT or qualWin2 >= QT):
# print i, base1, qual2, base2
cons += base2
CQ += pairGapBase
# base2 is a gap and base1 to is not a gap and (base1 quality score OR quality score of window1 >= quality threshold)
elif base1 != gap and base2 == gap and (qual1 >= QT or qualWin1 >= QT):
# print i, qual1, base1, base2
cons += base1
CQ += pairGapBase
# if one of the bases is a gap and the one which is not a gap has BOTH a quality score and a quality score of window below threshold, then nothing is added to the consensus
# Bases do not match:
elif base1 != base2 and base1 != gap and base2 != gap: # extra clauses just to ensure that neither are gaps
# If both are ACGT then use the one with the highest quality score as long as it is above qualityThreshold
# If only one is ACGT, then use that one (currently regardless of quality)
# If neither are ACGT, then use the one with the best quality (above quality threshold)
if base1 in BASES and base2 in BASES:
if qual1 >= qual2 and qual1 >= QT:
cons += base1
CQ += pairBaseBase
elif qual2 >= QT:
cons += base2
CQ += pairBaseBase
# both are ACGT but neither are above qualityThreshold
elif qual1 > qual2: # base1 quality is better
cons += base1
CQ += pairBaseBasePoor
elif qual2 < qual1: # base2 quality is better
cons += base2
CQ += pairBaseBasePoor
elif qualWin1 > qualWin2: # base1 window quality is better; will only execute if bases are = quality
cons += base1
CQ += pairBaseBasePoor
else:
cons += base2
CQ += pairBaseBasePoor
elif base1 in BASES and qual1 >= QT: # base1 is ACGT so base2 is not
cons += base1 # use base1, regardless of quality
CQ += pairBaseNon
elif base2 in BASES and qual2 >= QT: # base2 is ACGT so base1 is not
cons += base2 # use base2, regardless of quality
CQ += pairBaseNon
else:
if qual1 >= QT: # it's not ACGT, but if quality score is above threshold, add it
cons += base1
CQ += pairNon
elif qual2 >= QT: # ditto; if this is not met, then nothing is added
cons += base2
CQ += pairNon
else:
cons += base1
CQ += pairBaseGood
# print cons
# print "Consensus Length %i" % (len(cons))
# c = 0
# for i in cons:
# if i not in BASES:
# c += 1
# print "%i of %i (%3.2f%%) bases are ambiguous" % (c, len(cons), float(c)/len(cons) * 100)
# return contig, CW, aligned forward and reverse sequences, original forward and reverse sequences
# the original, untrimmed sequence is not available, as this was trimmed when the chromatogram was loaded
return [[">Contig_%s_%s" % (F.seq[0]['id'][1:], R.seq[0]['id'][1:]), cons], CQ/len(cons), [">Aligned_Forward_%s" % (F.seq[0]['id'][1:]), str(align[0].seq)], [">Aligned_Reverse_%s]" % (F.seq[0]['id'][1:]), str(align[1].seq)], [F.seq[0]['id'], F.seq[0]['seq']], [R.seq[0]['id'], R.seq[0]['seq']]]
# ---------------
def fragmentmerger(mergeFiles, FRAGABIF=[False] * MAX_FRAGMENTS, X=[BASESTHRESHOLD] * MAX_FRAGMENTS, Y=[QUALITYTHRESHOLD] * MAX_FRAGMENTS, R=[False] * MAX_FRAGMENTS, C=[False] * MAX_FRAGMENTS, mergeID='', slideMotif='', slidePosition=0):
'''Call EMBOSS merge to merge the fragments'''
import subprocess, sys
numFrags = len(mergeFiles)
MergeObject = []
m = []
for i in range(numFrags):
MergeObject.append(Sequence())
m.append(MergeObject[i].load(mergeFiles[i], ABIF=FRAGABIF[i], minGoodBases=X[i], minGoodQuality=Y[i]))
tooLow = []
for i in range(numFrags):
if m[i] == None and FRAGABIF[i]:
tooLow.append(i+1)
if len(tooLow) > 0:
print "Chromatogram quality too low (fragment/s %s trimmed to zero length)." % (tooLow)
sys.exit(2)
# Save the trimmed FASTA file locally
randomToken = randomStamp()
fileM = []
for i in range(numFrags):
fileM.append('%sMerge%i-%s.fasta' % (TEMPFOLDER, i+1, randomToken))
fileM.append('%sMerge0-%s.fasta' % (TEMPFOLDER, randomToken)) # file '0' is the merged file at index numFrags
for i in range(numFrags):
MergeObject[i].seqRevComp(rev=R[i], comp=C[i])
# mergeID = ''
# for i in range(numFrags):
# mergeID += MergeObject[i].seq[0]['id']
# MergeObject[0].seq[0]['id'] = mergeID
for i in range(numFrags):
MergeObject[i].save(fileM[i])
# command = 'merger -asequence %s -bsequence %s -auto -outfile /dev/null -outseq /dev/stdout | merger -asequence /dev/stdin -bsequence %s -auto -outfile /dev/null -outseq /dev/stdout | merger -asequence /dev/stdin -bsequence %s -auto -outfile /dev/null -outseq /dev/stdout | merger -asequence /dev/stdin -bsequence %s -auto -outfile /dev/null -outseq /dev/stdout | merger -asequence /dev/stdin -bsequence %s -auto -outfile /dev/null -outseq %s' % (fileM1, fileM2, fileM3, fileM4, fileM5, fileM6, fileM7)
# merger -asequence %s -bsequence %s -auto -outfile /dev/null -outseq /dev/stdout |
# merger -asequence /dev/stdin -bsequence %s -auto -outfile /dev/null -outseq /dev/stdout |
# merger -asequence /dev/stdin -bsequence %s -auto -outfile /dev/null -outseq /dev/stdout |
# merger -asequence /dev/stdin -bsequence %s -auto -outfile /dev/null -outseq /dev/stdout |
# merger -asequence /dev/stdin -bsequence %s -auto -outfile /dev/null -outseq %s
# % (fileM1, fileM2, fileM3, fileM4, fileM5, fileM6, fileM7)
# A --> merger -asequence %s -bsequence %s -auto -outfile /dev/null -outseq /dev/stdout
# B --> merger -asequence /dev/stdin -bsequence %s -auto -outfile /dev/null -outseq /dev/stdout
# C --> merger -asequence /dev/stdin -bsequence %s -auto -outfile /dev/null -outseq %s
# n = 2 (1 2 0) : merger -asequence %s -bsequence %s -auto -outfile /dev/null -outseq %s
# n = 3 (1 2 3 0) : A C
# n > 3 (1 2 3 ... 0): A B{n-3} C
# Therefore, can be generalized into A B{n-3} C for all cases where n >= 3
fileM_Save = fileM[:]
outCount = 1
outFile = TEMPFOLDER + 'outFile%02i.txt' % outCount
if numFrags == 2: # two fragments
command = 'merger -awidth 99999 -asequence %s -bsequence %s -auto -outfile %s -outseq %s' % (fileM[0], fileM[1], outFile, fileM[numFrags])
else:
command = 'merger -awidth 99999 -asequence %s -bsequence %s -auto -outfile %s -outseq /dev/stdout | '
fileM.insert(2, outFile)
for i in range(numFrags - 3):
command += 'merger -awidth 99999 -asequence /dev/stdin -bsequence %s -auto -outfile %s -outseq /dev/stdout | '
for i in range(numFrags - 3):
outCount += 1
outFile = TEMPFOLDER + 'outFile%02i.txt' % (outCount)
fileM.insert((i+2)*2, outFile)
command += 'merger -awidth 99999 -asequence /dev/stdin -bsequence %s -auto -outfile %s -outseq %s'
outCount += 1
outFile = TEMPFOLDER + 'outFile%02i.txt' % (outCount)
fileM.insert(len(fileM)-1, outFile)
command = command % (tuple(fileM))
return_code = subprocess.call(command, shell=(sys.platform != "win32"))
MergedOut = Sequence()
MergedOut.load(fileM_Save[numFrags])
if len(mergeID) > 0:
MergedOut.seq[0]['id'] = mergeID
MergedOut.seqCase() # Convert to uppercase
if len(slideMotif) > 0: # do slide here rather than using method, which would slide all sequences in the object
if (slidePosition > 0) and (slidePosition < len(MergedOut.seq[0]['seq'])):
start = MergedOut.seq[0]['seq'].find(slideMotif)
newStart = slidePosition - 1 - start # Python indexes strings from zero
if start >= 0:
MergedOut.seq[0]['seq'] = MergedOut.seq[0]['seq'][-newStart:] + MergedOut.seq[0]['seq'][:-newStart]
MergedOut.mergeSlide = True
MergedOut.save(MergedOut.fileName, overWrite=True)
return ((MergedOut,) + tuple(MergeObject[:numFrags]))
# --------------------
def fetchGenBank(sequenceList, emailAddress):
'''Fetch sequences from GenBank and return object'''
# Returns a sequence object
# To append fetched sequences to an existing object,
# interate over the sequences and append them
from Bio import Entrez, SeqIO
Entrez.email = emailAddress
seqs = len(sequenceList)
Fetch = Sequence()
count = 0
badSeq = 0
for seq in sequenceList:
handle = Entrez.efetch(db="nucleotide", rettype="gb", id=seq)
if len(handle.peekline()) == 1: # peek at the next line without consuming it
# print "%s is an invalid accession number and has been ignored" % seq
badSeq += 1 # what else to do?
else:
record = SeqIO.read(handle, "genbank")
Fetch.seq.append({'id': record.id, 'seq': str(record.seq)}) # omit .data for BioPython Sequence Object
# what about record.description?
count += 1
return Fetch
# ---------------
def fileToList(seqFilename):
seq = []
seqFile = open(seqFilename, 'r')
for line in seqFile:
seq.append(line.strip()) # remove trailing newline
seqFile.close()
return seq
# ---------------
def distributionShow(D, loci, numSeqs, rowList=BASES+NONBASES, percentage=True, html=False, suppressZeros=False, firstCell=''):
'''Output table of distribution or bases (default) or motifs'''
# shade alternate rows / bold font for A, C, G, T
# D is the list of dictionaries output by the baseDistribution method
# or a list of the motifs; in this case the loci parameter
# should only contain one position as only one column is output
if html:
delim = '</td><td>'
linestart = '<tr><td>'
lineend = '</td></tr>\n'
boldon = '<b>'
boldoff = '</b>'
else:
delim = '\t'
linestart = ''
lineend = '\n'
boldon = ''
boldoff = ''
out1 = linestart + firstCell
if loci != '0':
for i in parseList(loci):
for j in range(i[0], i[1]+1):
out1 += delim + '%s%i%s' % (boldon, j, boldoff)
out1 += lineend
else:
out1 += delim + boldon + 'Distribution' + boldoff
if loci == '0': # if loci = '0' then not bases, so then sort rowlist by dictionary *value*
tempSort = []
for kk, vv in D[0].iteritems(): # extract the dictionary from the list
tempSort.append([kk, vv])
tempSort = sorted(tempSort, key=lambda element: (element[1], element[0])) # ascending order of "value, key"
rowList = []
for tempLoop in tempSort:
rowList.append(tempLoop[0])
out2 = ''
for i in rowList: # loop through each base; force the order
tt1 = ''
for tt2 in i:
tt1 = tt1 + tt2 # + '\t'
out2 += linestart + boldon + tt1 + boldoff # row heading
for j in D:
out2 += delim
if (not suppressZeros) or (j[i] != 0): # populate table if value is not zero or if suppressZeros is false
if percentage:
out2 += '%06.2f' % (j[i] / float(numSeqs) * 100)
else:
out2 += '%3i' % (j[i])
else:
out2 += ' '
out2 += lineend
# print out2
return out1 + out2
# ---------------
def robustTranslate(ss):
'''Use BioPython functionality to translate codons into amino acids'''
if len (ss) != 3:
return None
import Bio.SeqUtils
if ss.find('-') >= 0:
return ('-', '---') # means that at least one position is a gap
ss = ss.upper()
ss = ss.replace('U', 'T') # so that translation to three-letter code works
for i in range(3):
if ss[i] not in BASES + NONBASES:
return ('#', '###') # means that at least one position is not a base or an ambiguous base
single = Bio.Seq.translate(ss)
return (single, Bio.SeqUtils.seq3(single))
# ---------------
def translateLociShow(TT, html=False, highlightAminoAcids=True):
'''Output translation loci data in a table'''
if html:
delim = '</td><td>'
newline = '</td></tr>'
linestart = '<tr><td>'
boldon = '<b>'
boldoff = '</b>'
else:
delim = '\t'
newline = '\n'
linestart = ''
boldon = ''
boldoff = ''
out = linestart + delim # need two delimeters at the start of the line -- one for the reading frame and one for the sequence ID
JJ = TT[0][2].keys() # keys
JJ.sort()
for i in JJ:
out += '%s%s%s%s' % (delim, boldon, i, boldoff)
out += newline
# Order of output must match order provided via 'loci'
for i in TT:
out = out + linestart + boldon + str(i[0]) + boldoff + delim + i[1]
for j in JJ:
# j is the key
print i[2][j][1]
threeLetter = robustTranslate(i[2][j])[1]
if highlightAminoAcids and html and threeLetter in HIGHLIGHTAMINOACIDS:
if threeLetter in ['Met', 'Ter']:
highlightFont = '; color:white'
else:
highlightFont = ''
out = out + '<td style="background-color:%s%s">'% (HIGHLIGHTAMINOACIDS[threeLetter], highlightFont) + i[2][j] + ' ' + threeLetter # output only the three-letter amino acid code
else:
out = out + delim + i[2][j] + ' ' + threeLetter # output only the three-letter amino acid code
out += newline
return out
# ---------------
def tabulateList(l, html=True, border=0, padding=0, header=False):
'''Create an HTML (default) or tab-delimited table of a list'''
# add alternate row shading
# border, padding and header only applicable to HTML mode; ignored when html == False
if html:
# linebreaks inserted for neater HTML
tableStart = '<table border="%s" cellpadding="%s">\n' % (str(border), str(padding))
tableEnd = '</table>\n'
lineStart = '<tr>'
lineEnd = '</tr>\n'
dividerStart = '<td>'
dividerEnd = '</td>'
headerStart = '<b>'
headerEnd = '</b>'
else:
tableStart = ''
tableEnd = ''
lineStart = ''
lineEnd = '\n'
dividerStart = ''
dividerEnd = '\t'
out = tableStart
for i in l:
out += lineStart
outTemp = ''
for j in i:
jj = str(j)
if len(jj) == 0 and html: # empty cell
jj = ' '
if not header:
outTemp += '%s%s%s' % (dividerStart, jj, dividerEnd)
else:
if html: # only process header in html mode
outTemp += '%s%s%s%s%s' % (dividerStart, headerStart, jj, headerEnd, dividerEnd)
out += outTemp
out += lineEnd
header = False # header will be done after first pass
out += tableEnd
return out
# ---------------
# mutation object? has "strip" as method?
def mutationStrip(mm):
# remove leading prefix and nucleotide and trailing nucleotide
out = ''
digits = '0123456789'
for i in mm:
if i in digits:
out += i
return out
# ---------------
class Sequence:
def __init__(self):
self.fileLoaded = False
self.fileName = ''
self.changed = False;
self.seq = [] # dictonary to store description and sequence
self.fileType = ''
self.QS = []
self.originalCalls = ''
self.trimThreshold = None
self.trimLeft = None
self.originalLength = None
self.trimRight = None
self.trimGoodBases = None
self.trimGoodQuality = None
self.linenumbers = 0
self.truncate = 20 # always applied; set to large value to 'disable'
self.totalCount = 0
self.mergeSlide = False
# ---------------
def seqLength(self, cc=''):
'''Return sequence ID and length'''
cc = cc.split()
out = []
if not self.fileLoaded:
error('No file loaded')
else:
for i in range(len(self.seq)):
out.append((self.seq[i]['id'][:self.truncate], len(self.seq[i]['seq'])))
return out
# ---------------
def status(self):
'''Return status'''
if not self.fileLoaded:
error('No file loaded')
else:
return (self.fileName, len(self.seq), self.fileType, self.trimThreshold, self.trimLeft, self.trimRight, self.changed)
# ---------------
def load(self, cc, ABIF=False, autoTrimThreshold=0, minGoodBases=BASESTHRESHOLD, minGoodQuality=QUALITYTHRESHOLD, filterPattern='.+', filterInclude=True):
'''Load sequence data from a file'''
# minGoodBases and minGoodQuality are ignored when autoTrimThreshold is specified
# filterPattern to filter sequence IDs according to regular expression
# filterInclude = True includes only sequences matching the filter pattern
# filters are only applicable to FASTA files, as these can contain multiple sequences
# filters will be ignored when an ABIF file is specified (this may change in future, but the benefit
# to filting out an ABIF file is obscure -- the file would not be loaded if the filter did not match,
# which may be the point in that case)
if len(cc) < 1:
error('Load what?')
cc = [cc]
if self.fileLoaded:
error('Cannot load file %s: File %s already loaded' % (cc[0], self.fileName))
try:
if cc[0][0] in ["'", '"'] and cc[0][len(cc[0])-1] in ["'", '"']:
cc[0] = cc[0][1:len(cc[0])-1]
if ABIF:
import ABIFReader
try:
f = ABIFReader.ABIFReader(cc[0])
except:
print "Bad chromatogram file: %s" % os.path.split(cc[0])[1] # clumsy but effective
sys.exit(1)
else:
f = open(cc[0], 'r')
except IOError:
error('Error opening file %s' % cc[0])
else:
self.fileLoaded = True
self.fileName = cc[0]
if not ABIF:
for record in SeqIO.parse(f, "fasta"):
# id repeated as first part of description, so storing description only
# length no longer stored here; can be determined on the fly
# filter each input sequence ID
self.totalCount += 1 # total all sequences in the file to output include/exclude if relevant
filterFound = (re.search(filterPattern, record.description) != None) # return True of found
if filterFound == filterInclude:
self.seq.append({'id': record.description, 'seq': str(record.seq)})
self.originalLength = len(str(record.seq))
self.trimLeft = 0
self.trimRight = 0
# (filterfound == True and filterInclude == True) or (filterFound == False and filterInclude == False)
# are the two conditions under which the sequence should be included
# condition above implements this in one condition
if len(self.seq) < 1:
if self.totalCount > 1:
print "All sequences excluded by filter pattern: %s" % filterPattern
else:
print "Bad FASTA file: %s" % os.path.split(cc[0])[1] # clumsy but effective
sys.exit(1)
self.fileType = 'FASTA'
else:
tempID = f.getData('SMPL') # Sample ID used as FASTA identifier
if len(tempID) == 0 or tempID == None:
tempID = cc[0] # Filename instead
base = f.getData('PBAS') # Base Calls
qual = f.getData('PCON') # Quality Scores
self.date = f.getData('RUND') # Start run date
self.QS = []
for i in qual:
self.QS.append(ord(i))
self.originalCalls = base # preserve the original base calls (as required by fragmentmerger)
if autoTrimThreshold > 0:
Qleft = 0
while self.QS[Qleft] < autoTrimThreshold:
Qleft += 1
Qright = len(base) - 1 # indexed from 0
while self.QS[Qright] < autoTrimThreshold:
Qright -= 1
if Qleft <= 0: # first base is above threshold
Qleft = 1
if Qright >= len(base):
Qright = len(base) - 2 # ?
base = base[Qleft-1:Qright+1]
self.trimThreshold = autoTrimThreshold
self.trimLeft = Qleft
self.trimRight = Qright
else:
c = 0 # counter
i = 0 # position in sequence
while i < len(self.QS) and c < minGoodBases: # still in the sequence and counter < minimum consecutive bases
if self.QS[i] >= minGoodQuality:
c += 1
else:
c = 0
i += 1
if i >= len(self.QS): # reached the right of the string
f.close()
return None
# error('No good window found searching from the left') # this could happen if minGoodQuality is too high
else:
self.trimLeft = i - minGoodBases # start of 'good' sequence is X bases 'back' from i
c = 0 # counter
i = len(self.QS)-1 # position in sequence, indexed from 0, starting from the right
while i > 0 and c < minGoodBases: # still in the sequence and counter < minimum consecutive bases
if self.QS[i] >= minGoodQuality:
c += 1
else:
c = 0
i -= 1
if i == 0: # reached the left of the string
f.close()
return None
# error('No good window found searching from the right') # this could happen if minGoodQuality is too high
else:
self.trimRight = len(self.QS) - i - minGoodBases - 1
self.originalLength = len(base)
base = base[self.trimLeft:len(self.QS)-self.trimRight]
self.trimGoodBases = minGoodBases
self.trimGoodQuality = minGoodQuality
tempID += '_(Trimmed_%i_%i)' % (minGoodBases,minGoodQuality) # no space so trimmed annotation part of ID
self.seq.append( {'id': tempID, 'seq': base}) ## MARK A ##
self.fileType = 'ABIF'
f.close()
return self.status()
# ---------------
def save(self, cc, overWrite=False):
'''Save sequence data to a file'''
# Saves as FASTA
# Saving with a new name makes that name the 'active' name
cc = cc.split()
if len(cc) < 1:
error('Save what?')
if len(cc) > 1:
error('Specify filename to save')
if not self.fileLoaded:
error ('Cannot save file %s: No file loaded' % (cc[0]))
if cc[0][0] in ["'", '"'] and cc[0][len(cc[0])-1] in ["'", '"']:
cc[0] = cc[0][1:len(cc[0])-1]
if os.path.exists(cc[0]) and not overWrite:
error('File exists; specify overWrite=True to overwrite')
try:
f = open(cc[0], 'w')
except IOError:
error('Error creating file %s' % cc[0])
else:
self.changed = False
self.fileName = cc[0]
for i in self.seq:
if i['id'] is not None: # do not write out empty entries
f.write('>' + i['id'] + '\n') # id and description
f.write(i['seq'] + '\n') # sequence data
f.close()
return self.status()
# ---------------
def unload(self, override=False):
'''Unload file'''
if self.fileLoaded:
if self.changed and not override:
warning('Data changed; specify override=True to unload')
return None
t = self.fileName
self.__init__()
return None
else:
error('Cannot unload: No file loaded')
# ---------------
def extract(self, cc, aain=False, aaout=False, mapping=1, inData=''):
'''Return proteins from a nucleotide sequence'''
# Base distributions are not returned by this method, as it would be difficult
# to encapsulate totals for each base for each position requested,
# and difficult to disentangle these (map them back to positions);
# the same may be true of the bases themselves, but these are only single characters
# and produce a 'pattern' or 'motif' which can be processed
cc = cc.split()
out = []
if len(cc) < 1:
error('Specify nucloetide position/s')
if len(cc) > 1:
error('Bad position syntax')
if cc[0].find(' ') != -1:
error('Spaces not permitted in positions')
if aain:
nucList = parseList(cc[0], mappingPos=mapping, aa=True)
else:
nucList = parseList(cc[0], mappingPos=mapping)
if inData == '':
inData = self.seq
for i in inData:
t = i['id'][:self.truncate]
tempout = ''
for j in nucList:
tempout += i['seq'][j[0]-1:j[1]]
if aaout:
out.append((t, Bio.Seq.Seq(tempout).translate().data))
else:
out.append((t, tempout))
return out
# ---------------
def nucCopy(self, cc):
'''Crop sequences'''
self.changed = True
c = 0
for i in self.extract(cc):
self.seq[c]['seq'] = i[1] # update sequence data only
c += 1
# ---------------
def find(self, cc, aain=False, aaout=False, readingframe=0):
'''Return all occurrences of a regular expression in a nucleotide sequence'''
# Returns nucleotide position and, if relevant, amino acid position
# find over the gap
# does not return anything if search string not found in sequence (report)
# returns multiple hits -- some way to limit?
# output in format which can be added as a new object?
# removed "context" in output as this did not work well with aain and aaout...
# supplying aain=False aaout=True with context makes no sense
if not self.fileLoaded:
error('No file loaded')
if len(cc) < 1:
error('Specify regular expression to find')
out = []
outLength = len(cc)
if aain != aaout:
if aain and not aaout:
outLength = outLength * 3
else:
outLength = outLength / 3 # not aain and aaout
for i in self.seq:
iiid = i['id']
if aain:
# Cannot translate gapped sequences; replace - with N for translation to "X"
ii = i['seq'][readingframe:].replace('-', 'N')
ii = Bio.Seq.Seq(ii).translate().data
else:
ii = i['seq']
findTemp = re.finditer(cc, ii)
for foundItem in findTemp:
startPos = foundItem.start()
endPos = foundItem.end()
if startPos < 0:
startPos = 0
if endPos > len(ii):
endPos = len(ii)
pos = foundItem.start()+1
if aain:
nucpos = pos * 3 - 2 + readingframe
aapos = pos