-
Notifications
You must be signed in to change notification settings - Fork 16
/
gbk_to_gff.py
216 lines (175 loc) · 6.89 KB
/
gbk_to_gff.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
#!/usr/bin/env python
"""
Convert data from Genbank format to GFF.
Usage:
python gbk_to_gff.py in.gbk > out.gff
Requirements:
BioPython:- http://biopython.org/
helper.py:- https://github.com/vipints/GFFtools-GX/blob/master/helper.py
Copyright (C)
2009-2012 Friedrich Miescher Laboratory of the Max Planck Society, Tubingen, Germany.
2012-2015 Memorial Sloan Kettering Cancer Center New York City, USA.
"""
import os
import re
import sys
import helper
import collections
from Bio import SeqIO
def feature_table(chr_id, source, orient, genes, transcripts, cds, exons, unk):
"""
Write the feature information
"""
for gname, ginfo in genes.items():
line = [str(chr_id),
'gbk2gff',
ginfo[3],
str(ginfo[0]),
str(ginfo[1]),
'.',
ginfo[2],
'.',
'ID=%s;Name=%s' % (str(gname), str(gname))]
sys.stdout.write('\t'.join(line)+"\n")
## construct the transcript line is not defined in the original file
t_line = [str(chr_id), 'gbk2gff', source, '0', '1', '.', ginfo[2], '.']
if not transcripts:
t_line.append('ID=Transcript:%s;Parent=%s' % (str(gname), str(gname)))
if exons: ## get the entire transcript region from the defined feature
t_line[3] = str(exons[gname][0][0])
t_line[4] = str(exons[gname][0][-1])
elif cds:
t_line[3] = str(cds[gname][0][0])
t_line[4] = str(cds[gname][0][-1])
if not cds:
t_line[2] = 'transcript'
else:
t_line[2] = 'mRNA'
sys.stdout.write('\t'.join(t_line)+"\n")
if exons:
exon_line_print(t_line, exons[gname], 'Transcript:'+str(gname), 'exon')
if cds:
exon_line_print(t_line, cds[gname], 'Transcript:'+str(gname), 'CDS')
if not exons:
exon_line_print(t_line, cds[gname], 'Transcript:'+str(gname), 'exon')
else: ## transcript is defined
for idx in transcripts[gname]:
t_line[2] = idx[3]
t_line[3] = str(idx[0])
t_line[4] = str(idx[1])
t_line.append('ID='+str(idx[2])+';Parent='+str(gname))
sys.stdout.write('\t'.join(t_line)+"\n")
## feature line print call
if exons:
exon_line_print(t_line, exons[gname], str(idx[2]), 'exon')
if cds:
exon_line_print(t_line, cds[gname], str(idx[2]), 'CDS')
if not exons:
exon_line_print(t_line, cds[gname], str(idx[2]), 'exon')
if len(genes) == 0: ## feature entry with fragment information
line = [str(chr_id), 'gbk2gff', source, 0, 1, '.', orient, '.']
fStart = fStop = None
for eid, ex in cds.items():
fStart = ex[0][0]
fStop = ex[0][-1]
for eid, ex in exons.items():
fStart = ex[0][0]
fStop = ex[0][-1]
if fStart or fStart:
line[2] = 'gene'
line[3] = str(fStart)
line[4] = str(fStop)
line.append('ID=Unknown_Gene_' + str(unk) + ';Name=Unknown_Gene_' + str(unk))
sys.stdout.write('\t'.join(line)+"\n")
if not cds:
line[2] = 'transcript'
else:
line[2] = 'mRNA'
line[8] = 'ID=Unknown_Transcript_' + str(unk) + ';Parent=Unknown_Gene_' + str(unk)
sys.stdout.write('\t'.join(line)+"\n")
if exons:
exon_line_print(line, cds[None], 'Unknown_Transcript_' + str(unk), 'exon')
if cds:
exon_line_print(line, cds[None], 'Unknown_Transcript_' + str(unk), 'CDS')
if not exons:
exon_line_print(line, cds[None], 'Unknown_Transcript_' + str(unk), 'exon')
unk +=1
return unk
def exon_line_print(temp_line, trx_exons, parent, ftype):
"""
Print the EXON feature line
"""
for ex in trx_exons:
temp_line[2] = ftype
temp_line[3] = str(ex[0])
temp_line[4] = str(ex[1])
temp_line[8] = 'Parent=%s' % parent
sys.stdout.write('\t'.join(temp_line)+"\n")
def gbk_parse(fname):
"""
Extract genome annotation recods from genbank format
@args fname: gbk file name
@type fname: str
"""
fhand = helper.open_file(gbkfname)
unk = 1
for record in SeqIO.parse(fhand, "genbank"):
gene_tags = dict()
tx_tags = collections.defaultdict(list)
exon = collections.defaultdict(list)
cds = collections.defaultdict(list)
mol_type, chr_id = None, None
for rec in record.features:
if rec.type == 'source':
try:
mol_type = rec.qualifiers['mol_type'][0]
except:
mol_type = '.'
pass
try:
chr_id = rec.qualifiers['chromosome'][0]
except:
chr_id = record.name
continue
strand='-'
strand='+' if rec.strand>0 else strand
fid = None
try:
fid = rec.qualifiers['gene'][0]
except:
pass
transcript_id = None
try:
transcript_id = rec.qualifiers['transcript_id'][0]
except:
pass
if re.search(r'gene', rec.type):
gene_tags[fid] = (rec.location._start.position+1,
rec.location._end.position,
strand,
rec.type
)
elif rec.type == 'exon':
exon[fid].append((rec.location._start.position+1,
rec.location._end.position))
elif rec.type=='CDS':
cds[fid].append((rec.location._start.position+1,
rec.location._end.position))
else:
# get all transcripts
if transcript_id:
tx_tags[fid].append((rec.location._start.position+1,
rec.location._end.position,
transcript_id,
rec.type))
# record extracted, generate feature table
unk = feature_table(chr_id, mol_type, strand, gene_tags, tx_tags, cds, exon, unk)
fhand.close()
if __name__=='__main__':
try:
gbkfname = sys.argv[1]
except:
print __doc__
sys.exit(-1)
## extract gbk records
gbk_parse(gbkfname)