-
Notifications
You must be signed in to change notification settings - Fork 2
/
ebed2GenePred.py
executable file
·482 lines (373 loc) · 13.9 KB
/
ebed2GenePred.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
#!/usr/bin/env python
'''
Copyright 2010 Wu Albert Cheng <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
'''
extended bed (ebed)
1) chrom
2) chrom start g0
3) chrom end g1
4) name
5) score
6) strand
7) thickStart = CDS Start g0
8) thickEnd = CDS End g1
9) itemRGB
10) blockCount = exonCount
11) blockSizes (,)
12) blockStarts (,) relative to Chom Start in 0-based
----
genePred format
1) name
2) chrom
3) strand
4) txStart g0
5) txEnd g1
6) cdsStart g0
7) cdsEnd g1
8) exonCount
9) exonStarts g0
10) exonEnds g1
'''
from sys import *
from operator import itemgetter
def toStrListInPlaceRecursive(L,prefix="",suffix="",sep=","):
emptyL=[]
emptyT=tuple()
emptySet=set()
for i in range(0,len(L)):
if type(L[i])==type(emptyL) or type(L[i])==type(emptyT) or type(L[i])==type(emptySet):
L[i]=prefix+sep.join(toStrListInPlaceRecursive(L[i]))+suffix
else:
L[i]=str(L[i])
return L
def ebedFields2genePredFields(fields,score,itemRgb,options):
try:
chrom,chromStartG0,chromEndG1,name,score,strand,thickStartG0,thickEndG1,itemRGB,blockCount,blockSizes,blockStarts0=fields
chromStartG0=int(chromStartG0)
chromEndG1=int(chromEndG1)
thickStartG0=int(thickStartG0)
thickEndG1=int(thickEndG1)
blockCount=int(blockCount)
blockSizeSplits=blockSizes.split(",")
blockSizes=[]
for s in blockSizeSplits:
s=s.strip()
if len(s)>0:
blockSizes.append(int(s))
blockStarts0Splits=blockStarts0.split(",")
blockStarts0=[]
for s in blockStarts0Splits:
s=s.strip()
if len(s)>0:
blockStarts0.append(int(s))
if len(blockStarts0)!=blockCount or len(blockSizes)!=blockCount:
print >> stderr,"block count not consistent with blockStarts or blockSizes data"
raise ValueError
except:
print >> stderr,"format error",fields
raise ValueError
exonStartsG0=[]
exonEndsG1=[]
for bStart0,bSize in zip(blockStarts0,blockSizes):
exonStartsG0.append(bStart0+chromStartG0)
exonEndsG1.append(bStart0+chromStartG0+bSize)
genePredFields=[name,chrom,strand,chromStartG0,chromEndG1,thickStartG0,thickEndG1,blockCount,exonStartsG0,exonEndsG1]
toStrListInPlaceRecursive(genePredFields)
return genePredFields
def genePredFields2ebedFields(fields,score,itemRgb,options):
try:
name,chrom,strand,txStartG0,txEndG1,cdsStartG0,cdsEndG1,exonCount,exonStartsG0,exonEndsG1=fields
txStartG0=int(txStartG0)
txEndG1=int(txEndG1)
cdsStartG0=int(cdsStartG0)
cdsEndG1=int(cdsEndG1)
exonCount=int(exonCount)
exonStartsG0Splits=exonStartsG0.split(",")
exonEndsG1Splits=exonEndsG1.split(",")
exonStartsG0=[]
for s in exonStartsG0Splits:
s=s.strip()
if len(s)>0:
exonStartsG0.append(int(s))
exonEndsG1=[]
for s in exonEndsG1Splits:
s=s.strip()
if len(s)>0:
exonEndsG1.append(int(s))
if len(exonStartsG0)!=exonCount or len(exonEndsG1)!=exonCount:
print >> stderr,"exon count not consistent with exon starts and exon ends data"
raise ValueError
except:
print >> stderr,"format error",fields
raise ValueError
blockSizes=[]
blockStarts0=[]
for eStartG0,eEndG1 in zip(exonStartsG0,exonEndsG1):
blockStarts0.append(eStartG0-txStartG0)
blockSizes.append(eEndG1-eStartG0)
ebedFields=[chrom,txStartG0,txEndG1,name,score,strand,cdsStartG0,cdsEndG1,itemRgb,exonCount,blockSizes,blockStarts0]
toStrListInPlaceRecursive(ebedFields)
return ebedFields
def readEEBedSeq(filename):
EEBedSeqDict=dict()
fil=open(filename)
for lin in fil:
fields=lin.rstrip().split("\t")
chrom=fields[0]
start=int(fields[1])
end=int(fields[2])
seq=fields[-1] #last field
try:
chromDict=EEBedSeqDict[chrom]
except KeyError:
chromDict=dict()
EEBedSeqDict[chrom]=chromDict
chromDict[(start,end)]=seq
fil.close()
return EEBedSeqDict
def EbedFieldsToEbedSeqField(fields,eebedSeqDict):
try:
chrom,chromStartG0,chromEndG1,name,score,strand,thickStartG0,thickEndG1,itemRgb,blockCount,blockSizes,blockStarts0=fields
chromStartG0=int(chromStartG0)
chromEndG1=int(chromEndG1)
thickStartG0=int(thickStartG0)
thickEndG1=int(thickEndG1)
blockCount=int(blockCount)
blockSizeSplits=blockSizes.split(",")
blockSizes=[]
for s in blockSizeSplits:
s=s.strip()
if len(s)>0:
blockSizes.append(int(s))
blockStarts0Splits=blockStarts0.split(",")
blockStarts0=[]
for s in blockStarts0Splits:
s=s.strip()
if len(s)>0:
blockStarts0.append(int(s))
if len(blockStarts0)!=blockCount or len(blockSizes)!=blockCount:
print >> stderr,"block count not consistent with blockStarts or blockSizes data"
raise ValueError
except:
print >> stderr,"format error",fields
raise ValueError
seq=""
eebedSeqDictChrom=eebedSeqDict[chrom]
for bStart0,bSize in zip(blockStarts0,blockSizes):
exonStartG0=bStart0+chromStartG0
exonEndG1=bStart0+chromStartG0+bSize
try:
seq+=eebedSeqDictChrom[(exonStartG0,exonEndG1)]
except:
print >> stderr,"Error in eebedSeq",chrom,":",exonStartG0,"-",exonEndG1,"not found. Abort"
exit()
return fields+[seq]
def expandEbedFieldsToBedFieldList(fields,score,itemRgb,replaceCDSPosWithTranscriptStartEnd):
try:
chrom,chromStartG0,chromEndG1,name,score,strand,thickStartG0,thickEndG1,itemRgb,blockCount,blockSizes,blockStarts0=fields
chromStartG0=int(chromStartG0)
chromEndG1=int(chromEndG1)
thickStartG0=int(thickStartG0)
thickEndG1=int(thickEndG1)
blockCount=int(blockCount)
blockSizeSplits=blockSizes.split(",")
blockSizes=[]
for s in blockSizeSplits:
s=s.strip()
if len(s)>0:
blockSizes.append(int(s))
blockStarts0Splits=blockStarts0.split(",")
blockStarts0=[]
for s in blockStarts0Splits:
s=s.strip()
if len(s)>0:
blockStarts0.append(int(s))
if len(blockStarts0)!=blockCount or len(blockSizes)!=blockCount:
print >> stderr,"block count not consistent with blockStarts or blockSizes data"
raise ValueError
except:
print >> stderr,"format error",fields
raise ValueError
bedFieldList=[]
for bStart0,bSize in zip(blockStarts0,blockSizes):
exonStartG0=bStart0+chromStartG0
exonEndG1=bStart0+chromStartG0+bSize
if exonEndG1<=thickStartG0 or exonStartG0>=thickEndG1: #out of Range~!
cdsStartForThisExon=0
cdsEndForThisExon=0
else:
cdsStartForThisExon=max(thickStartG0,exonStartG0)
cdsEndForThisExon=min(thickEndG1,exonEndG1)
if replaceCDSPosWithTranscriptStartEnd:
bedFields=[chrom,exonStartG0,exonEndG1,name,score,strand,chromStartG0,chromEndG1,itemRgb,1,bSize,0]
else:
bedFields=[chrom,exonStartG0,exonEndG1,name,score,strand,cdsStartForThisExon,cdsEndForThisExon,itemRgb,1,bSize,0]
toStrListInPlaceRecursive(bedFields)
bedFieldList.append(bedFields)
return bedFieldList
def genePredFields2exonexpandedebedFields(fields,score,itemRgb,options):
return expandEbedFieldsToBedFieldList(genePredFields2ebedFields(fields,score,itemRgb),score,itemRgb,options.replaceCDSPosWithTranscriptStartEnd)
def printListOfFields(stream,L,sep="\t"):
if len(L)<1:
return
if type(L[0])==type(list()):
for subL in L:
print >> stream,sep.join(subL)
else:
print >> stream,sep.join(L)
def convertFormat(filename,converter,score,itemRgb,options):
fil=open(filename)
lino=0
for lin in fil:
lino+=1
fields=lin.rstrip("\r\n").split(options.FS)
try:
ofields=converter(fields,score,itemRgb,options)
except ValueError:
if options.AbortOnError:
print >> stderr,"Abort on line #"+str(lino),fields
exit()
else:
continue
printListOfFields(stdout,ofields)
fil.close()
def ebedToebedSeqConvert(filename,eebedseqfilename,options):
eebedseqDict=readEEBedSeq(eebedseqfilename)
fil=open(filename)
for lin in fil:
fields=lin.rstrip("\r\n").split(options.FS)
try:
ofields=EbedFieldsToEbedSeqField(fields,eebedseqDict)
except ValueError:
if options.AbortOnError:
print >> stderr,"Abort on line #"+str(lino),fields
exit()
else:
continue
printListOfFields(stdout,ofields)
fil.close()
def exonbedToEbed(filename,options):
store=dict() # store[geneName]=[ chrom, score, strand , (start0, end1), ... ]
if options.splitNameComp:
splitter,componentDiscard=options.splitNameComp
componentDiscard=int(componentDiscard)
fil=open(filename)
for lin in fil:
lin=lin.rstrip("\r\n")
if len(lin)<1 or lin[0]=="#":
continue
strand="."
score="0"
fields=lin.split(options.FS)
if len(fields)<4:
print >> stderr,"line with insufficient column, abort:",fields
continue
chrom=fields[0]
start0=int(fields[1])
end1=int(fields[2])
name=fields[3]
if len(fields) >= 5:
score=fields[4]
if len(fields)>=6:
strand=fields[5]
if options.splitNameComp:
name=name.split(splitter)[:-componentDiscard]
try:
geneStruct=store[name]
except KeyError:
geneStruct=[chrom,score,strand]
store[name]=geneStruct
geneStruct.append((start0,end1))
fil.close()
#now go to each gene
for geneName,geneStruct in store.items():
chrom=geneStruct[0]
score=geneStruct[1]
strand=geneStruct[2]
exons=geneStruct[3:]
exons.sort(key=itemgetter(0))
chromStart0=exons[0][0]
chromEnd1=exons[-1][1]
fields=[chrom,str(chromStart0),str(chromEnd1),geneName,score,strand,str(chromStart0),str(chromEnd1),options.itemRgb,str(len(exons))]
blockSizes=[]
blockStarts=[]
for exonStart0,exonEnd1 in exons:
blockSizes.append(str(exonEnd1-exonStart0))
blockStarts.append(str(exonStart0-chromStart0))
fields.append(",".join(blockSizes))
fields.append(",".join(blockStarts))
print >> stdout,options.FS.join(fields)
'''
1) chrom
2) chrom start g0
3) chrom end g1
4) name
5) score
6) strand
7) thickStart = CDS Start g0
8) thickEnd = CDS End g1
9) itemRGB
10) blockCount = exonCount
11) blockSizes (,)
12) blockStarts (,) relative to Chom Start in 0-based
'''
if __name__=='__main__':
from optparse import OptionParser
usage="usage: %prog [other options] filename [ebed2genePred*|--genePred2ebed|--genePred2exonebed|--ebed2exonebed|--ebed2ebedseq eebedseq|--exonbed2ebed]"
parser=OptionParser(usage)
#parser.add_option("--genePred2ebed",dest="genePred2ebed",default=False,action="store_true",help="convert genePred to ebed format")
#parser.add_option("--genePred2exonebed",dest="genePred2exonebed",default=False,action="store_true",help="convert genePred to exon expanded ebed format")
#parser.add_option("--ebed2exonebed",dest="ebed2exonebed",default=False,action="store_true",help="convert ebed into exon expanded ebed format")
parser.add_option("--genePred2ebed",const=genePredFields2ebedFields,dest="conversion",default=ebedFields2genePredFields,action="store_const",help="convert genePred to ebed format")
parser.add_option("--genePred2exonebed",const=genePredFields2exonexpandedebedFields,dest="conversion",default=ebedFields2genePredFields,action="store_const",help="convert genePred to exon expanded ebed format")
parser.add_option("--ebed2exonebed",const=expandEbedFieldsToBedFieldList,dest="conversion",default=ebedFields2genePredFields,action="store_const",help="convert ebed into exon expanded ebed format")
parser.add_option("--score",default="0",dest="score",help="set score (bed output)")
parser.add_option("--itemRgb",default="0,0,0",dest="itemRgb",help="set itemRgb (bed output)")
parser.add_option("--ebed2ebedseq",dest="ebedseq",default=None,help="transcribe the gene structure to make ebedseq file (with the last column as transcribed sequence)")
#parser.conversion=genePredFields2ebedFields
parser.add_option("--replace-Start-End-With-Transcript-Start-End",dest="replaceCDSPosWithTranscriptStartEnd",default=False,action="store_true",help="replace the CDS start end end field with transcript start and end field (valid for --ebed2exonbed)")
parser.add_option("--abort-on-error",default=False,dest="AbortOnError",action="store_true",help="aborts on error parsing a line of input")
parser.add_option("--fs",default="\t",dest="FS",help="set fields separator. default [tab]")
parser.add_option("--split-name-component-for-exonbed",dest="splitNameComp",default=None,nargs=2,help="set splitting of if component, e.g., '.' 1 means that the last component from .-split are to be removed for the ebed ID, default none")
parser.add_option("--exonbed2ebed",dest="exonBed2EBed",default=False,action="store_true",help="convert exon bed using gene name (see --split-name-component-for-exonbed option) to ebed")
(options, args) = parser.parse_args()
try:
filename,=args
except:
parser.print_help()
exit()
if options.ebedseq:
eebedseqfilename=options.ebedseq
ebedToebedSeqConvert(filename,eebedseqfilename,options)
elif options.exonBed2EBed:
exonbedToEbed(filename,options)
else:
convertFormat(filename,options.conversion,options.score,options.itemRgb,options)
#opsum=int(options.genePred2ebed)+int(options.genePred2exonebed)+int(options.ebed2exonebed)
#if opsum==0: #do default [ebed2genePred]
#elif opsum==1: #do required
# if options.genePred2ebed:
# elif options.genePred2exonebed:
# elif options.ebed2exonebed:
# else: #will not happen
# pass
#else:
# print >> stderr,"please make decision, cannot perform multiple operations"
# parser.print_help()
# exit()