-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFastaManager.py
More file actions
executable file
·3163 lines (2792 loc) · 82.5 KB
/
FastaManager.py
File metadata and controls
executable file
·3163 lines (2792 loc) · 82.5 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
#!/usr/local/bin/python
##
#
# 08/21,02
# Implement compare_lists()
# 09/23,02
# Problem with DOS style files. In get_sequences, "\r\n" is explicitly detected
# but should use a generate function to convert file first.
# 01/02,03
# The function get_group_seq don't output sequences in the order of the input
# list. Make it so.
# 05/27,03
# This is very significant so I am writing this down. A new code seqment for
# fasta_to_dict is written, now it proceed at BLAZING SPEED.
##
import os, sys, FileUtility, string, Translation
class fasta_manager:
def __init__(self):
pass
#
# @param coords [seq_id][L][R]
#
def mask(self,fasta,coords):
print ("Read fasta into dict...")
F = self.fasta_to_dict(fasta,dflag=0)
print ("Read coords into dict...")
C = {}
inp = open(coords)
inl = inp.readline()
while inl != "":
L = inl.split("\t")
if C.has_key(L[0]):
C[L[0]].append([int(L[1]),int(L[2])])
else:
C[L[0]] = [[int(L[1]),int(L[2])]]
inl = inp.readline()
print ("Concatenate seq...")
for i in C:
if F.has_key(i):
print ("",i,"%i features" % len(C[i]))
c = 0
for j in C[i]:
if c % 100 == 0:
print (" %i x100" % (c/100))
c += 1
F[i] = "%s%s%s" % \
(F[i][:j[0]-1],"N"*(j[1]-j[0]+1),F[i][j[1]:])
else:
print ("SEQ ABSENT:",i)
print ("Write sequences...")
self.dict_to_fasta(F,fasta+".mask")
print ("Done!")
def dict_to_fasta(self,fdict,fname):
oup = open(fname,"w")
for i in fdict:
oup.write(">%s\n" % i)
s = fdict[i]
c = 0
while c < len(s):
oup.write("%s\n" % s[c:c+80])
c += 80
oup.close()
##
# This is written to get stretch from a LARGE sequence file with a single
# sequence, such as the chromosome sequence. The other method takes forever
# because the fasta is concatenated into a single string. A SERIOUS negative
# for this function is that the coords CANNOT overlap.
#
# @param fasta the implementation only work for one id one seq in the file
# @param coords separated by ",". Sequence obtained is inclusive of the
# coords OR a file name can be passed. The file contains
# a pair of coords separated by "," in each line
# @param call whether return the sequence as dict [1] or written [0]
# @param isfile coords in a file
##
def get_stretch2(self,fasta,coords,call=0,isfile=0):
print ("Fasta :",fasta)
print ("Coord :",coords)
print ("isfile :",isfile)
# check if coord is a file
if isfile:
inp = open(coords,"r")
inl = inp.readline()
# first read to a dict to sort the coords
order = {}
while inl != "":
L = self.rmlb(inl).split(",")
# assume coord are not overlapping
order[int(L[0])] = int(L[1])
inl = inp.readline()
okeys = order.keys()
okeys.sort()
clist = []
for i in okeys:
clist.extend([i,order[i]])
inp.close()
else:
clist = coords.split(",")
clist = [int(clist[0]),int(clist[1])]
inp = open(fasta,"r")
idx = self.rmlb(inp.readline())[1:]
# rid of anything after the 1st space
if idx.find(" ") != -1:
idx = idx[:idx.find(" ")]
inl = inp.readline()
c = 0
get = 0
odict = {}
ostr = ""
end = 0
read = 1
saved = 0
while inl != "":
inl = self.rmlb(inl)
#print [inl]
# only increment if this line has been read
if read:
c += len(inl)
else:
read = 1
if int(clist[0]) < int(clist[1]):
cL = int(clist[0])
cR = int(clist[1])
else:
cR = int(clist[0])
cL = int(clist[1])
if c > cL:
if get == 0:
#print "%s-%s" % (clist[0],clist[1]),cL,cR
#print " start:",
if c < cR:
ostr += "%s\n" % inl[cL-c+len(inl)-1:]
get = 1
else:
#print "end1"
ostr += "%s\n" % inl[cL-c+len(inl)-1:\
cR-c+len(inl)]
end = 1
else:
if c < cR:
#print ">%s\n" % inl
#print ".",
ostr += "%s\n" % inl
else:
#print "end2"
ostr += "%s\n" % inl[:cR-c+len(inl)]
end = 1
# store seq into dict and reset everything
if end:
#print " reset"
#print " store->",[ostr]
if saved % 10000 == 0:
print (" %i x 10k" % (saved/10000))
saved += 1
# deal with coords in reverse
if int(clist[0]) > int(clist[1]):
ostr = trans.rc(ostr)
print ("rc:",[ostr])
odict["%s|%s" % (clist[0],clist[1])] = ostr
# reset everything
end = 0
get = 0
ostr = ""
clist = clist[2:]
if clist == []:
break
# just in case that the next entry is also in this line.
if c > cL:
#print ">>>no_read"
read = 0
# read line or not
if read:
#print " new_line"
inl = inp.readline()
if call:
return odict
else:
if isfile:
oup = open(coords+".seg.fa","w")
else:
oup = open(fasta +".seg.fa","w")
for i in odict:
oup.write(">%s_%s\n%s" % (idx,i,odict[i]))
print ("Done!")
# for multiple chr, derived from get_stretch3.
# 2/24/12, coordinates used to be [chr][L][R] or can be multiple coordinates
# separated by ",". now allow only [seq][L1,R1,...]
#
# @param fasta can have multiple sequences in one file
# @param coords [seq][L1,R1,L2,R2...]. If L > R, take reverse complement.
# @param seqid Use 4th column of the coords file as sequence ID if available.
# (1) or not (0, default)
def get_stretch4(self,fasta,coords,seqid):
print ("Sequence to dict...")
seq = self.fasta_to_dict(fasta,0)
# fasta_to_dict got rid of "\n" already
print (seq.keys())
new_dict={}
for i in seq.keys():
newseq= i.strip().split(" ")[0]
print (newseq)
value= seq[i]
new_dict[newseq]=value
c = 0 # count total
m = 0 # count not in fasta
if coords.find(",") == -1:
print ("Read coordinates...")
inp = open(coords)
oup = open(coords+".fa","w")
oup2= open(coords+".missing","w")
inl = inp.readline()
while inl != "": # Go through each coord
if c % 1000 == 0:
print (" %i k" % (c/1000))
c += 1
L = inl.strip().split("\t")
seqName = L[0] # Sequnece name
if seqName in new_dict:
if len(L) >= 2:
# L = [name, L, R], some may have 4th col which is IDs to be given.
if L[1].find(",") == -1:
# Deal with reverse ori
ori= 1; cL = int(L[1]); cR = int(L[2])
if cL > cR:
ori = -1
# Get sequence
if ori == -1:
S = new_dict[seqName][cR-1:cL]
else:
S = new_dict[seqName][cL-1:cR]
if S == "":
print ("ERR COORD: %s,[%i,%i]" % (seqName,cL,cR))
else:
if ori == -1:
S = trans.rc(S)
# If there is 4th column, use them as sequence IDs.
if len(L) == 4 and seqid:
oup.write(">%s\n%s\n" % (L[3],S))
else:
oup.write(">%s|%i-%i\n%s\n" % (seqName,cL,cR,S))
# name <\t> "L1,R1,L2,R2..." <\t> whatever
elif L[1].find(",") != -1:
genename= L[2]
coordList = L[1].split(",")
S = ""
# Set orientation, only consider the first pair
if int(coordList[0]) < int(coordList[1]):
ori = 1
else:
ori = -1
for j in range(0,len(coordList),2):
cL = int(coordList[j]); cR = int(coordList[j+1])
if ori == -1:
cL = int(coordList[j+1])
cR = int(coordList[j])
S = new_dict[seqName][cL-1:cR] + S
else:
S += new_dict[seqName][cL-1:cR]
oup.write(">%s %s|%s\n%s\n" % (genename, seqName,"-".join(coordList),S))
else:
print ("Unknown cooord format:",L)
print ("Quit!")
sys.exit(0)
else:
m += 1
oup2.write(inl)
inl = inp.readline()
print ("Total coords:",c)
print ("Not in seq :",m)
oup2.close()
# coordinates are passed
else:
coords = coords.split(",")
print ("Coords:",coords)
oup = open("%s_%s.fa" % (fasta,"-".join(coords)),"w")
C = []
for i in coords:
C.append(int(i))
for i in seq:
s = ""
for j in range(0,len(C),2):
s += seq[i][C[j]-1:C[j+1]]
oup.write(">%s\n%s\n" % (i,s))
oup.close()
print ("Done!")
#
# Well... get_strech2 is problematic when overlapping sequences are needed.
# Now this method is much smarter... and much shorter too.
# 07/19,05. New lines are not formed in some entries. Fixed?
# 04/27,06. Reverse complement coordinates are not reflected. Fixed.
# Modify this for multiple sequences
#
# @para fasta file with single sequence
# @para coords coord file, tab-delim, the last two token have to be coords.
#
def get_stretch3(self,fasta,coords):
print ("Covert fasta into a string...")
inp = open(fasta)
inl = inp.readlines()
idx = self.rmlb(inl[0])[1:]
seq = string.joinfields(inl[1:],"")
# get rid of line breaks, sometimes \n and \r\n are mixed.
if seq.find("\r\n") != -1:
seq = string.joinfields(seq.split("\r\n"),"")
if seq.find("\n") != -1:
seq = string.joinfields(seq.split("\n"),"")
print (len(seq))
print ("Read coords and output seq...")
inp = open(coords)
oup = open(coords+".fa","w")
inl = inp.readline()
c = 0
while inl != "":
print ([inl])
if c % 10000 == 0:
print (" %i x 10k" % (c/10000))
c += 1
L = inl.split("\t")
# deal with reverse ori
cL = int(L[-2])
cR = int(L[-1])
ori = 1
if int(L[-2]) > int(L[-1]):
cL = int(L[-1])
cR = int(L[-2])
ori = -1
S = seq[cL-1:cR]
if S == "":
print ("ERR COORD: [%i,%i]" % (cL,cR))
else:
if ori == 1:
oup.write(">%s|%i-%i\n%s\n" % (idx,cL,cR,S))
else:
S = trans.rc(S)
oup.write(">%s|%i-%i\n%s\n" % (idx,cR,cL,S))
#print ">%s|%i-%i %s" % (idx,cR,cL,S[:10])
inl = inp.readline()
print ("Done!")
##
# coord format: from id<space>L-R to id_((L-1)*3+1)_R
##
def convert_header(self,fasta):
inp = open(fasta,"r")
oup = open(fasta+".coord.fa","w")
inl = inp.readline()
while inl != "":
if inl[0] == ">":
if inl.find(" ") == -1 or inl.find("-") == -1:
print ("Wrong descriptor format, Quit!")
sys.exit(0)
L = inl.split(" ")
left = int(L[1][:L[1].find("-")])
righ = int(L[1][L[1].find("-")+1:-1])
left = (left-1)*3+1
righ = righ*3
oup.write("%s_%i_%i\n" % (L[0],left,righ))
else:
oup.write(inl)
inl = inp.readline()
# rid of coords
#
# @style coord connected to id via underscore: 0 [default], or space [1]
def delete_coord(self,fasta,style):
print ("NOT SURE THIS IS WORKING YET")
inp = open(fasta,"r")
oup = open(fasta+".mod.fa","w")
inl = inp.readline()
while inl != "":
if inl[0] == ">":
if style == 0:
if inl.find("_") == -1:
oup.write(inl)
elif style == 1:
if inl.find(" ") == -1:
oup.write(inl)
inl = inp.readline()
##
# Return a dict with seq id as key, seq as value. Will convert things to
# UNIX format without "\r".
#
# 11/15 Major rewrite of the method
# 11/17 Deal with redundant id, before they are simply replaced.
#
# @param fasta
# @param desc include desc[1] or not[0,default]. The description is
# separated from seq id with a space. If include, it will
# be the first element of the list, the second will be seq
# @param verbose display line count [1], or not [0, default]
# @param dflag delimit by space or not, default no
# @param newline rid of new line or not
##
def fasta_to_dict(self,fasta,dflag=0,verbose=0,newline=0):
# each idx should only occur once.
inp = open(fasta,"r")
inl = inp.readline()
fdict = {} # idx as key, seq as value
c = 0
N = 0
while inl != "":
inl = self.rmlb(inl)
next = 0
idx = ""
desc = ""
if inl == "":
pass
elif inl[0] == ">":
if verbose and c%1e3 == 0:
print (" %i k" % (c/1e3))
c += 1
# rid of anything after space if asked
if dflag and inl.find(" ") != -1:
desc = idx[idx.find(" ")+1:]
idx = idx[:idx.find(" ")]
else:
idx = inl[1:]
# count lines and store seq into a list
slist = []
inl = inp.readline()
while inl[0] != ">":
inl = inl.strip()
# Add new line char, do this after strip because I do not
# want to have cases of /r/n
if newline:
inl = inl + "\n"
slist.append(inl)
inl = inp.readline()
if inl == "":
break
seq = "".join(slist)
if idx in fdict.keys():
#if fdict.has_key(idx):
if verbose:
print ("Redundant_id:",idx,)
if dflag:
if len(fdict[idx][1]) < len(seq):
fdict[idx] = [desc,seq]
if verbose:
print ("longer")
else:
if verbose:
print ("shorter")
else:
if len(fdict[idx]) < len(seq):
fdict[idx] = seq
if verbose:
print ("longer")
else:
if verbose:
print ("shorter")
else:
N += 1
if dflag:
fdict[idx] = [desc,seq]
else:
fdict[idx] = seq
next = 1
# so no extra line is read, because of the innder while
if not next:
inl = inp.readline()
inp.close()
if verbose:
print ("Total %i sequences, %i with non-redun names" % (c,N))
#print(fdict)
return fdict
#
# @param t Truncated or not, default no.
def fasta_to_phylip(self,fasta,t=0):
print ("To oneline...")
self.fasta_to_oneline(fasta)
print ("To phylip...")
inp = open(fasta+".pep")
oup = open(fasta+".phylip","w")
inl = inp.readlines()
c = 0
# Figure out the longest name
nlen = 0
for i in inl:
n = i.split("\t")[0]
if len(n) > nlen:
nlen = len(n)
#print nlen,n
#print nlen
for i in inl:
L = i.strip().split("\t")
# Write header
if c == 0:
oup.write("%i %i\n" % (len(inl),len(L[1])))
c += 1
n = L[0]
if t:
if len(n) > 10:
print ("Truncate name:",n)
n = n[:10]
oup.write("%s%s%s\n" % (n," "*(10-len(n)+1),L[1]))
else:
oup.write("%s%s%s\n" % (n," "*(nlen-len(n)+1),L[1]))
inp.close()
oup.close()
print ("Done!")
#
# This is mainly done for HMMER3...
#
def fasta_to_stockholm(self,fasta):
fa = self.fasta_to_dict(fasta)
blocklen = 80
# Find out length of the longest name and number of blocks
nlen = 0
nblc = 0
for i in fa:
if len(i) > nlen:
nlen = len(i)
if nblc == 0:
nblc = len(fa[i])/80.0
if nblc > int(nblc):
nblc = int(nblc)+1
else:
nblc = int(nblc)
# Output sequence blocks
oup = open(fasta+".stockholm","w")
oup.write("# STOCKHOLM 1.0\n\n")
nkeys = fa.keys()
nkeys.sort()
for i in range(nblc):
for j in nkeys:
n = "_".join(j.split(" ")) # Rid of space in names
#print nlen, len(n)
oup.write("%s%s%s\n" % (n,
" "*(nlen-len(n)+2),
fa[j][blocklen*i:blocklen*(i+1)]))
oup.write("\n")
oup.write("//")
oup.close()
##
# Generate fasta file based on species passed, assuming desc like:
# >XX_id
#
# @param fasta
##
def get_sp(self,fasta,species):
print ("Get sequences for a particular species:")
print (" Fasta :",fasta)
print (" Species:",species)
inp = open(fasta,"r")
oup = open(fasta+".%s.fa" % species,"w")
inl = inp.readline()
slist = []
w = 1 # write or not
c = 0
while inl != "":
if inl[0] == ">":
if inl[1:3] == species:
w = 1
c += 1
else:
w = 0
if w:
oup.write(inl)
inl = inp.readline()
print ("Total %i sequences" % c)
##
# Count the number of sequences for species specified
#
# @fasta
# @sp Species header file, each line one species.
##
def count_sp(self,fasta,sp):
print ("Read species info into a dict...")
inp = open(sp)
inl = inp.readlines()
S = {}
for i in inl:
S[i.strip()] = 0
print ("Go through fasta...")
inp = open(fasta)
inl = inp.readline()
while inl != "":
if inl[0] == ">":
n = inl.strip()[1:]
sp = []
for j in S:
if j in n:
sp.append(j)
if len(sp) == 0:
print (" No sp definition:",n)
elif len(sp) >1:
print (" Ambiguous",n,sp)
else:
S[sp[0]] += 1
inl = inp.readline()
print ("Generate output...")
oup = open(fasta+".sp_count","w")
for i in S:
oup.write("%s\t%s\n" % (i,S[i]))
print ("Done!")
#
# Convert GFF to coord file
#
def gff_to_coord(self,gff):
inp = open(gff)
oup = open(gff+".coord","w")
inl = inp.readline()
while inl != "":
#print (inl)
T = inl.strip().split("\t") # tokens
if len(T) > 6:
#print (T)
C = T[0] # chr
if T[6] == "+": # orientation
L = T[3] # left coord
R = T[4] # right coord
else:
L = T[4]
R = T[3]
N = "" # sequence name
n = T[-1].split(";")
if "Name" in T[-1]: # has Name tag, # refers to last item in list
for j in n:
if "Name" in j:
N = j.split("=")[1]
break
elif T[-1] != "": # no name tag but not empty, use 1st
N = n[0].split("=")[1]
else:
print ("No desc:",T)
if N != "":
oup.write("%s\t%s\t%s\t%s\n" % (C,L,R,N))
else:
print(T, "line not used")
inl = inp.readline()
print ("Done!")
#
# Convert GFF to coord file for 1000bp upstream of genes
#
def gff_prom_to_coord2(self,gff):
inp = open(gff)
oup = open(gff+".coord","w")
inl = inp.readline()
tmp_list=[]
count= 0
while inl != "":
#print (inl)
T = inl.strip().split("\t") # tokens
if len(T) > 6:
C = T[0] # chr
#print (T[2])
if T[2] == 'gene' and count== 0:
#count= count+1
tmp_list=[]
if T[6] == "+": # orientation
L = T[3] # left coord
R = T[4] # right coord
prom= int(L)-1000 #get 1000 bp upstream of L
else:
L = T[4]
R = T[3]
prom = int(L)+1000
#print (prom, L)
if prom > 0:
tmp_list=[L, prom]
else:
tmp_list=[L, 0]
#if T[2]=='mRNA' and count== 1: #only get the protein name
N = "" # sequence name
n = T[-1].split(";") # get gene name
#print(n)
if "Name" in T[-1]: # has Name tag, # refers to last item in list
for j in n:
if "Name" in j:
N = j.split("=")[1]
#print(N)
break
elif T[-1] != "": # no name tag but not empty, use 1st
N = n[0].split("=")[1]
else:
print ("No desc:",T)
if N != "":
#print(tmp_list)
L2= tmp_list[0]
prom2= tmp_list[1]
oup.write("%s\t%s,%s\t%s\n" % (C,prom2,L2,N))
count = 0
else:
pass
#print(T, "line not used")
inl = inp.readline()
print ("Done!")
#clear spaces
def clear_space(self,string): #returns tab-delimited
string = string.strip()
while " " in string:
string = string.replace(" "," ")
string = string.replace(" ","")
return (string)
def gff_promoter_to_coord(self,gff):
inp = open(gff)
oup = open(gff+".coord","w")
inl = inp.readline()
while inl != "":
#gene = ""
#print (gene)
if inl.startswith('##'):
T1 = inl.strip().split(" ") #split line
gene = T1[1]
#oup.write("%s\t" % (gene))
elif inl.startswith('#'):
T1 = inl.strip().split(" ") #split line
gene = T1[1]
#oup.write("%s\t" % (gene))
else:
T = inl.strip().split("\t") # tokens
C = T[0] # chr
if T[6] == "+": # orientation
L = T[3] # left coord
R = T[4] # right coord
else:
L = T[4]
R = T[3]
if self.clear_space(T[2]) == "promoter": # check if this is the promoter
oup.write("%s\t%s\t%s\t" % (C,L,R))
oup.write("%s\n" % (gene))
else:
pass
#print (gene)
inl = inp.readline()
print ("Done!")
#
# Rename all files in dir, if they have .fa or .fasta extension.
#
def rename_all(self,targetDir,name):
fList = os.listdir(targetDir)
for i in fList:
if i[-3:] == ".fa" or i[-6:] == ".fasta":
self.rename2("%s/%s" % (targetDir,i),name,"")
print ("rename_all done!")
#
# New rename function. But this function is not so good. It's slow and
# only output seq if new name is found.. Should throw this away.
#
def rename2(self,fasta,name,ignore=""):
print ("Read fasta file:",fasta)
fdict = manager.fasta_to_dict(fasta,0)
print ("Rename sequence...")
inp = open(name,"r")
inl = inp.readline()
oup = open(fasta+"_rename.fa","w")
absent = []
ndict = {}
countN = 0
countS = 0
while inl != "":
countN += 1
inl = inl.strip().split("\t")
if fdict.has_key(inl[1]):
countS += 1
oup.write(">%s\n%s\n" % (inl[0],fdict[inl[1]]))
if ndict.has_key(inl[1]):
ndict[inl[1]]+= 1
else:
ndict[inl[1]] = 1
else:
absent.append(inl[1])
inl = inp.readline()
oup = open(fasta + "_rename.log","w")
oup.write("In name file but not in sequence file:\n ")
oup.write("%s" % string.joinfields(absent,"\n "))
oup.write("\nSequence id redundant:\n ")
for i in ndict:
if ndict[i] > 1:
oup.write(" %s: %i\n" % (i,ndict[i]))
print ("Fasta: %i entries, %i with new name" % (len(fdict.keys()),countS))
print ("Name : %i entries, %i unique, %i not in fasta" % \
(countN,len(ndict.keys()),len(absent)))
print ("Done!")
##
# Rename id within fasta file
#
# @param fasta
# @param name name file in [new][old] format. Tab-delimited.
# @param ignore Ignore whatever is after the passed char. Default nothing.
#
##
def rename(self,fasta,name,ignore=""):
# put names to a dict, old as key, new as value
inp = open(name,"r")
inl = inp.readline()
ndict = {}
countR = 0
found = 0
print ("Read name file...")
oup_log.write("Redundant names:\n")
while inl != "":
inl = self.rmlb(inl)
L = inl.split("\t")
if ndict.has_key(L[1].lower()):
print ("",L[1])
found = 1
countR = countR+1
else:
ndict[L[1].lower()] = L[0]
inl = inp.readline()
if not found:
print (" none")
# scan fasta descriptor line
print ("Read fasta file and change names...")
inp = open(fasta,"r")
oup = open(fasta+"_rename.fa","w")
inl = inp.readline()
countF = 0 # found
countN = 0 # not found
oup_log.write("\nFasta name not found:\n")
while inl != "":
if inl[0] == ">":
inl = self.rmlb(inl)
if ignore == "" or inl.find(ignore) == -1:
if ndict.has_key(inl[1:].lower()):
oup.write(">%s\n" % ndict[inl[1:].lower()])
countF = countF+1
# if no new name, just output old ones.
else:
oup.write(inl+"\n")
oup_log.write(" %s\n" % inl[1:])
countN = countN+1
else:
if ndict.has_key(inl[1:inl.find(ignore)].lower()):
oup.write(">%s%s\n" % \
(ndict[inl[1:inl.find(ignore)].lower()],\
inl[inl.find(ignore):]))
countF = countF+1
# if no new name, just output old ones.
else:
oup.write(inl+"\n")
oup_log.write(" %s\n" % inl[1:])
countN = countN+1
else:
oup.write(inl)
inl = inp.readline()
oup.close()
print ("Found %s, not found %s, %i redundant" % (countF,countN,countR))
print ("Done!")
##
# Convert fasta seq id back to its original ones
#
# @param fasta the fasta desc line can have just ">name\n" or something
# like ">name description". The script looks for space as
# delimiter in this case, so name should NOT contain any
# of it.
# @param desc_flag should see string after space as desc [1] or not [0]
# @param name_file in the format [new_name][old_name]
##
def change_names(self,fasta,name_file,desc_flag,delim=" "):
print ("Change ID in Fasta file")
print (" Fasta:",fasta)
print (" Name :",name_file)
# read names into a dict
ndict = f_util.file_to_dict(name_file,5)
#print ndict
# compare names against the fasta file
inp = open(fasta,"r")
oup = open(fasta+".mod.fa","w")
inl = inp.readline()
countF = 0
countA = 0
while inl != "":
if inl[0] == ">":
countA = countA + 1
old = inl[1:-1]
desc = ""
if desc_flag and inl.find(" ") != -1:
old = old[:old.find(" ")]
desc = inl[inl.find(" ")+1:-1]
print (old,">>",desc)