forked from djhn75/RNAEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Genome.py
executable file
·324 lines (252 loc) · 13 KB
/
Genome.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
'''
Created on 11.06.2014
@author: david
'''
'''
classdocs
'''
#from __builtin__ import SyntaxError
from array import array
from collections import defaultdict
import gzip
#from itertools import izip
from operator import attrgetter
from Gene import Gene
from Helper import Helper
from Transcript import Transcript
import gtfHandler
class Genome(object):
def __init__(self,gtfFile,logFile=None,textField=0):
'''
Constructor
'''
self.logFile=logFile
self.textField =textField
startTime = Helper.getTime()
Helper.info(" [%s] Assembling Genome from %s" % (startTime.strftime("%c"),gtfFile),self.logFile,self.textField)
#Dict / List for all Genes
self.geneList = []
self.genesByChromosome = defaultdict(list)
# list of all features
self.featureTypes = set() #set of all possible featuresTypes
self.geneTypes = set() #set of all possible geneTypes (sources)
# gene_id -> (gene_name,contig,strand)
self.uniqGeneSet = set()
self.uniqGene_to_source = dict()
self.uniqGene_to_names = defaultdict(set)
self.uniqGene_to_transcriptIds = defaultdict(set)
# transcriptId
self.transcriptId_to_names = defaultdict(set)
self.transcriptId_to_protId = dict()
self.transcriptId_to_startCodons = defaultdict(tuple)
self.transcriptId_to_stopCodons = defaultdict(tuple)
self.transcriptId_to_exons = defaultdict(set)
self.transcriptId_to_cds = defaultdict(set)
self.transcriptId_to_codingFrames= defaultdict(set)
self.transcriptIds = defaultdict(set)
#this fills also the dictionary self.geneByChromosome
self.createTranscriptomeFromFile(gtfFile)
self.genesByChromosome = self.getGenesByChromosome()
Helper.printTimeDiff(startTime,self.logFile,self.textField)
def parseGtf(self,gtfFile):
"""
fill the dictionarys with the correspending attributes
"""
try:
for lineNumber, f in enumerate(gtfHandler.iterator(gtfFile)):
uniqGene = f.geneId, f.chr, f.strand #(ENSG,chr,strand)
interval = (f.start, f.end)
exonNumber = int(f.attributes["exon_number"]) - 1
self.featureTypes.add(f.featureType)
if "transcript_name" in f.attributes:
self.transcriptId_to_names[f.transcriptId].add(f.attributes["transcript_name"])
if "gene_name" in f.attributes:
self.uniqGene_to_names[uniqGene].add(f.attributes["gene_name"])
self.uniqGeneSet.add(uniqGene)
self.uniqGene_to_source[uniqGene] = f.source
self.geneTypes.add(f.source)
self.uniqGene_to_transcriptIds[uniqGene].add(f.transcriptId)
#react for different feature types
if f.featureType == "exon":
self.transcriptId_to_exons[f.transcriptId].add(interval)
elif f.featureType == "CDS":
proteinId = f.attributes["protein_id"]
if (uniqGene in self.transcriptId_to_protId and self.transcriptId_to_protId[uniqGene] != proteinId):
Helper.warning("Transcript [%s] has many Protein IDs" % uniqGene)
self.transcriptId_to_protId[f.transcriptId] = proteinId
self.transcriptId_to_codingFrames[f.transcriptId].add((exonNumber, f.frame))
self.transcriptId_to_cds[f.transcriptId].add(interval)
elif f.featureType == "start_codon":
self.transcriptId_to_startCodons[f.transcriptId] += (exonNumber, interval),
elif f.featureType == "stop_codon":
self.transcriptId_to_stopCodons[f.transcriptId] += (exonNumber, interval),
except:
raise SyntaxError("In line %s with Gene %s! Check your gtf file" % lineNumber,f.geneId)
def assembleTranscriptome(self):
'''
Loop over uniqueGeneSet, in which the ENSG-IDs are saved,
and assemble all the transcripts and exons for this gene and save it as a Gene object.
This gene obeject ist then added to the geneList of this Genome object
'''
#transcriptsByType = defaultdict(list)
#construct Genes
for uniqGene in self.uniqGeneSet:
geneId, chromosome, strand = uniqGene
geneNames = list(self.uniqGene_to_names[uniqGene])
geneType = self.uniqGene_to_source[uniqGene]
geneExons = set()
geneCds = set()
#get exons from all transcripts
for transcriptId in self.uniqGene_to_transcriptIds[uniqGene]:
geneExons |= self.transcriptId_to_exons[transcriptId] # add new exon tuples to geneExons set
geneCds |= self.transcriptId_to_cds[transcriptId]
#usually gtf Files are sorted, but this can't be assumed
geneExons = sorted(geneExons, reverse = not strand)
geneCds = sorted(geneCds, reverse = not strand)
gene = Gene(geneId, chromosome, strand, geneType, geneNames, geneExons, geneCds)
geneExons = dict(zip(geneExons,xrange(1000000)))
geneCds = dict(zip(geneCds,xrange(1000000)))
self.geneList.append(gene)
#construct transcripts
for transcriptId in self.uniqGene_to_transcriptIds[uniqGene]:
transcriptNames = self.transcriptId_to_names[transcriptId]
protId = self.transcriptId_to_protId[transcriptId] if transcriptId in self.transcriptId_to_protId else None
exons = sorted(self.transcriptId_to_exons[transcriptId])
codingExons = sorted(self.transcriptId_to_cds[transcriptId])
exonIndices = array('H', [geneExons[e] for e in exons])
codingExonIndices = array('H', [geneCds[e] for e in codingExons])
codingFrames = array('H', [int(frame) for exonNumber, frame in sorted(self.transcriptId_to_codingFrames[transcriptId])])
startCodon = tuple([interval for exonNumber, interval in sorted(self.transcriptId_to_startCodons[transcriptId])])
stopCodon = tuple([interval for exonNumber, interval in sorted(self.transcriptId_to_stopCodons[transcriptId])])
if len(codingExons) != len(codingFrames):
raise Exception("Number of coding Exons and Frames differ for %s %s" % geneId, transcriptId)
transcript = Transcript(gene, transcriptId,list(transcriptNames), protId, exonIndices, codingExonIndices, codingFrames, startCodon, stopCodon)
gene.addTranscript(transcript)
def createTranscriptomeFromFile(self,gtfFilePath):
"""
Construct Genome from GTF File
Saves all the information in dictionarys
This function calls internally:
-parseGTF
-assembleTranscriptome
Returns a list with all the genes for each chromosome in a dictionary
return: genesByChromosome
"""
#startTime = Helper.getTime()
#Helper.info(" [%s] Parsing Gene Data from %s" % (startTime.strftime("%c"),gtfFilePath))
#check fileType of Genome File
if gtfFilePath.endswith(".gz"):
gtfFile = gzip.open(gtfFilePath)
else:
gtfFile = open(gtfFilePath)
#parse GTF file
self.parseGtf(gtfFile)
self.assembleTranscriptome()
#duration = Helper.getTime() -startTime
#Helper.info(" Finished parsing in %s" % (str(duration)))
del self.featureTypes
del self.geneTypes
#delete unneccesarry variables
del self.uniqGeneSet
del self.uniqGene_to_source
del self.uniqGene_to_names
del self.uniqGene_to_transcriptIds
#
# transcriptId
#
del self.transcriptId_to_names
del self.transcriptId_to_protId
del self.transcriptId_to_startCodons
del self.transcriptId_to_stopCodons
del self.transcriptId_to_exons
del self.transcriptId_to_cds
del self.transcriptId_to_codingFrames
del self.transcriptIds
def getGenesByChromosome(self):
"""
Returns a dictionary with chromosomes as key and all the genes on the chromosome as values
The genes are also sorted
{"1":[Gene1,Gene2....]}
"""
genesByChr = defaultdict(list)
if len(self.geneList) == 0:
raise Exception("Gene List is empty")
else:
for gene in self.geneList:
genesByChr[gene.chromosome].append(gene)
#sort genes by by start and end
for key in genesByChr.keys():
genesByChr[key] = sorted(genesByChr[key], key=attrgetter('start','end'))
return genesByChr
def getGenesByGeneID(self):
"""
Returns a dictionary with geneID (ENSG000001) as key and the gene object as value
{"ENSG000001":GeneObject;"ENSG000002":GeneObject2}
"""
genesByGeneID = defaultdict()
for gene in self.geneList:
genesByGeneID[gene.geneId]=gene
return genesByGeneID
def annotateRegion(self,chromosome,start,stop):
"""
returns information for the given region like (3'UTR,Exon,Intron,5'UTR)
Gene ......|---------gene1-----------|...................|-----gene2------|...
pos1 ...|----pos1----|......................................
pos2 ................|---pos2----|..........................
pos3 ..........................|-------pos3----|............
pos4 ..|------------------------pos4---------------|........
pos5 |pos5|..................................................
pos6...|----------------------------------------pos6-------------------------|.....
"""
for gene in self.genesByChromosome[chromosome]:
segment=set()
if start < gene.start < stop and stop < gene.end:
#case 1
pass
#TODO: write this function like annotate position
def annotatePosition(self,chromosome, position):
'''
returns the gene and information for the given position like (3'UTR,Exon,Intron,5'UTR)
:param chromosome: String
:param position: Int
:return list of Tuples List[(gene,segment1;segment2..)...]
'''
result=[]
#Loop over the genes of the chromosome
for gene in self.genesByChromosome[chromosome]:
#check if the position is in the current gene
#geneName=None
segment = set()
if gene.start < position < gene.end:
#geneName=gene.names[0]
if len(gene.codingExons)>0:
#check if position is in front of first coding exon
if (gene.strand and position < gene.codingExons[0][0]) or (not gene.strand and position > gene.codingExons[0][1]):
for exon in gene.exons:
if exon[0]<position<exon[1]:
segment.add("5'UTR")
#continue
#check if position is behind the last coding exon
elif (gene.strand and position > gene.codingExons[-1][1]) or not gene.strand and position < gene.codingExons[-1][0] :
for exon in gene.exons:
if exon[0]<position<exon[1]:
segment.add("3'UTR")
#continue
for cds in gene.codingExons:
if cds[0] < position < cds[1]:
segment.add("coding-exon")
#continue
else:
for exon in gene.exons:
if exon[0] < position < exon[1]:
segment.add("noncoding-exon")
#continue
if len(segment)==0:
segment.add("intron")
result.append((gene,tuple(segment)))
#if len(segment)>=2:
# print(chromosome,gene.geneId,int(position),segment)
if result == []:
result.append(("-",tuple(["intergenic"])))
#return geneName, segment
return result