-
Notifications
You must be signed in to change notification settings - Fork 3
/
AlnUtility.py
executable file
·1762 lines (1555 loc) · 48.9 KB
/
AlnUtility.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
#!/usr/bin/
##
# This class is written to manipulate alignment and take care of the calculation
# of dN, dS, and dA
#
# 04/23,03
# This class was modified many many times since maybe 4 months ago. No documen-
# tation. Shame on myself. Anyway, rate_pair() need to be changed somewhat to
# allow the use of full length Ks value as denominator in sliding window ana-
# lysis.
# 05/15,03
# Found a serious bug in rate_pair(). The increment was not correct so every
# step will miss one codon. Fix it.
# 12/15,03
# Problem with paml, some sequence pairs has dS = -1 in Nei & Gojobori method.
# So the paml dN and dS are not generated.
# 08/17,04
# Rate pair now include capability to use Pan's KaKsTools
#
##
import os, sys, FastaManager, Translation, time, TreeUtility, DrawBlocks, \
SVGWriter, FileUtility, string
from kaksToolsHacked import calculate
class aln_util:
def __init__(self):
pass
#
# Getting alingments and neighbor joining trees
#
def batch_nj(self,phydir,alndir):
#phydir = "~/bin/phylip3.66/exe/" # dir for phylip executables
#alndir = "/home/shiu/project/stress_expr_at/1_nj/_aln"
flist = os.listdir(alndir)
c = 1
for alnfile in flist:
if alnfile[-3:] != "phy":
continue
print "#########################"
print "# File %i out of %i" % (c,len(flist))
c += 1
if os.path.isfile("%s/%s.nj.tre" % (alndir,alnfile)) and \
os.path.getsize("%s/%s.nj.tre" % (alndir,alnfile)) == 0:
print " done!"
else:
os.system("rm %s/%s.nj.tre %s/%s.nj.out %s/%s.pd.out" % \
(alndir,alnfile,alndir,alnfile,alndir,alnfile))
# get distance
f = os.popen("%sprotdist" % phydir,"w")
f.write("%s\n" % alnfile) # aln file name
f.write("F\n") # rename file, have a fake outfile ready
f.write("%s.pd.out\n" % alnfile) # output file name
f.write("G\n") # gamma correction
f.write("Y\n") # setting ok
f.write("0.3162\n") # coefficient of var, assume alpha = 10
f.close()
# get nj tree
f = os.popen("%sneighbor" % phydir,"w")
f.write("%s.pd.out\n" % alnfile) # distance file name
f.write("F\n") # rename file, have a fake outfile ready
f.write("%s.nj.out\n" % alnfile) # output file name
f.write("Y\n") # accept default parameters
f.write("F\n") # rename file, have a fake outree ready
f.write("%s.nj.tre\n" % alnfile) # tree file name
f.close()
print "Done!"
##
# This is for getting alignments and bootstrapped phylogeny for each seq
# group.
#
##
def batch_tree(self,group,fasta,clus_dir,bootstrap=0,isdir=0):
# create group fasta files and get group list back
if isdir == 0:
print "Creat group fasta files..."
# originally setting is (fasta,group,0,1), change the
# last to 0 so no outgroup is passed
glist = fasta_manager.get_group_seq(fasta,group,0,0)
else:
print "Run fasta files in dir:",fasta
tmp = os.listdir(fasta)
glist = []
for i in tmp:
if i.find(".fa") != -1:
glist.append(i[:i.find(".fa")])
print "\nAlign and generate phylogeny.."
for i in glist:
print "\n align:",i
# generate alignment
#print "%s/clustalw %s.fa " % (clus_dir,i) + ">> TMP.log"
os.system("%s/clustalw %s.fa " % (clus_dir,i) + ">> TMP.log")
print " tree :",i
if bootstrap != 0:
os.system("%s/clustalw %s.aln /BOOTSTRAP=400 /BOOTLABELS=node" % \
(clus_dir,i) + ">> TMP.log")
else:
os.system("%s/clustalw %s.aln -tree" % \
(clus_dir,i) + ">> TMP.log")
#tree_util.simplify("%s.phb" % i)
#os.system("mv %s.phb.simplify %s.tre" % (i,i))
os.system("rm %s.dnd" % i)
print "Done!"
def batch_tree_submit(self,groups,fasta,c_dir,w_dir="./",mode=1,spflag=1,pick="",
aln_profile="",bootstrap=0):
# read group info into dict
gdict = file_util.file_to_dict(groups,2)
# filter, if less than 3 taxa or has only one sp, they will be deleted
countT = 0
countU = 0
oup_log = open(groups+".log","w")
for i in gdict.keys():
countT += 1
same_sp = 1
taxa_lm = 2
sp = ""
for j in gdict[i]:
if sp == "":
sp = j[:2]
elif sp != j[:2]:
same_sp = 0
break
if len(gdict[i]) < 3:
oup_log.write("%s\tless than 3 seq\n" % i)
countU += 1
del(gdict[i])
elif spflag and same_sp:
oup_log.write("%s\tsame_sp\n" % i)
countU += 1
del(gdict[i])
for i in gdict:
"""
print "python ~/codes/qsub2.py -s run_%s -c \"python" % i +\
" ~/codes/AlnUtility.py -f batch_tree2 -group %s" % groups+\
" -fasta %s -clustal %s -mode %i -sp %i" % (fasta,c_dir,mode,spflag)+\
" -bootstrap %i -profile %s -pick %s\"" %(bootstrap,aln_profile,i)
"""
os.system("python ~/codes/qsub2.py -s run_%s -c \"python" % i +\
" ~/codes/AlnUtility.py -f batch_tree2 -group %s" % groups+\
" -fasta %s -clustal %s -mode %i -sp %i" % (fasta,c_dir,mode,spflag)+\
" -bootstrap %i -profile %s -pick %s\"" %(bootstrap,aln_profile,i))
##
# Generate alignments based on a passed file with [group][seq_id]
# Then generate a tree for it.
#
# @param mode run alignment only [0] or both [1, default]
# @param spflag run even if seqs are the same sp [0], not [1, default].
# sp is defined as the first two characters of seq names.
# @param pick specify what group(s) to run. Group names seperated by
# ",".
# @param aln_profile name of the profile alignment, if this is not empty
# sequences to profile alignment mode for clustsal will
# be triggered. Assume the profile alignment file is in the
# working dir.
##
def batch_tree2(self,groups,fasta,c_dir,w_dir="./",mode=1,spflag=1,pick="",
aln_profile="",bootstrap=0):
# get working directories, this is for qsub
w_dir = os.getcwd()
print "working_dir:",w_dir
# make directories
if not os.path.isdir("%s/seq" % w_dir):
os.system("mkdir %s/seq" % w_dir)
if not os.path.isdir("%s/aln" % w_dir):
os.system("mkdir %s/aln" % w_dir)
if not os.path.isdir("%s/tre" % w_dir):
os.system("mkdir %s/tre" % w_dir)
# check if the profile alignment file exisit
if aln_profile != "" and \
not os.path.isfile("%s/%s" % (w_dir,aln_profile)):
print "Profile %s does not exist in %s" % (aln_profile,w_dir)
sys.exit(0)
# read group info into dict
gdict = file_util.file_to_dict(groups,2)
# filter, if less than 3 taxa or has only one sp, they will be deleted
countT = 0
countU = 0
oup_log = open(groups+".log","w")
for i in gdict.keys():
countT += 1
same_sp = 1
taxa_lm = 2
sp = ""
for j in gdict[i]:
if j.find("|") != -1:
curr_sp = j.split("|")[0]
else:
curr_sp = j[:2]
if sp == "":
sp = curr_sp
elif sp != curr_sp:
same_sp = 0
break
if len(gdict[i]) < 3:
oup_log.write("%s\tless than 3 seq\n" % i)
countU += 1
del(gdict[i])
elif spflag and same_sp:
oup_log.write("%s\tsame_sp\n" % i)
countU += 1
del(gdict[i])
if pick != "":
print "Pick groups..."
pick = pick.split(",")
pdict = {}
for i in pick:
if gdict.has_key(i):
pdict[i] = gdict[i]
#else:
# print "Family %s not qualified" % i
gdict = pdict
if pdict == {}:
print "No qualified family, quit!"
sys.exit(0)
else:
print "%i families qualified out of %i picked" % \
(len(gdict.keys()),len(pick))
oup_log.close()
# this is here so the variable can be reused. Meanwhile, pdict will not
# be read unless ncessary, this is good for large-scale operation
# where I usu get the group sequences ready so there is no need to
# load pdict.
pdict = {}
# iterating groups
count = 1
print "Iterate groups..."
for i in gdict.keys():
print "%i %s, %i seq" % (count,i,len(gdict[i]))
# write sequence into a file
if(os.path.isfile("%s/seq/%s.fa" % (w_dir,i)) and \
os.path.getsize("%s/seq/%s.fa" % (w_dir,i)) != 0):
print " seq exist..."
else:
print " get sequences..."
pdict = fasta_manager.fasta_to_dict(fasta)
oup = open("%s/seq/%s.fa" % (w_dir,i),"w")
for j in gdict[i]:
oup.write(">%s\n%s\n" % (j,pdict[j]))
oup.close()
# generate alignment
if(os.path.isfile("%s/aln/%s.aln" % (w_dir,i)) and \
os.path.getsize("%s/aln/%s.aln" % (w_dir,i)) != 0):
print " aln exist..."
else:
print " align..."
if aln_profile == "":
os.system("%s/clustalw %s/seq/%s.fa" % \
(c_dir,w_dir,i) + ">>%s/TMP_%s.log" % (w_dir,i))
else:
p1 = aln_profile
#print "%sclustalw -sequences -PROFILE1=%s/%s "%(c_dir,w_dir,p1)+\
# "-PROFILE2=%s/seq/%s.fa " %(w_dir,i) +\
# ">> %s/TMP_%s.log" %(w_dir,i)
os.system("%s/clustalw -sequences -PROFILE1=%s/%s "%(c_dir,w_dir,p1)+\
"-PROFILE2=%s/seq/%s.fa " %(w_dir,i) +\
">> TMP_%s.log" %i)
os.system("mv %s/seq/%s.aln %s/aln/" % (w_dir,i,w_dir))
os.system("rm %s/seq/%s.dnd" % (w_dir,i))
time.sleep(2)
# build tree
# 05/06,07 A weird bug. during tree building phase, the aln name
# pass sometimes clustal will complain that it end with "^Y" so the
# file is not found. There is no where that this control-Y is found
# in the code. So I tried rid of the w_dir part of the os.system
# parameter. And it somehow works.
# 05/11,07 Still some trees are just not built for unknown reason.
# Try sleep for 2 sec after alignment but before tree building. Add
# "./" before aln. Somehow worked...??
if mode:
if((os.path.isfile("%s/tre/%s.ph" % (w_dir,i)) and \
os.path.getsize("%s/tre/%s.ph" % (w_dir,i)) != 0) or \
(os.path.isfile("%s/tre/%s.phb" % (w_dir,i)) and \
os.path.getsize("%s/tre/%s.phb"% (w_dir,i)) != 0)):
print " tree exist..."
else:
print " build tree..."
if bootstrap == 0:
os.system("%s/clustalw %s/aln/%s.aln -tree >> %s/TMP_%s.log" % \
(c_dir,w_dir,i,w_dir,i))
else:
os.system("%s/clustalw aln/%s.aln" %(c_dir,i) +\
" /BOOTSTRAP=%i /BOOTLABELS=node"%bootstrap +\
" >> TMP_%s.log" %i)
os.system("mv %s/aln/%s.ph* %s/tre" % (w_dir,i,w_dir))
time.sleep(2)
count+=1
print "Done!"
##
# Genearte alignments based on a passed file with [group][seq_id]
#q
# @param groups tab delimited file with [organisms][clade_id][subtree]
# @param fasta fasta sequence file. This file should always have a sequence
# named "OUT" for outgroup sequence
##
def batch_align(self,groups,fasta,clus_dir,paml_dir):
# read group info into dict
gdict = {}
trees = {}
inp = open(groups,"r")
lines = inp.readlines()
oup = open(groups+".log","w")
for i in lines:
if i[-2:] == "\r\n":
i = i[:-2]
elif i[-1] == "\n":
i = i[:-1]
llist = i.split("\t")
trees["%s_%s" % (llist[0],llist[2])] = llist[3]
# parse tree into taxa information
tree_str = ""
for j in llist[3]:
if j not in ["(",")",":",";"]:
tree_str += j
tlist = tree_str.split(",")
gdict["%s_%s" % (llist[0],llist[2])] = tlist
for j in tlist:
oup.write("%s_%s\t%s\n" % (llist[0],llist[2],j))
# filter, if less than 3 taxa or has only one sp, they will deleted
countT = 0
countU = 0
for i in gdict.keys():
countT += 1
same_sp = 1
taxa_lm = 2
sp = ""
for j in gdict[i]:
if sp == "":
sp = j[:2]
elif sp != j[:2]:
same_sp = 0
break
if len(gdict[i]) <=2 or same_sp:
countU += 1
del(gdict[i])
print "Total %i groups, %i not qualified" % (countT, countU)
# read seq into dict
pdict = fasta_manager.fasta_to_dict(fasta)
# iterating groups
oup_rate = open("%s.matrix" % group, "w")
for i in gdict.keys():
# write sequence into 2 files.
oup2= open("TMP2.FA","w") # tree for rate calculation
for j in gdict[i]:
oup2.write(">%s\n%s\n" % (j,pdict[j][1]))
oup2.close()
# run clustal for TMP2
print "%s/clustalw /INFILE=TMP2.FA /OUTFILE=TMP2.GDE /OUTPUT=GDE" % \
clus_dir
os.system("%s/clustalw /INFILE=TMP2.FA /OUTFILE=TMP2.GDE /OUTPUT=GDE" % \
clus_dir)
# save tree into temp file
oup2 = open("TMP2.PHB","w")
oup2.write("%s;\n" % trees[i])
# convert alignment GDE to fa and then to phylip format
inp = open("TMP2.GDE","r")
oup = open("TMP2.GDE.FA","w")
tlines = inp.readlines()
for j in tlines:
if j[0] == "%":
oup.write(">%s" % j[1:])
else:
oup.write(j)
oup.close()
self.to_phylip("TMP2.GDE.FA","TMP2")
# run paml
os.system("%s/codeml" % paml_dir)
# get the matrix part
inp = open("TMP2.OUT","r")
inlines = inp.readlines()
found = 0
rdict = {}
nlist = []
for j in inlines:
if j.find("ML distances of aa seqs.") != -1:
found = 1
elif found:
if j[-2:] == "\r\n":
j = j[:-2]
elif j[-1] == "\n":
j = j[:-1]
jlist = j.split(" ")
tlist = []
nlist.append(jlist[0])
for k in jlist[1:]:
if k != "":
tlist.append(k)
rdict[jlist[0]] = tlist
ilist = i.split("_")
for j in range(len(nlist)):
for k in rdict.keys():
if nlist[j] != k:
oup_rate.write("%s\t%s\t%s\t%s\t%s\n" % \
(ilist[0],ilist[1],nlist[j],k,rdict[k][j]))
else:
del(rdict[k])
#os.system("rm -f TMP*")
##
# Back translate alignment sequences
##
def bt_align(self,pep,cds):
# read fasta into dicts
pdict = fasta_manager.fasta_to_dict(pep)
ndict = fasta_manager.fasta_to_dict(cds)
# back translate each and write into GDE
oup = open(cds+".aligned.fa","w")
flag = 0
for j in pdict.keys():
seq, flag = trans.back_translate2(pdict[j][1],ndict[j][1])
if flag:
print "Error:",j
oup.write(">%s\n%s\n" % (j,seq))
oup.close()
#
# This function take a list of pairs, conduct pairwise alignment with
# clustal, then parse the gap information out of the alignments.
#
def parse_gap(self,pairs,fasta,clus_dir):
inp = open(pairs,"r")
inlines = inp.readlines()
pdict = fasta_manager.fasta_to_dict(fasta)
# find -, and return a list of coordinates (alignment-based)
def gap(astr):
c = 1
gL = gR = 0
glist = []
for i in astr:
if i == "-":
if gL == 0:
gL = gR = c
else:
gR += 1
else:
if gL != 0:
glist.append("%i-%i" % (gL,gR))
gL = gR = 0
c += 1
if gL != 0:
glist.append("%i-%i" % (gL,gR))
return glist
oup1= open(pairs+".gap","w")
oup2= open(pairs+".seqpair","w")
count = 1
for i in inlines:
# write sequences into temp fasta file and align sequences
i = self.rmlb(i)
# line list, contain ids for each pair
L = i.split("\t")
print " %i %s-%s" % (count,L[0],L[1])
count += 1
# align
error = self.do_clustal(L[0],L[1],pdict,"TMP",clus_dir)
if error:
print " sequence absent"
oup_rate.write("%s\t%s\t" % (llist[0],llist[1]))
oup_rate.write("-\t-\tsequence_absent\n")
else:
# read alignment GDE file
inp = open("TMP.GDE","r")
tmp = inp.readlines()
inp.close()
tag = 0
aln = ["",""]
for i in tmp:
if i[0] == "%":
tag += 1
if tag == 1 and i[0] != "%":
aln[0] += self.rmlb(i)
if tag == 2 and i[0] != "%":
aln[1] += self.rmlb(i)
qlist = gap(aln[0])
slist = gap(aln[1])
qlen = len(pdict[L[0]][1])
slen = len(pdict[L[1]][1])
# should be the same as sline
alen = len(aln[0])
# [q][s][qStr][qEnd][sStr][sEnd][alnL][qGaps][sGaps]
oup1.write("%s\t%s\t1\t%s\t1\t%s\t%i\t%s\t%s\n" % \
(L[0],L[1],qlen,slen,alen,string.joinfields(qlist,","),
string.joinfields(slist,",")))
# 2 lines, each pair seperate by an empty line
oup2.write("%s\t%s\n%s\t%s\n\n" % (L[0],aln[0],L[1],aln[1]))
os.system("rm TMP*")
print "Done!"
##
# Find 4x degenerate sites. The sequences passed should be aligned already.
#
#
# @param seq1 cds seq for gene1
# @param seq2 cds seq for gene2
# @return a list of two modified sequence
##
def find_x4(self,seq1,seq2):
#print seq1
#print seq2
x4 = trans.get_x4()
code = trans.get_nt_code()
nseq1 = nseq2 = ""
for i in range(0,len(seq1),3):
#print seq1[i:i+3],code[seq1[i:i+3]],
#print seq2[i:i+3],code[seq2[i:i+3]],
# both codons are 4fold
if x4.has_key(seq1[i:i+3]) and x4.has_key(seq2[i:i+3]):
# synonymous
if x4[seq1[i:i+3]] == x4[seq2[i:i+3]]:
nseq1 += seq1[i:i+3]
nseq2 += seq2[i:i+3]
#print "4x",
#print ""
#print nseq1
#print nseq2
return [nseq1,nseq2]
##
# Do the following:
# 1. get each pair of orthologs from a pep fasta file based on a table
# 2. clustalw
# 3. back translate NT sequences based on pep alignment. Still in GDE
# 4. parse GDE output and convert into "simple" PHYLIP format
# default output is TMP.GDE.phy
# 5. run yn00 based on the control file yn00.ctl, default output is TMP.out
# in PAML dir.
# 6. parse yn00 output, generate another output file with rates with
# [org1_geneA][org2_geneA][dN/Ds][dN][dS]
#
# !!!!!! FOR THIS TO WORK, THE PAML CONTROL FILE NEED TO BE COPIED TO THE
# WORKING DIR!!!!!!!!
#
# @param wdir working directory, default local
# @param pep polypeptide sequence file to get pairs from
# @param cds nucleotide sequence file. The id should be exactly the same
# as that in pep. All sequences should also be in the same
# frame.
# @param prog program to use paml or tpl (Tzeng,Pan,Li, 2004)
# @param pairs tab delimited file with ortholog relationships
# @param windows the sliding-window size for getting Ka, Ks. Default 0
# @param step step size of the sliding window
# @param gdom graphic domain file
# @param ks the Ks value used to calculate Ka/Ks ratio. Default is
# "full" which is the Ks for the whole gene, or "window" for
# Ks from the sequence of each window.
# @param justka 0 [default] or 1, just show Ka.
# @param x4 Only calculate Ka Ks for 4x sites [1] or all [0, default],
# will not allow window calculation if 4x = 1
# @param debug turn file deletion off (1). Default 0.
##
def rate_pair(self,pep,cds,pairs,clus_dir,prog,paml_dir,window,step,
gdom,ks,justka,x4=0,idxpairs=0,debug=0):
print "Calculate pairwise evol rate:"
print " pep :",pep
print " cds :",cds
print " pairs :",pairs
print " clustal:",clus_dir
print " 4fold :",x4
print " program:",prog
if prog == "paml":
print " paml :",paml_dir
if window != 0:
print " window :",window
print " step :",step
print " ks_full:",ks
# read fasta into dicts
print "Read:",pep
pdict = fasta_manager.fasta_to_dict(pep,verbose=0)
print "Read:",cds
ndict = fasta_manager.fasta_to_dict(cds,verbose=0)
if prog == "paml":
try:
inp = open("yn00.ctl","r")
except IOError:
print "Control file missing, can't do anything... QUIT!"
sys.exit(0)
# read and process sequences pair by pair
inlines = []
if pairs != "":
inp = open(pairs,"r")
inlines = inp.readlines()
oup_rate = open(pairs+".rate","w")
if window != 0:
oup_rate2 = open(pairs+".rate_windows","w")
# no pair info passed, look at all combo
else:
print "No pair info passed, all combination..."
keys = pdict.keys()
for i in range(len(keys)):
for j in range(i+1,len(keys)):
inlines.append("%s\t%s" % (keys[i],keys[j]))
oup_rate = open("all_pairs.rate","w")
if window != 0:
oup_rate2 = open("all_pairs.rate_windows","w")
errors = []
# if window size is specified
if window != 0:
# read gdom file into dict
if gdom == "":
gdict = {}
else:
gdict = file_util.file_to_dict(gdom,1)
Xsize = 2000
Ysize = 300 * (len(inlines)+2)
svg_writer = SVGWriter.svg_writer(pairs+".svg")
svg_writer.write_header(Xsize,Ysize)
oup_rate.write("Seq1\tSeq2\tKa\tKs\tvKa\tvKs\n")
if window != 0:
oup_rate2.write("Window(cds):%i, Step(cds):%i\n" % (window,step))
oup_rate2.write("Seq1\tSeq2\tKa\tKs\tvKa\tvKs\tfull_Ks\tStartAA\n")
# start to process pairs
print "\nProcess pairs:"
count = 1
for i in inlines:
# write sequences into temp fasta file and align sequences
i = self.rmlb(i)
# line list, contain ids for each pair
llist = i.split("\t")
print " %i %s vs %s" % (count,llist[0],llist[1])
if len(llist[0]) > 30 or len(llist[1]) > 30:
print " ERR: seq name too long, clustal cannot deal with it"
continue
error = self.do_clustal(llist[0],llist[1],pdict,"TMP",clus_dir)
if error:
print " sequence absent"
oup_rate.write("%s\t%s\t" % (llist[0],llist[1]))
oup_rate.write("-\t-\t-\t-\tsequence_absent\n")
else:
# convert aligned sequence to fasta, then to dict again
inp = open("TMP.GDE","r")
oup = open("TMP.GDE.FA","w")
tlines = inp.readlines()
inp.close()
for j in tlines:
if j[0] in ["%","#"]:
oup.write(">%s" % j[1:])
else:
oup.write(j)
oup.close()
tdict = fasta_manager.fasta_to_dict("TMP.GDE.FA",verbose=0)
# back translate each and write into GDE
flag = 0
seqs = ""
tkeys = tdict.keys()
tkeys.sort()
for j in tkeys:
try:
seq, flag = trans.back_translate2(tdict[j],
ndict[j])
#print ">>>",flag
except KeyError:
flag = 2
print ">>>",j,j in tdict, j in ndict
if flag != 0:
errors.append(j)
break
seqs += ">%s\n%s\n" % (j,seq)
# problem black translate sequences
if flag != 0:
oup_rate.write("%s\t%s\t-\t-\t-\t-\t" % (llist[0],llist[1]))
if flag == 1:
print " size discrepancy between pep and cds seq"
oup_rate.write("pep_cds_discrepancy\n")
elif flag == 2:
print " sequence not found"
oup_rate.write("seq_absent\n")
count += 1
continue
# no problem, generate output
else:
S = seqs.split("\n")
# if asking for 4fold sites
if x4 == 1:
newseq = self.find_x4(S[1],S[3])
S[1] = newseq[0]
S[3] = newseq[1]
# no 4x sites
if len(S[1]) == 0:
oup_rate.write("%s\t%s\t-\t-\t-\t-\tno_4x_site\n"%\
(llist[0],llist[1]))
continue
if len(S[1]) == 0 or len(S[2]) == 0:
oup_rate.write("%s\t%s\t-\t-\t-\t-\tno_common_site\n"%\
(llist[0],llist[1]))
continue
oup = open("TMP.NT.FA","w")
oup.write(string.joinfields(S,"\n"))
###############################################################
# If sequence absent or size discrepancy, won't get past here
###############################################################
oup.close()
# calculate full length rate
if prog == "paml":
# convert FA into "simple PHYLIP"
self.to_phylip("TMP.NT.FA","TMP")
rate = self.do_yn00(paml_dir,llist)
else:
tmp = calculate(seqs)
rate = []
for i in tmp:
rate.append(str(i))
# deal with situations where no Ka or Ks is generated.
prog_error = 0
try:
Ka_full = float(rate[0])
Ks_full = float(rate[1])
except ValueError:
prog_error = 1
except IndexError:
prog_error = 2
#########################
# deal with window size
#########################
# program error
if prog_error != 0:
oup_rate.write("%s\t%s\t%sprog_err%i\n" %
(llist[0],llist[1],"-\t"*4,prog_error))
# output full length only
elif window == 0:
oup_rate.write("%s\t%s\t%s\n" % (llist[0],llist[1],
string.joinfields(rate,"\t")))
# go through windows
elif window > 0 and x4 == 0:
# generate a full length ka ks output as well
oup_rate.write("%s\t%s\t%s\n" % (llist[0],llist[1],
string.joinfields(rate,"\t")))
# make sure the window and step sizes are multiple of 3
if window%3 != 0:
window += (3-window%3)
if step % 3 != 0:
step += (3-step%3)
# cds sequence dict for a pair
sdict = fasta_manager.fasta_to_dict("TMP.NT.FA")
keys = sdict.keys()
leng = len(sdict[keys[0]][1])
idx = 0
while idx+window < leng:
#print "\n>>>>> WINDOW:",(idx/3+1)
#print sdict[keys[0]][1][idx:idx+window]
#print sdict[keys[1]][1][idx:idx+window]
oup_rate2.write("%s\t%s\t" % (llist[0],llist[1]))
seqs = ">%s\n%s\n>%s\n%s\n" % \
(keys[0],sdict[keys[0]][1][idx:idx+window],
keys[1],sdict[keys[1]][1][idx:idx+window])
if prog == "paml":
oup = open("TMP.NT.FA","w")
oup.write(seqs)
oup.close()
self.to_phylip("TMP.NT.FA","TMP")
rate = self.do_yn00(paml_dir,llist)
else:
#print seqs
tmp = calculate(seqs)
rate = []
for i in tmp:
rate.append(str(i))
# so far, the rate is empty if two sequences are exactly
# the same, paml throws Error: DistanceF84: input err..
# so the Ka/Ks is set to *
if rate == []:
oup_rate2.write("%s%s\t%i\n" % \
("-\t"*4,Ks_full,(idx/3+1)))
else:
oup_rate2.write("%s\t%f\t%i\n" % \
(string.joinfields(rate,"\t"),Ks_full,idx/3+1))
idx += step # because idx start from 0, no need to +1
#######################
# DISABLED!!!
"""
# modify gdom line
try:
glist = self.modify_gdom([llist[0]+"\t"+gdict[llist[0]],
llist[1]+"\t"+gdict[llist[1]]],
"TMP.GDE.FA")
except KeyError:
glist = [llist[0]+"\terror",
llist[1]+"\terror"]
# generate graphics
rkeys = rdict.keys()
rkeys.sort()
print "\nKa/Ks values:"
for k in rkeys:
print k/3+1,"\t",rdict[k]
draw_block.combine(glist,rdict,svg_writer,count,step)
"""
########################
if prog == "paml":
# Delete tmp files
if debug == 0:
os.system("rm TMP* 2YN* rst* rub")
pass
count += 1
if window != 0:
svg_writer.write_footer()
print "Size discrepancies between Nt and Pep:",
if error != []:
for i in errors:
print "",i
else:
print " none..."
print "\nDone!\n"
#
# Assume that the CDS is aligned with no stop like output of Translation.
# tl_mindless(). Pairs file is also generated with the same function.
#
def rate_pair2(self,pairs,cds,prog,paml_dir):
print "Read sequences into dict..."
cds = fasta_manager.fasta_to_dict(cds,verbose=0)
print "Process pairs:",
inp = open(pairs,"r")
inlines = inp.readlines()
np = len(inlines) # number of pairs
print np
oup_rate = open(pairs+".rate","w")
oup_rate.write("Seq1\tSeq2\tKa\tKs\tvKa\tvKs\n")
count = 0
for i in inlines:
i = i.strip()
if count % 1e2 == 0:
print " %i x100, %f%s" % (count/1e2,count*100.0/np,"%")
count += 1
PAIR = i.split("\t")
# Check if sequence is present
noseq1 = noseq2 = 0
if PAIR[0] not in cds:
print " no seq:",PAIR[0]
noseq1 = 1
if PAIR[1] not in cds:
print " no seq:",PAIR[1]
noseq2 = 1
if noseq1 or noseq2:
oup_rate.write("%s\t%s\t" % (PAIR[0],PAIR[1]))
oup_rate.write("-\t-\t-\t-\tno_seq:%i,%i\n" % (noseq1,noseq2))
continue
seqs = ">seq1\n%s\n>seq2\n%s\n" % (cds[PAIR[0]],cds[PAIR[1]])
if len(cds[PAIR[0]]) != len(cds[PAIR[1]]):
print "Err: length discrepancy",
print PAIR,len(cds[PAIR[0]]),len(cds[PAIR[1]])
print cds[PAIR[0]]
print cds[PAIR[1]]
sys.exit(0)
# calculate full length rate
if prog == "paml":
# convert FA into "simple PHYLIP"
oup = open("TMP.NT.FA","w")
oup.write(seqs)
oup.close()
self.to_phylip("TMP.NT.FA","TMP")
rate = self.do_yn00(paml_dir,PAIR)
else:
tmp = calculate(seqs)
rate = []
for i in tmp:
rate.append(str(i))
# deal with situations where no Ka or Ks is generated.
prog_error = 0
try:
Ka_full = float(rate[0])
Ks_full = float(rate[1])
except ValueError:
prog_error = 1
except IndexError:
prog_error = 2
sys.exit(0)
# program error
if prog_error != 0:
oup_rate.write("%s\t%s\t%sprog_err%i\n" %
(PAIR[0],PAIR[1],"-\t"*4,prog_error))
else:
oup_rate.write("%s\t%s\t%s\n" % (PAIR[0],PAIR[1],
string.joinfields(rate,"\t")))
if prog == "paml":
# Delete tmp files
if debug == 0:
os.system("rm TMP* 2YN* rst* rub")
pass
##
# subroutine for synchronize alignments and gdom coordinates THERE ARE BUGS
# IN THIS THING. SOME DON'T QUITE ALIGN RIGHT.
#
#
# @param glist a list of gdom lines
# @param aligned the fasta file of polypeptide alignments
##
def modify_gdom(self,glist,aligned):
adict = fasta_manager.fasta_to_dict(aligned)
#print adict