-
Notifications
You must be signed in to change notification settings - Fork 4
/
GffTranscriptReader.py
executable file
·445 lines (424 loc) · 18.4 KB
/
GffTranscriptReader.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
#=========================================================================
# This is OPEN SOURCE SOFTWARE governed by the Gnu General Public
# License (GPL) version 3, as described at www.opensource.org.
# Copyright (C)2016 William H. Majoros (martiandna@gmail.com).
#=========================================================================
from __future__ import (absolute_import, division, print_function,
unicode_literals, generators, nested_scopes, with_statement)
from builtins import (bytes, dict, int, list, object, range, str, ascii,
chr, hex, input, next, oct, open, pow, round, super, filter, map, zip)
# The above imports should allow this program to run in both Python 2 and
# Python 3. You might need to update your version of module "future".
from Exon import Exon
from Transcript import Transcript
from Gene import Gene
from Integer import Integer
from Rex import Rex
import re
######################################################################
# Returns a list of Transcripts. For each transcript, the Exons
# will be sorted according to order of translation, so that
# the exon containing the start codon will come before the exon
# containing the stop codon. This means that for the minus strand,
# exon begin coordinates will be decreasing. However, an individual
# exon's begin coordinate is always less than its end coordinate.
# The transcripts themselves are sorted along the chromosome left-to-
# right. Note that although the GFF coordinates are 1-based/base-based
# (1/B), internally all coordinates are stored as 0-based/space-based
# (0/S). This conversion is handled automatically.
#
# Attributes:
# shouldSortTranscripts
# exonsAreCDS : interpret "exon" features as "CDS" when reading GFF
# Methods:
# reader=GffTranscriptReader()
# reader.setStopCodons({"TAG":1,"TAA":1,"TGA":1})
# transcriptArray=reader.loadGFF(filename)
# geneList=reader.loadGenes(filename)
# hashTable=reader.hashBySubstrate(filename)
# reader.hashBySubstrateInto(filename,hash)
# hashTable=reader.hashGenesBySubstrate(filename)
# hashTable=reader.loadTranscriptIdHash(filename)
# hashTable=reader.loadGeneIdHash(filename)
# reader.doNotSortTranscripts()
######################################################################
class GffTranscriptReader:
def __init__(self):
self.shouldSortTranscripts=True
self.exonsAreCDS=False
self.stopCodons={"TAG":1,"TAA":1,"TGA":1}
def loadGenes(self,filename):
transcripts=self.loadGFF(filename)
genes=set()
for transcript in transcripts:
gene=transcript.getGene()
if(not gene):
raise Exception("transcript "+transcript.getID()+
" has no gene")
genes.add(gene)
genes=list(genes)
genes.sort(key=lambda gene: gene.getBegin())
return genes
def doNotSortTranscripts(self):
self.shouldSortTranscripts=False
def loadTranscriptIdHash(self,filename):
transcriptArray=self.loadGFF(filename)
hash={}
for transcript in transcriptArray:
id=transcript.getID()
hash[id]=transcript
return hash
def loadGeneIdHash(self,filename):
transcriptArray=self.loadGFF(filename)
hash={}
for transcript in transcriptArray:
id=transcript.getGeneId()
array=hash.get(id,None)
if(array is None): array=hash[id]=[]
array.append(transcript)
return hash
def hashBySubstrate(self,filename):
hash={}
self.hashBySubstrateInto(filename,hash)
return hash
def hashBySubstrateInto(self,filename,hash):
transcriptArray=self.loadGFF(filename)
for transcript in transcriptArray:
id=transcript.getSubstrate()
array=hash.get(id,None)
if(array is None): array=hash[id]=[]
array.append(transcript)
def hashGenesBySubstrate(self,filename):
geneArray=self.loadGenes(filename)
hash={}
for gene in geneArray:
id=gene.getSubstrate()
array=hash.get(id,None)
if(array is None): array=hash[id]=[]
array.append(gene)
return hash
def computeFrames(self,transcripts):
for transcript in transcripts:
if(not transcript.areExonTypesSet()): transcript.setExonTypes()
strand=transcript.getStrand()
exons=transcript.exons
frame=0 # fine for both strands
for exon in exons:
exon.frame=frame
length=exon.getLength()
frame=(frame+length)%3 # this is fine, on both strands
def exonContainsPoint(self,exon,point):
return point>=exon.begin and point<=exon.end;
# this '<=' is necessary for the minus strand!
# do not change it back to '<' !!!
def setStopCodons(self,stopCodons):
self.stopCodons=stopCodons
def adjustStartCodons_fw(self,transcript,totalIntronSize):
startCodon=None
exons=transcript.exons
exons.sort(key=lambda exon: exon.begin)
numExons=len(exons)
#if(transcript.getID()=="ENST00000361390.2"):
# print("adjustStartCodons_fw",numExons,"exons")
if(numExons==0): return None
if(transcript.begin is None) :
transcript.begin=exons[0].begin
if(transcript.end is None):
transcript.end=exons[numExons-1].end
if(transcript.startCodon is not None):
startCodon=transcript.startCodon-transcript.begin
else:
startCodon=0
transcript.startCodon=transcript.begin
transcript.startCodonAbsolute=transcript.begin
for i in range(numExons): exons[i].order=i
for i in range(numExons):
exon=exons[i]
if(i>0):
prevExon=exons[i-1]
intronSize=exon.begin-prevExon.end
totalIntronSize+=intronSize
if(transcript.startCodon is not None and
self.exonContainsPoint(exon,transcript.startCodon)): break
return startCodon
def adjustStartCodons_bw(self,transcript,totalIntronSize):
startCodon=None
exons=transcript.exons
exons.sort(key=lambda exon: exon.begin,reverse=True)
numExons=len(exons)
if(numExons==0): return None
if(transcript.end is None): transcript.end=exons[0].end
if(transcript.begin is None): transcript.begin=exons[numExons-1].begin
if(transcript.startCodon is not None):
startCodon=transcript.end-transcript.startCodon
else:
startCodon=0
transcript.startCodon=transcript.end ###
transcript.startCodonAbsolute=transcript.end ###
for i in range(numExons):
exon=exons[i]
exon.order=i
if(i>0):
prevExon=exons[i-1]
intronSize=prevExon.begin-exon.end
totalIntronSize+=intronSize
if(transcript.startCodon is not None and
self.exonContainsPoint(exon,transcript.startCodon)): break
return startCodon
def adjustStartCodons(self,transcripts):
for transcript in transcripts:
transcript.sortExons()
transcript.adjustOrders()
strand=transcript.strand
startCodon=None
totalIntronSize=Integer(0)
if(strand=="+"):
startCodon=\
self.adjustStartCodons_fw(transcript,totalIntronSize)
else:
startCodon=\
self.adjustStartCodons_bw(transcript,totalIntronSize)
if(startCodon is not None):
startCodon-=int(totalIntronSize)
transcript.startCodon=startCodon
def loadGFF_transcript(self,fields,line,transcriptBeginEnd,GFF,
transcripts,readOrder,genes):
begin=int(fields[3])-1
end=int(fields[4])
rex=Rex()
if(rex.find('transcript_id[:=]?\s*"?([^\s";]+)"?',line)):
transcriptId=rex[1]
transcriptBeginEnd[transcriptId]=[begin,end]
strand=fields[6]
score=fields[5]
transcriptExtraFields=""
for i in range(8,len(fields)):
transcriptExtraFields+=fields[i]+" "
transcript=transcripts.get(transcriptId,None)
if(transcript is None):
transcripts[transcriptId]=transcript= \
Transcript(transcriptId,strand)
transcript.setStopCodons(self.stopCodons)
transcript.readOrder=readOrder;
readOrder+=1
transcript.substrate=fields[0]
transcript.source=fields[1]
transcript.setBegin(begin)
transcript.setEnd(end)
if(transcript.score is None and
score!="."): transcript.score=float(score)
geneId=None
if(rex.find("genegrp=(\S+)",line)): geneId=rex[1]
elif(rex.find('gene_id[:=]?\s*\"?([^\s\;"]+)\"?',line)):
geneId=rex[1]
if(not geneId): raise Exception("can't parse GTF: "+line)
transcript.geneId=geneId
gene=genes.get(geneId,None)
if(not gene): genes[geneId]=gene=Gene(); gene.setId(geneId)
transcript.setGene(gene)
gene.addTranscript(transcript)
transcript.extraFields=transcriptExtraFields
def loadGFF_UTR(self,fields,line,transcriptBeginEnd,GFF,
transcripts,readOrder,genes):
exonBegin=int(fields[3])-1
exonEnd=int(fields[4])
exonScore=fields[5]
strand=fields[6]
frame=fields[7]
transcriptId=None
rex=Rex()
if(rex.find('transgrp[:=]\s*(\S+)',line)): transcriptId=rex[1]
elif(rex.find('transcript_id[:=]?\s*"?([^\s";]+)"?',line)):
transcriptId=rex[1]
elif(rex.find('Parent=([^;,\s]+)',line)): transcriptId=rex[1]
geneId=None
if(rex.find('genegrp=(\S+)',line)): geneId=rex[1]
elif(rex.find('gene_id[:=]?\s*"?([^\s\;"]+)"?',line)): geneId=rex[1]
if(transcriptId is None): transcriptId=geneId
if(geneId is None): geneId=transcriptId
if(transcriptId is None):
raise Exception(line+" : no transcript ID found")
if(rex.find("(\S+);$",transcriptId)): transcriptId=rex[1]
if(rex.find("(\S+);$",geneId)): geneId=rex[1]
extra=""
for i in range(8,len(fields)): extra+=fields[i]+" "
if(exonBegin>exonEnd): (exonBegin,exonEnd)=(exonEnd,exonBegin)
transcript=transcripts.get(transcriptId,None)
if(not transcript):
transcripts[transcriptId]=transcript= \
Transcript(transcriptId,strand)
transcript.setStopCodons(self.stopCodons)
transcript.readOrder=readOrder
readOrder+=1
transcript.substrate=fields[0]
transcript.source=fields[1]
if(transcriptBeginEnd.get(transcriptId,None) is not None):
(begin,end)=transcriptBeginEnd[transcriptId]
transcript.setBegin(begin)
transcript.setEnd(end)
else:
transcript.setBegin(exonBegin)
transcript.setEnd(exonEnd)
transcript.geneId=geneId
gene=genes.get(geneId,None)
if(gene is None):
genes[geneId]=gene=Gene(); gene.setId(geneId)
transcript.setGene(gene)
exon=Exon(exonBegin,exonEnd,transcript)
exon.extraFields=extra
if(transcript.rawExons is not None):
exon.frame=frame
exon.score=exonScore
exon.type=fields[2]
transcript.rawExons.append(exon)
elif(not transcript.exonOverlapsExon(exon)):
exon.frame=frame
exon.score=exonScore
exon.type=fields[2]
transcript.UTR.append(exon) # OK -- we sort later
gene.addTranscript(transcript)
def loadGFF_exon(self,fields,line,transcriptBeginEnd,GFF,
transcripts,readOrder,genes):
exonBegin=int(fields[3])-1
exonEnd=int(fields[4])
exonScore=fields[5]
strand=fields[6]
frame=fields[7]
transcriptId=None
rex=Rex()
if(rex.find("transgrp[:=]\s*(\S+)",line)): transcriptId=rex[1]
elif(rex.find('transcript_id[:=]?\s*"?([^\s";]+)"?',line)):
transcriptId=rex[1]
elif(rex.find('Parent=([^;,\s]+)',line)): transcriptId=rex[1]
geneId=None
if(rex.find("genegrp=(\S+)",line)): geneId=rex[1]
elif(rex.find('gene_id[:=]?\s*"?([^\s\;"]+)"?',line)): geneId=rex[1]
if(transcriptId is None): transcriptId=geneId
if(geneId is None): geneId=transcriptId
if(rex.find("(\S+);$",transcriptId)): transcriptId=rex[1]
if(rex.find("(\S+);$",geneId)): geneId=rex[1]
extra=""
for i in range(8,len(fields)): extra+=fields[i]+" "
if(exonBegin>exonEnd): (exonBegin,exonEnd)=(exonEnd,exonBegin)
transcript=transcripts.get(transcriptId,None)
if(transcript is None):
transcripts[transcriptId]=transcript= \
Transcript(transcriptId,strand)
transcript.setStopCodons(self.stopCodons)
transcript.readOrder=readOrder
readOrder+=1
transcript.substrate=fields[0]
transcript.source=fields[1]
if(transcriptBeginEnd.get(transcriptId,None) is not None):
(begin,end)=transcriptBeginEnd[transcriptId]
transcript.setBegin(begin)
transcript.setEnd(end)
else:
transcript.setBegin(exonBegin)
transcript.setEnd(exonEnd)
transcript.geneId=geneId
gene=genes.get(geneId,None)
if(gene is None):
genes[geneId]=gene=Gene(); gene.setId(geneId)
transcript.setGene(gene)
exon=Exon(exonBegin,exonEnd,transcript)
exon.extraFields=extra
exon.score=exonScore
exon.type=fields[2]
if(transcript.rawExons is None): transcript.rawExons=[]
transcript.rawExons.append(exon)
gene.addTranscript(transcript)
def loadGFF_CDS(self,fields,line,transcriptBeginEnd,GFF,
transcripts,readOrder,genes):
exonBegin=int(fields[3])-1
exonEnd=int(fields[4])
exonScore=fields[5]
strand=fields[6]
frame=fields[7]
transcriptId=None
rex=Rex()
if(rex.find('transgrp[:=]\s*(\S+)',line)): transcriptId=rex[1]
elif(rex.find('transcript_id[:=]?\s*"?([^\s";]+)"?',line)):
transcriptId=rex[1]
elif(rex.find('Parent=([^;,\s]+)',line)): transcriptId=rex[1]
geneId=None
if(rex.find('genegrp=(\S+)',line)): geneId=rex[1]
elif(rex.find('gene_id[:=]?\s*"?([^\s\;"]+)"?',line)): geneId=rex[1]
if(transcriptId is None): transcriptId=geneId
if(geneId is None): geneId=transcriptId
if(transcriptId is None):
raise Exception(line+" : no transcript ID found")
if(rex.find('(\S+);$',transcriptId)): transcriptId=rex[1]
if(rex.find('(\S+);$',geneId)): geneId=rex[1]
extra=""
for i in range(8,len(fields)): extra+=fields[i]+" "
if(exonBegin>exonEnd): (exonBegin,exonEnd)=(exonEnd,exonBegin)
transcript=transcripts.get(transcriptId,None)
if(transcript is None):
transcripts[transcriptId]=transcript= \
Transcript(transcriptId,strand)
transcript.setStopCodons(self.stopCodons)
transcript.readOrder=readOrder
readOrder+=1
transcript.substrate=fields[0]
transcript.source=fields[1]
if(transcriptBeginEnd.get(transcriptId,None) is not None):
(begin,end)=transcriptBeginEnd[transcriptId]
transcript.setBegin(begin)
transcript.setEnd(end)
else:
transcript.setBegin(exonBegin)
transcript.setEnd(exonEnd)
transcript.geneId=geneId
gene=genes.get(geneId,None)
if(gene is None):
genes[geneId]=gene=Gene(); gene.setId(geneId)
transcript.setGene(gene)
exon=Exon(exonBegin,exonEnd,transcript)
exon.extraFields=extra
if(not transcript.exonOverlapsExon(exon)):
exon.frame=frame
exon.score=exonScore
exon.type=fields[2]
transcript.exons.append(exon) # OK -- we sort later
gene.addTranscript(transcript)
def loadGFF(self,gffFilename):
transcripts={}
genes={}
readOrder=Integer(1)
GFF=open(gffFilename,"r")
transcriptBeginEnd={}
while(True):
line=GFF.readline()
if(not line): break
if(not re.search("\S+",line)): continue
if(re.search("^\s*\#",line)): continue
fields=line.split("\t") ### \t added 3/24/2017
if(len(fields)<8): raise Exception("can't parse GTF:"+line)
if(fields[2]=="transcript" or fields[2]=="mRNA"):
self.loadGFF_transcript(fields,line,transcriptBeginEnd,GFF,
transcripts,readOrder,genes)
elif("UTR" in fields[2] or "utr" in fields[2]):
self.loadGFF_UTR(fields,line,transcriptBeginEnd,GFF,
transcripts,readOrder,genes)
elif(fields[2]=="exon"):
if(self.exonsAreCDS):
self.loadGFF_CDS(fields,line,transcriptBeginEnd,GFF,
transcripts,readOrder,genes)
else:
self.loadGFF_exon(fields,line,transcriptBeginEnd,GFF,
transcripts,readOrder,genes)
elif("CDS" in fields[2] or "-exon" in fields[2]):
self.loadGFF_CDS(fields,line,transcriptBeginEnd,GFF,
transcripts,readOrder,genes)
GFF.close()
transcripts=list(transcripts.values())
for transcript in transcripts: transcript.parseRawExons()
self.adjustStartCodons(transcripts)
self.computeFrames(transcripts);
if(self.shouldSortTranscripts):
transcripts.sort(key=lambda t: t.substrate+" "+str(t.begin)+" "+
str(t.end))
else:
transcripts.sort(key=lambda t: t.readOrder)
return transcripts