forked from roryk/junkdrawer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgtfUtils.py
406 lines (345 loc) · 12.3 KB
/
gtfUtils.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
from sets import Set
import logging
def filterByMinLength(gtflines, size):
newlines = []
lengths = calculateLengths(gtflines)
total = 0
kept = 0
for line in gtflines:
total = total + 1
if 'transcript_id' not in line:
kept = kept + 1
newlines.append(line)
continue
if line['transcript_id'] not in lengths:
kept = kept + 1
newlines.append(line)
continue
if lengths[line['transcript_id']] < size:
continue
kept = kept + 1
newlines.append(line)
logging.info("%d out of %d lines had a size greater than " \
"%d." %(kept, total, size))
return newlines
def filterByMaxLength(gtflines, size):
newlines = []
lengths = calculateLengths(gtflines)
total = 0
kept = 0
for line in gtflines:
total = total + 1
if 'transcript_id' not in line:
kept = kept + 1
newlines.append(line)
continue
if line['transcript_id'] not in lengths:
kept = kept + 1
newlines.append(line)
continue
if lengths[line['transcript_id']] > size:
continue
kept = kept + 1
newlines.append(line)
logging.info("%d out of %d lines had a size less than " \
"%d." %(kept, total, size))
return newlines
def calculateLengths(gtflines):
"""
calculate the lengths of each transcript in the gtf file by
summing up the length of all the exons in the transcript
"""
lengths = {}
total_transcripts = 0
for line in gtflines:
if line['feature'] != "exon":
continue
size = abs(int(line['end']) - int(line['start'])) + 1
if 'transcript_id' not in line:
continue
if line['transcript_id'] not in lengths:
total_transcripts = total_transcripts + 1
lengths[line['transcript_id']] = size
else:
lengths[line['transcript_id']] = lengths[line['transcript_id']] + \
size
logging.info("Processed %d transcripts." %(total_transcripts))
return lengths
def outputLengths(lengths, outfn):
outfile = open(outfn, 'w')
written = 0
for l in lengths.iteritems():
written = written + 1
l = [str(x) for x in l]
outfile.write("\t".join(l) + "\n")
logging.info("Wrote %d lines to %s." %(written, outfn))
outfile.close()
def filterAttributes(gtflines, ffn):
ffile = open(ffn, 'r')
header = ffile.readline().strip()
filter_set = Set()
for line in ffile:
filter_set.add(line.strip())
newlines = []
for line in gtflines:
attrdict = attributeToDict(line)
if not (header in attrdict):
newlines.append(line)
continue
id = attrdict[header].replace("\"", "")
if id in filter_set:
newlines.append(line)
return newlines
def reorderAttributes(gtflines, order):
newlines = []
order = order.split(" ")
for line in gtflines:
attrdict = attributeToDict(line)
line['attribute'] = buildAttributeFieldFromDictWithOrder(attrdict,
order)
newlines.append(line)
return(newlines)
def addAttribute(gtflines, afn):
afile = open(afn, 'r')
header = afile.readline()
header = header.split("\t")
logging.info("Attaching %s to %s." %(header[1], header[0]))
linedict = {}
for line in afile:
line = line.split("\t")
linedict[line[0]] = line[1]
newlines = []
for line in gtflines:
attrdict = attributeToDict(line)
if not (header[0] in attrdict):
newlines.append(line)
continue
id = attrdict[header[0]].replace("\"", "")
attrdict[header[1].strip()] = "\"" + linedict[id].strip() + "\""
line['attribute'] = buildAttributeFieldFromDict(attrdict)
newlines.append(line)
return newlines
def swapAttributes(gtflines, source, replace):
newlines = []
repdict = dict(zip(replace, source))
for line in gtflines:
attrdict = attributeToDict(line)
newdict = attrdict.copy()
for r, s in repdict.items():
if s in attrdict:
newdict[r] = attrdict[s]
line[r] = attrdict[s]
line['attribute'] = buildAttributeFieldFromDict(newdict)
newlines.append(line)
return newlines
def delAttributes(gtflines, delete):
newlines = []
for line in gtflines:
attrdict = attributeToDict(line)
for x in delete:
if x in attrdict:
del attrdict[x]
if x in line:
del line[x]
line['attribute'] = buildAttributeFieldFromDict(attrdict)
newlines.append(line)
return newlines
def GTFtoDict(infn):
logging.info("Parsing the GTF file %s." %(infn))
gtflines = []
infile = open(infn, 'r')
numlines = 0
for line in infile:
numlines = numlines + 1
gtflines.append(parseGTFlineToDict(line))
logging.info("Processed %d lines in %s." %(numlines, infn))
infile.close()
return gtflines
def buildAttributeFieldFromDict(attrdict):
z = [x[0] + " " + x[1] for x in attrdict.items()]
return("; ".join(z) + "\n")
def buildAttributeFieldFromDictWithOrder(attrdict, order):
f = [0 for i in order]
e = []
for item in attrdict.items():
if item[0] in order:
f[order.index(item[0])] = item
else:
e.append(item)
f = [x for x in f if x != 0]
g = f + e
z = [x[0] + " " + x[1] for x in g]
return("; ".join(z) + "\n")
def attributeToDict(linedict):
attributes = linedict["attribute"].split(";")
attributes = filter(lambda x: x != "\n", attributes)
return dict([x.strip().split(" ") for x in attributes])
def addAttributesToGTFline(linedict):
attributes = linedict["attribute"].split(";")
del attributes[-1]
attributes = [x.strip() for x in attributes]
for attrib in attributes:
attr = attrib.strip().split(" ")
linedict[attr[0]] = attr[1].strip("\"")
return linedict
def parseGTFlineToDict(line):
values = line.split("\t")
keys = ["seqname", "source", "feature", "start", "end", "score",
"strand", "unknown", "attribute"]
linedict = dict(zip(keys, values))
linedict = addAttributesToGTFline(linedict)
return linedict
def outputGTF(gtflines, outfn):
logging.info("Writing GTF file.")
written = 0
outfile = open(outfn, 'w')
for line in gtflines:
outline = formatGTFLine(line)
outfile.write(outline)
written = written + 1
outfile.close()
logging.info("Wrote %d lines to %s." %(written, outfn))
def formatGTFLine(line):
outline = "\t".join([line['seqname'], line['source'],
line['feature'], line['start'],
line['end'], line['score'],
line['strand'], line['unknown'],
line['attribute']])
return outline
def outputGTFout(gtflines):
import sys
logging.info("Writing GTF file.")
written = 0
for line in gtflines:
outline = formatGTFLine(line)
sys.stdout.write(outline)
written = written + 1
logging.info("Wrote %d lines." %(written))
def aggregateFeaturesByTranscript(gtflines):
"""
aggregates a set of features by transcript_id
if transcript_id does not exist it deletes the line
sorts the features under a transcript by start site
adds a start-end tuple to each transcript indicating where
in the transcript each feature is (referenced to the mRNA, not
the genome)
"""
transcripts = {}
for line in gtflines:
if 'transcript_id' not in line:
continue
transcript_id = line['transcript_id']
if transcript_id not in transcripts:
transcripts[transcript_id] = [line]
else:
index = len(transcripts[transcript_id]) - 1
while (transcripts[transcript_id][index]['start'] >
line['start']):
index = index - 1
if index == -1:
break
transcripts[transcript_id].insert(index + 1, line)
return transcripts
def aggregateFeaturesByGene(gtflines):
genes = {}
for line in gtflines:
if 'gene_id' not in line:
continue
gene_id = line['gene_id']
if gene_id not in genes:
genes[gene_id] = [line]
else:
index = len(genes[gene_id]) - 1
while (genes[gene_id][index]['start'] >
line['start']):
index = index - 1
if index == -1:
break
genes[gene_id].insert(index + 1, line)
return genes
def mergeOverlappedExons(genes):
for gene in genes:
exons = []
for feature in genes[gene]:
if feature['feature'] != "exon":
continue
if exons == []:
exons.append(feature)
continue
for exon in reversed(exons):
# the new feature is the furthest along, so add it and go to
# the next feature
if (exon['end'] < feature['start']):
exons.append(feature)
break
# the old feature is contained in the new feature
if ((exon['start'] >= feature['start']) and
exon['end'] <= feature['end']):
exon['end'] = feature['end']
exon['start'] = feature['start']
# the new feature is contained in the old feature
# skip it
if ((exon['start'] <= feature['start']) and
(exon['end'] >= feature['end'])):
break
# the new feature overlaps with the old feature
# merge them together
if ((exon['start'] <= feature['start']) and
(exon['end'] <= feature['end'])):
exon['end'] = feature['end']
break
if ((exon['end'] >= feature['end']) and
(exon['start'] >= feature['start'])):
exon['start'] = feature['start']
break
genes[gene] = exons
return genes
def addFeatureCoordinatesToTranscripts(transcripts):
for trans_id in transcripts:
start = 0
for feature in transcripts[trans_id]:
length = int(feature['end']) - int(feature['start']) + 1
feature['fstart'] = start + 1
feature['fend'] = start + length
start = feature['fend']
return transcripts
def orderFeaturesByTranscript(gtflines):
"""
orders a set of features in each transcript by start site
transcripts are not ordered
"""
transcripts = aggregateFeaturesByTranscript(gtflines)
new_gtflines = []
for transcript in transcripts:
for feature in transcript:
new_gtflines.append(feature)
return new_gtflines
def orderTranscriptsByChromosome(transcripts):
"""
orders a set of transcripts by chromosome
"""
chromosomes = {}
for trans_id in transcripts.keys():
seqname = transcripts[trans_id][0]['seqname']
if seqname not in chromosomes:
chromosomes[seqname] = [trans_id]
else:
index = len(chromosomes[seqname]) - 1
ss = transcripts[chromosomes[seqname][index]][0]['start']
while(int(ss) > int(transcripts[trans_id][0]['start'])):
index = index - 1
if index == -1:
break
ss = transcripts[chromosomes[seqname][index]][0]['start']
chromosomes[seqname].insert(index + 1, trans_id)
return chromosomes
def unwindChromosomes(chromosomes, transcripts):
gtflines = []
chromosomelist = chromosomes.keys()
chromosomelist.sort()
for chromosome in chromosomelist:
transcript_list = chromosomes[chromosome]
for transcript_id in transcript_list:
for gtfline in transcripts[transcript_id]:
gtflines.append(gtfline)
return gtflines