-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTranslation.py
More file actions
executable file
·1819 lines (1577 loc) · 45.3 KB
/
Translation.py
File metadata and controls
executable file
·1819 lines (1577 loc) · 45.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import FastaManager,sys,os,ParseBlast,FileUtility,BlastUtility,string,time
#from string import *
from bisect import bisect
class translate:
##
# This is not for general things but for peptides derived from EST contigs.
#
# If searching for a nt_code and it is not found after a gap larger than 2
# and the next 3 nt doesn't match the next aa, it will return an error
# message for that particular sequence.
#
# This method ABSOLUTELY dependent that the correct corresponding start of
# the sequence is given. It is not good at all in finding the start then
# get the rest.
#
# @param pep peptide sequence, this should be derived from the nt seq
# either through direct translation or through extracted cds
# The seq comes with orientation information and coordinates.
# using tblastn. Either identical or very similar.
# @param nt nucleotide sequence.
# @param exclstop [1] or not [0, default]
#
##
def bt(self,pep,cds,exclstop):
# store sequences into dict
manager = FastaManager.fasta_manager()
print ("Load pep file...")
pdict = manager.fasta_to_dict(pep,0)
print ("Load cds file...")
ndict = manager.fasta_to_dict(cds,0)
code = self.get_aa_code()
oup = open(pep+".cds.fa","w")
print ("Total %i pep sequences:" % len(pdict.keys()))
countS = 0
for i in pdict.keys(): # each peptide
if countS % 1e2 == 0:
print (" %i x 100" % (countS/1e2))
countS = countS+1
id = i
aa = pdict[i] # peptide seq
nt = "" # get the corresponding nucleotide seq
L = 0
R = 0
# parse coordinates
if id.find("_") == -1:
print ("No coord delimiter found, skip:",id)
continue
id = i.split("_")
L = int(id[-2])
R = int(id[-1])
# reassemble ID so those with "_" in ID can be conserved
id = i[:i.find("_%s_%s" %(id[-2],id[-1]))]
#print "",id,L,R
# extract nt sequence and make sure it is the right orientation
if ndict.has_key(id):
if L<R:
nt = ndict[id][L-1:R]
else:
nt = ndict[id][R-1:L]
nt = self.complement(nt)
nt = self.reverse2(nt)
else:
print ("NOT in ndict, skip:",id)
continue
#print ">",aa
#print ">",nt
if exclstop:
seq,firstMis = self.matching(code,aa,nt)
else:
seq,firstMis = self.back_translate(code,aa,nt)
if seq != "":
oup.write(">%s\n%s\n" % (i,seq))
else:
print (" %s ->no sequence..." % i)
if firstMis:
print (" %s ->first AA mismatch" % i)
def matching(self,code,aa,nt):
firstMis = 0
# check if the first aa is at the beginning, skip the first if it is
# mismatched. Assuming from the second one, it will be ok...
if not nt[:3] in code[aa[0]]:
firstMis = 1
P = 1
else:
P = 0
# read aa seq and match nt, generate synthetic cds
seq = ""
N = 0
for i in range(P,len(aa)):
if aa[i] not in code:
print ("Unknown code:",aa[i])
if aa[i] == "B":
N += 3
else: # such as X
pass
else:
for j in range(N,len(nt)):
if nt[j:j+3] in code[aa[i]]:
seq += nt[j:j+3]
N = j+3
break
elif j+4<len(nt) and nt[j+1:j+4] in code[aa[i]]:
seq += nt[j+1:j+4]
N = j+4
break
elif j+5<len(nt) and nt[j+2:j+5] in code[aa[i]]:
seq += nt[j+2:j+5]
N = j+5
break
if seq[-3:] in code["*"]:
seq = seq[:-3]
return seq,firstMis
##
# This is part of the back translate function. Just make the reiteration
# part into an independent method
##
def back_translate(self,code,aa,nt):
#print aa
#print nt
firstMis = 0
# check if the first aa is at the beginning
if not nt[:3] in code[aa[0]]:
firstMis = 1
print ("",aa[0])
print ("",nt[:3])
cn = 0 # count nt
# skip the first if it is mismatched. Assuming from the second one, it
# will be ok...
if firstMis:
ca = 1
else:
ca = 0
g = 0 # count gap
seq = ""
last = "" # the previous nt code
reset= 0
# each aa in that peptide
while ca < len(aa):
if not aa[ca] in code.keys():
ca = ca+1
continue
#print "",aa[ca]
if cn+3 > len(nt):
#print nt[cn:]
#print "End of nt sequence!"
break
if nt[cn:cn+3] in code[aa[ca]]:
if last != "":
#print " addL>",last,"gap:%i-%i" % (cn-3-g,cn-3-1)
seq = seq + last
last = ""
g = 0
#print " add >",nt[cn:cn+3],aa[ca]
seq = seq + nt[cn:cn+3]
cn = cn+3
else:
# give the previous one up,evaluate the current one again
if last != "":
#print " omit > %s, no match" % aa[ca]
# reset
last = ""
cn = cn-g
g = 0
continue
# find recursively
else:
#print " recursive find:",aa[ca]
found = 0
#print " cn :",cn
while cn < len(nt):
if nt[cn:cn+3] in code[aa[ca]]:
last = nt[cn:cn+3]
#print " last>",nt[cn:cn+3]
cn = cn+3
found = 1
break
cn = cn+1
g = g +1
#print " cn,gap:",cn,g
if not found:
#print " omit> %ith aa, not found" % (ca+1)
cn = cn-g
g = 0
# if found and it is the last, write it
elif ca+1 == len(aa):
pass
#print " add >",nt[cn:cn+3],aa[ca]
ca = ca+1
return seq,firstMis
##
# A back translation utility based on synchronized pep and nt sequences
#
# 4/14,03, problems when sequence is in lower case. Taken care of.
# 3/11,03, implement verbose
##
def back_translate2(self,pep,nt,v=0):
if v:
print ("\nBack translate:")
# verify length first
plen = 0
if pep.find("-") != -1:
plist = pep.split("-")
for i in plist:
plen += len(i)
else:
plen = len(pep)
# nt sequence don't have "-", but need to rid of stop
if nt[-3:] in ["TAA","TGA","TAG","taa","tga","tag"]:
nt = nt[:-3]
flag = 0
if len(nt) != plen*3:
if v:
print ("Size discrepancy: nt",len(nt),"pep",plen)
flag = 1
seq = ""
if not flag:
countN = 0
codes = self.get_nt_code()
for i in pep:
if i == "-":
seq += "---"
else:
seq += nt[countN:countN+3]
# checking if it translate alright
if not codes.has_key(nt[countN:countN+3].upper()):
if v:
print ("Code unknown:",i.upper(),\
nt[countN:countN+3].upper())
elif codes[nt[countN:countN+3].upper()] != i.upper():
if v:
print ("Discrepancy:",i.upper(),\
nt[countN:countN+3].upper())
countN += 3
return seq, flag
#
# @param id for translating one particular sequence in a Fasta file.
# default is an empty string means translate the whole file.
#
def translate(self,cds,id="",frame=0,discard=0,indiv=0,lenT=0):
print ("Read fasta into dict...")
cdict = manager.fasta_to_oneline(cds,1)
if id != "":
print ("Translate:", id)
oup = open("%s_F%i.trans" % (id,frame),"w")
oup.write(">%s\n" % id)
oup.write("%s\n" % self.translate_passed(cdict[id].upper()))
else:
oup = open(cds+"_F%i.trans" % frame,"w")
oup1= open(cds+"_F%i.trans.log" % frame,"w")
ckeys = cdict.keys()
ckeys.sort()
countT = 0
count1 = 0
count2 = 0
count3 = 0
countW = 0
udict = {}
print ("Translate each seq...")
for i in ckeys:
if frame == 1:
cdict[i] = "NN" + cdict[i]
elif frame == 2:
cdict[i] = "N" + cdict[i]
[pep,error,unk_dict] = self.translate_passed2(cdict[i].upper())
write = 0
if error == 1:
print (" ERR-length:",i)
count1 += 1
elif error == 2:
print (" ERR-unk codons:",i)
count2 += 1
else:
write = 1
# check if there is stop that is not the last residue
if pep[:-1].find("*") != -1 and pep[:-1][-1] != "*":
print (" ERR-inner stop:",i)
#print pep
#sys.exit(0)
count3 += 1
error = 3
write = 0
for j in unk_dict:
if udict.has_key(j):
udict[j] += 1
else:
udict[j] = 1
if discard and not write:
#print " here"
pass
else:
countW += 1
#print " there"
oup.write(">%s\n" % i)
oup.write("%s\n" % pep)
oup1.write("%s\terror%i\n" % (i,error))
countT += 1
print ("Total %i sequences translated." % countT)
print (" %i has length not divisable by 3." % count1)
print (" %i has inner stop codon(s)." % count3)
print (" %i has unknown codons." % count2)
print ("Discard flag: %i" % discard)
print (" %i in output file" % countW)
if count2 > 0:
print (" listed:")
for i in udict:
print ("",i,udict[i])
#
# Break ORFs into subORFs that >= size threshold. All ORF should start with
# M.
#
def suborf(self,orfcds,lenT,check):
print ("Read sequence file...")
fdict = manager.fasta_to_dict(orfcds,0)
print (" total %i\n" % len(fdict.keys()))
print ("Iterate throughs sequences...")
oup = open(orfcds+".sub","w")
countS = 0
countT = 0
for i in fdict:
if countT % 1e4 == 0:
print (" %i x 10k" % (countT/1e4))
countT += 1
#print i
# chr|ori|frame|L-R
sid = i.split("|")
sid[-1] = sid[-1].split("-")
# there are situations where there is negative coord like:
# Contig989|-|2|-2-192
# in all cases, they are -2. And should be corrected by +3
if check and len(sid[-1]) == 3:
if sid[-1][0] == "":
sid[-1] = ["1",sid[-1][2]]
else:
print ("ERR1:",[i])
continue
L = int(sid[-1][0])
R = int(sid[-1][1])
cds = fdict[i]
# check size
if check and abs(R-L)+1 != len(cds):
if abs(R-L)+1-3 == len(cds):
R = R-3
else:
print ("ERR2:",[i],abs(R-L)+1,len(cds))
continue
# construct new seq names
seqname = "%s|%s|%s|%i-%i" % (sid[0],sid[1],sid[2],L,R)
pep = self.translate_passed2(cds)[0]
m = 0
mprime = m
l = len(pep)
#print "> ",m,l,lenT
#print [pep]
#print [cds]
while l > lenT:
countS += 1
oup.write(">%s|%i\n%s\n" % (seqname,m*3,cds))
#print ">>write"
mprime = pep[1:].find("M")
m += mprime + 1
pep = pep[1:][mprime:]
cds = cds[3:][mprime*3:]
l = len(pep)
#print ">>",m,l
#print [pep]
#print [cds]
print ("%i sequences, %i suborfs" % (countT,countS))
print ("Done!\n")
###
# 6 frame translation. Not for getting ORFs, just straight translation.
#
# @param seq fasta sequence file
###
def sixpack_simple(self,seq):
print ("Read fasta into dict:")
fdict = manager.fasta_to_dict(seq,0)
oup1 = open("%s.6pack_cds" % seq,"w")
oup2 = open("%s.6pack_pep" % seq,"w")
for i in fdict:
f = fdict[i] # forward
fn0 = f # forward frame 0
fn1 = f[1:]
fn2 = f[2:]
# Rid of extra 1 or 2 nt
if len(fn0) % 3 != 0:
fn0 = fn0[:-(len(fn0)%3)]
if len(fn1) % 3 != 0:
fn1 = fn1[:-(len(fn1)%3)]
if len(fn2) % 3 != 0:
fn2 = fn2[:-(len(fn2)%3)]
r = self.rc(f) # reverse
rn0 = f # reverse frame 0
rn1 = f[1:]
rn2 = f[2:]
if len(rn0) % 3 != 0:
rn0 = rn0[:-(len(rn0)%3)]
if len(rn1) % 3 != 0:
rn1 = rn1[:-(len(rn1)%3)]
if len(rn2) % 3 != 0:
rn2 = rn2[:-(len(rn2)%3)]
# Get translation
fp0 = self.translate_passed2(fn0,0)[0]
fp1 = self.translate_passed2(fn1,0)[0]
fp2 = self.translate_passed2(fn2,0)[0]
rp0 = self.translate_passed2(rn0,0)[0]
rp1 = self.translate_passed2(rn1,0)[0]
rp2 = self.translate_passed2(rn2,0)[0]
oup1.write(">%s_f0\n%s\n>%s_f1\n%s\n>%s_f2\n%s\n" % (i,fn0,i,fn1,i,fn2) +\
">%s_r0\n%s\n>%s_r1\n%s\n>%s_r2\n%s\n" % (i,rn0,i,rn1,i,rn2))
oup2.write(">%s_f0\n%s\n>%s_f1\n%s\n>%s_f2\n%s\n" % (i,fp0,i,fp1,i,fp2) +\
">%s_r0\n%s\n>%s_r1\n%s\n>%s_r2\n%s\n" % (i,rp0,i,rp1,i,rp2))
print ("Done!")
#
# Batch call six pack
#
def batch_6pack(self,seq,lenT,lenT2,met,inc,verbose):
oup0 = open("%s_T%i-%im%i.cds" % (seq,lenT,lenT2,met),"w")
oup1 = open("%s_T%i-%im%i.pep" % (seq,lenT,lenT2,met),"w")
oup2 = open("%s_T%i-%im%i.coord" % (seq,lenT,lenT2,met),"w")
oup2.write("SeqID\tOri\tFrame\tL\tR\n")
print ("Read fasta into dict:")
fdict = manager.fasta_to_dict(seq,0)
c = 0
print ("Do 6pack:")
fkeys = fdict.keys()
fkeys.sort()
for i in fkeys:
print ("",i)
eflag = self.sixpack([i,fdict[i]],lenT,lenT2,met,inc,
oup0,oup1,oup2,verbose)
if eflag:
break
print ("Done!")
#
# sixpack: 6 frame translation
#
# PROBLEM: met set to 2 is not working for antisense strand.
# 05/16,05 Stop codon position is included
# 05/17,05 lenT2 is not applied to met = 0
#
# @param seq a fasta file with 1 seq
# @param lenT leng cutoff for ORF, 25 default
# @param lenT2 leng threshold for ORF, 10000 default
# @param met methionine as ORF start [1,default] or any [0], or get
# all ORFs start with Met in any full length ORF [2] NOT
# WORKING!!!!!
# @param oup0 Passed from batch_6pack, for ORF cds
# @param oup1 Passed from batch_6pack, for ORF pep
# @param oup2 Passed from batch_6pack, for ORF coord
#
def sixpack(self,seq,lenT,lenT2,met,inc,oup0="",oup1="",oup2="",verbose=1):
if verbose:
if oup1 == "":
print ("\nSequence:",seq)
else:
print ("\nSequence:",seq[0])
print ("lenT :",lenT)
print ("lenT2 :",lenT2)
print ("Met_flag:",met)
print ("TL_inc :",inc)
if inc % 3 != 0:
print ("ERR: TL_inc has to be multiple of 3")
if oup1 == "":
sys.exit(0)
else:
return 1
###################
# split() start
# seq_index,ori,ntseq,TL_seq,frame,lenT,met,antisense,antisense length
###################
def split(idx,ori,ntseq,s,f,a=0,alen=0,verbose=1):
# L coord as key, [R_coord,pep,nt] as value
#print s
sdict = {}
s = s.split("*")
#print s
c = f
countT = 0
if verbose:
print (" split_orf:",len(s))
for i in s:
if verbose and countT != 0 and countT % 10000 == 0:
print (" %i x 10k" % (countT/10000))
countT += 1
#print "ORF:",i
if i == "":
c += 3
continue
EXC = ["?","X"]
#EXC = ["X"]
# if orf starts or ends in ? or X, this orf will be disgarded
if len(i) >= lenT and i[0] not in EXC and i[-1] not in EXC:
iL = len(i)
if met == 1 and i.find("M") != -1:
m = i.find("M")
mprime = m
x = i[m:]
l = len(x)
#print m,x,l
while bisect([lenT,lenT2+1],l) == 2:
#print " .."
mprime = x[1:].find("M")
m += mprime + 1
x = x[1:][mprime:]
l = len(x)
# len(x) is between lenT and lenT2
if bisect([lenT,lenT2],l) == 1:
if a:
ntL = c+m*3+1 # ntseq coord
ntR = c+(iL+1)*3
coordL = alen-(c+iL*3)+1-3 # sense strand
coordR = alen-(c+m*3+1)+1
# sense
else:
ntL = c+m*3+1 # nt seq coord
ntR = c+(iL+1)*3
coordL = c+m*3+1 # sense strand
coordR = c+(iL+1)*3
if len(x) > 0:
sdict[coordL] = [coordR,x,ntseq[ntL-1:ntR]]
#print "IN :",x
#print " ",ntL,ntR,coordL,coordR
else:
#print "OUT:",x
pass
elif met == 0:
# NOTICE THAT lenT2 is not applied.
# antisense
if a:
sdict[alen-(c+iL*3)+1-3] = [alen-(c+1)+1,i,
ntseq[c+1-1:c+(iL+1)*3]]
# sense
else:
sdict[c+1] = [c+(iL+1)*3,i,ntseq[c+1-1:c+(iL+1)*3]]
""" PROBLEM HERE, INACTIVETED FOR NOW
elif met == 2:
m = i.find("M") # initial position for MET
n = m # variable aa position for Met
x = i
while m != -1:
x = x[m:]
if len(x) >= lenT:
# antisense
if a:
coordL = alen-(c+iL*3)+1
coordR = alen-(c+n*3+1)+1
# deal with ? and X
if x.find("?") != -1:
...
# sense
else:
coordL = c+n*3+1
coordR = c+iL*3
if len(x) > 0:
sdict[coordL] = [coordR,x]
else:
break
x = x[1:]
m = x.find("M")
n += m+1
"""
c += len(i)*3 + 3
skeys = sdict.keys()
skeys.sort()
if verbose:
print (" qualified:",len(sdict))
for i in skeys:
if verbose:
print ("----")
print (idx,ori,f,i,sdict[i][0])
print (sdict[i][1])
print (sdict[i][2])
# Get rid of sequences that have ? or X
if sdict[i][1].find("?") != -1 or sdict[i][1].find("X") != -1:
#print "---ERR_SEQ"
#print sdict[i][1]
continue
# 06/-6,07 for ORFs involving the 1st or the last nucleotide,
# the coordinates are -3 or +3 more than they should. This is
# not so much of a problem when working with chromosomes, but
# an issue when looking to multiple contigs. The following
# is to check if there is discrepancy between the length of sub
# seq and if they are the beginning or ending entries. If so,
# coordinates are corrected accordingly.
err = 0
modi = 0
if i < 0:
if i == -2 and sdict[i][0] == len(sdict[i][2]):
modi = 1
else:
" ERR:",idx,ori,f,i,sdict[i][0]
#print sdict[i][0]-i+1, len(ntseq)
if not modi:
if sdict[i][0]-i+1 > len(ntseq):
if sdict[i][0]-len(ntseq) == 2 and \
sdict[i][0]-i+1-3 == len(ntseq):
sdict[i][0] -= 3
else:
" ERR:",idx,ori,f,i,sdict[i][0]
else:
if sdict[i][0]-modi+1 > len(ntseq):
if sdict[i][0]-len(ntseq) == 2 and \
sdict[i][0]-modi+1-3 == len(ntseq):
sdict[i][0] -= 3
else:
" ERR:",idx,ori,f,i,sdict[i][0]
if not err:
oup0.write(">%s|%s|%i|%i-%i\n%s\n" % \
(idx,ori,f,i,sdict[i][0],sdict[i][2]))
oup1.write(">%s|%s|%i|%i-%i\n%s\n" % \
(idx,ori,f,i,sdict[i][0],sdict[i][1]))
oup2.write("%s\t%s\t%i\t%i\t%i\n" % \
(idx,ori,f,i,sdict[i][0]))
###################
# split() end
###################
if verbose:
print ("Read sense strand...")
# output stream not specified, must be direct call
if oup1 == "":
inp = open(seq,"r")
inl = inp.readlines()
idx = self.rmlb(inl[0])[1:]
sense = string.joinfields(inl[1:],"")
oup0 = open("%s_T%i-%im%i.cds" % (idx,lenT,lenT2,met),"w")
oup1 = open("%s_T%i-%im%i.pep" % (idx,lenT,lenT2,met),"w")
oup2 = open("%s_T%i-%im%i.coord" % (idx,lenT,lenT2,met),"w")
oup2.write("SeqID\tOri\tFrame\tL\tR\n")
# batch call, seq passed is a list with [idx,sequence]
else:
idx = seq[0]
sense = seq[1]
# get rid of line breaks, sometimes \n and \r\n are mixed.
if sense.find("\r\n") != -1:
sense = string.joinfields(sense.split("\r\n"),"")
if sense.find("\n") != -1:
sense = string.joinfields(sense.split("\n"),"")
if verbose:
print ("Reverse...")
antis = self.reverse2(sense)
if verbose:
print ("Complement...")
antis = self.complement(antis)
# sense, frame 0,1,2
if verbose:
print ("Translate..")
print (" sense, frame 0")
s0 = self.translate_passed(sense,0,inc)[0]
#print s0
split(idx,"+",sense,s0,0,0,0,verbose)
if verbose:
print (" sense, frame 1")
s1 = self.translate_passed(sense,1,inc)[0]
split(idx,"+",sense,s1,1,0,0,verbose)
if verbose:
print (" sense, frame 2")
s2 = self.translate_passed(sense,2,inc)[0]
split(idx,"+",sense,s2,2,0,0,verbose)
# antisense, frame 0,1,2
if verbose:
print (" antisense, frame 0")
a0 = self.translate_passed(antis,0,inc)[0]
split(idx,"-",antis,a0,0,1,len(antis),verbose)
if verbose:
print (" antisense, frame 1")
a1 = self.translate_passed(antis,1,inc)[0]
split(idx,"-",antis,a1,1,1,len(antis),verbose)
if verbose:
print (" antisense, frame 2")
a2 = self.translate_passed(antis,2,inc)[0]
split(idx,"-",antis,a2,2,1,len(antis),verbose)
#oup1.close()
#oup2.close()
if verbose:
print ("Done!")
def translate_passed(self,seq,frame=0,inc=1000):
code = self.get_nt_code()
if frame == 1:
seq = seq[1:]
elif frame == 2:
seq = seq[2:]
window_size = 1000000
if len(seq) > window_size:
print (" nt_len: %i" % len(seq))
print (" break into %i chucks" % (len(seq)/window_size+1))
inc = inc*1000
prot_all = []
for i in range(0,len(seq),inc):
#if len(seq) > 1000000:
# print " %i-%i kb" % (i/1000,(i+inc)/1000)
# 090911: Deal with fragments that are not multiple of 3.
segment = seq[i:i+inc]
#print "pre :",[segment]
blah = len(segment)%3
if blah != 0:
segment = segment[:-blah]
#print "post:",[segment]
prot = ""
for j in xrange(0,len(segment),3):
#print "",prot
prot += code.get(segment[j:j+3], "?")
prot_all.append(prot)
#print prot_all
prot_all = string.joinfields(prot_all,"")
"""
prot_all = ""
for i in xrange(0,len(seq),3):
prot_all += code.get(seq[i:i+3], "?")
"""
return [prot_all,0,{}]
#
# Exclude
#
def exclude(self,orf_coord,exc_coord):
print ("Read %s...\n" % exc_coord)
inp = open(exc_coord)
inl = inp.readline()
# {idx:{L:R}}
E = {}
while inl != "":
inl = inl.split("\t")
i = inl[0]
L = int(inl[1])
R = int(inl[2])
if E.has_key(i):
if E[i].has_key(L):
if R > E[i][L]:
E[i][L] = R
else:
E[i][L] = R
else:
E[i] = {L:R}
inl = inp.readline()
print ("Generated sorted exclusion coordinates...\n")
Esorted = {}
for i in E:
ikeys = E[i].keys()
ikeys.sort()
Esorted[i] = ikeys
print ("Read %s and generate outputs..." % orf_coord)
inp = open(orf_coord)
oup = open(orf_coord+".qualified","w")
inp.readline() # first line is header
inl = inp.readline()
countA = 0
countQ = 0
c = 0
while inl != "":
if countA % 1e4 == 0:
print (" %i x 10k" % (countA/1e4))
countA += 1
S = inl.split("\t")
L = int(S[3])
R = int(S[4])
elist = Esorted[S[0]]
ins = bisect(elist,L)
#print [inl]
#print "5':",elist[ins-1],E[S[0]][elist[ins-1]]
#print "3':",elist[ins],E[S[0]][elist[ins]]
# evaluate 5', as long as it is not the first
O5 = O3 = 1
if ins != 0:
if L > E[S[0]][elist[ins-1]]:
O5 = 0
# evaluate 3', as long as it is not the last
if ins != len(elist):
if R < elist[ins]:
O3 = 0
if not O5 and not O3:
oup.write(inl)
countQ += 1
#print "O5:%i,O3:%i" % (O5,O3)
inl = inp.readline()
print (" total %i, %i qualified\n" % (countA,countQ))
#
# Read a fasta file with one seq, return a list with [id,seq]
#
def read_1seq(self,fasta):
inp = open(fasta,"r")
inl = inp.readlines()
idx = self.rmlb(inl[0])[1:]
fasta = string.joinfields(inl[1:],"")
# get rid of line breaks, sometimes \n and \r\n are mixed.
if fasta.find("\r\n") != -1:
sense = string.joinfields(fasta.split("\r\n"),"")
if fasta.find("\n") != -1:
fasta = string.joinfields(fasta.split("\n"),"")
return([idx,fasta])
#
# Do reverse complement on sequences based on passed names
# > whatever_xxxx|yyyy
#
# if x > y, then it will be rc'ed.
#
def rc2(self,nt):
fdict = manager.fasta_to_dict(nt,0)
oup = open(nt+".rc_correct","w")
fkeys = fdict.keys()
countR = 0
for i in fkeys:
rc = 0 # rc or not flag
if i.find("|") != -1 and i.find("_") != -1:
# coordinates
c = i[i.rfind("_")+1:].split("|")
if int(c[0]) > int(c[1]):
rc = 1
countR += 1
if rc:
oup.write(">%s\n%s\n" % \
(i,self.complement(self.reverse2(fdict[i]))))
else:
oup.write(">%s\n%s\n" % (i,fdict[i]))
print ("%i sequences, %i rc'ed" % (len(fkeys), countR))
#
# Do reverse complement on sequences based on passed names. If no name
# passed, all will be rc'd.
#
def batch_rc(self,nt,names):
fdict = manager.fasta_to_dict(nt,0)
oup = open(nt+".rc_select","w")
if names != "":
inp = open(names)
inl = inp.readlines()
names = {}
for i in inl:
names[self.rmlb(i)] = 0
fkeys = fdict.keys()
fkeys.sort()
countR = 0
for i in fkeys:
if i in names:
names[i] = 1
oup.write(">%s\n%s\n" % \
(i,self.complement(self.reverse2(fdict[i]))))
countR += 1
else:
oup.write(">%s\n%s\n" % (i,fdict[i]))
for i in names:
if names[i] == 0:
print ("Not found:",i)
print ("%i sequences, %i rc'ed" % (len(fkeys), countR))
#
# @param call internal[0,default] or outside[1].
#
def rc(self,nt,call=0):
# external call, read file
if call:
fn = nt
nt = self.read_1seq(nt)
idx = nt[0]
nt = nt[1]
nt = self.complement(self.reverse2(nt))
if call:
oup = open(fn+".rc","w")
oup.write(">%s\n%s\n" % (idx,nt))
else:
return nt
def complement(self,nt):
try: # Only works in Python 2