-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcheck_cds.py
More file actions
executable file
·304 lines (275 loc) · 9.17 KB
/
check_cds.py
File metadata and controls
executable file
·304 lines (275 loc) · 9.17 KB
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
#!/usr/bin/python
import sys
import os
import getopt
import urllib.parse
def main():
params = parseArgs()
if params.gff:
total_genes=0
blacklist=list()
current_gene=None
current_sum=0
gene_sums=dict()
if params.correct:
print("WARNING: You have chosen to force non-conforming CDS to be divisible by 3. Note that this assumes CDS records are sorted")
if params.remove:
print("WARNING: Removing all non-conforming CDS from output file")
for r in read_gff(params.gff):
if r.type == "CDS":
if params.gffid in r.attributes:
name=r.attributes[params.gffid]
if not current_gene:
current_gene=name
current_sum += (r.end-r.start)+1
elif current_gene == name:
current_sum += (r.end-r.start)+1
else:
#gene is done
if current_sum%3 != 0:
blacklist.append(current_gene)
gene_sums[current_gene]=current_sum
current_gene=name
current_sum=0
total_genes+=1
else:
print("ERROR: Given ID not present in GFF attributed field.")
sys.exit()
if current_sum>0:
if current_sum%3 != 0:
blacklist.append(current_gene)
gene_sums[current_gene]=current_sum
current_gene=name
current_sum=0
total_genes+=1
if len(blacklist)>0:
print("Found", str(len(blacklist)), "of", str(total_genes),"genes not divisible by 3:")
for g in blacklist:
print(g)
if params.out:
print("Writing new output GFF (CDS records only):",params.out)
with open(params.out, 'w') as fh:
last_line=None
current_gene=None
if len(blacklist)>0:
lookup = dict(zip(blacklist, blacklist))
for r in read_gff(params.gff):
if params.gffid in r.attributes:
name=r.attributes[params.gffid]
if r.type != "CDS":
if params.printAll:
if params.remove:
if name not in blacklist:
fh.write(r.as_string())
fh.write("\n")
else:
fh.write(r.as_string())
fh.write("\n")
else:
#if continuing gene, check if blacklisted
if not current_gene:
current_gene=name
if current_gene == name:
#print(name)
if name in blacklist:
#print("bad")
#skip if params.remove
if params.correct:
if last_line:
fh.write(last_line)
fh.write("\n")
last_line=r.as_string()
last_line=r.as_string()
else:
fh.write(r.as_string())
fh.write("\n")
else:
if current_gene in blacklist:
#print(name)
#print("bad")
if params.correct:
#print("correcting",current_gene)
if last_line:
#print("last_line:")
#print(last_line)
corrected=GFFRecord(last_line.split("\t"))
#print(corrected.as_string())
#print("GENE: ", corrected.attributes[params.gffid])
#print("GENE SUM: ",gene_sums[corrected.attributes[params.gffid]])
#print("DIFFERENCE:", gene_sums[corrected.attributes[params.gffid]]%3)
diff=gene_sums[corrected.attributes[params.gffid]]%3
corrected.end-=diff
#print(corrected.as_string())
fh.write(r.as_string())
fh.write("\n")
current_gene=name
if current_gene in blacklist:
#print(name)
#print("bad")
if params.correct:
#print("correcting",current_gene)
if last_line:
#print("last_line:")
#print(last_line)
corrected=GFFRecord(last_line.split("\t"))
#print(corrected.as_string())
#print("GENE: ", corrected.attributes[params.gffid])
#print("GENE SUM: ",gene_sums[corrected.attributes[params.gffid]])
#print("DIFFERENCE:", gene_sums[corrected.attributes[params.gffid]]%3)
diff=gene_sums[corrected.attributes[params.gffid]]%3
corrected.end-=diff
#print(corrected.as_string())
fh.write(r.as_string())
fh.write("\n")
else:
print("All",str(total_genes),"genes passed.")
#Function to split GFF attributes
def splitAttributes(a):
ret = {}
for thing in a.split(";"):
stuff = thing.split("=")
if len(stuff) != 2: continue #Eats error silently, YOLO
key = stuff[0]
value = stuff[1]
ret[key] = value
return ret
#Class for holding GFF Record data, no __slots__
class GFFRecord():
def __init__(self, things):
self.seqid = "." if things[0] == "." else urllib.parse.unquote(things[0])
self.source = "." if things[1] == "." else urllib.parse.unquote(things[1])
self.type = "." if things[2] == "." else urllib.parse.unquote(things[2])
self.start = "." if things[3] == "." else int(things[3])
self.end = "." if things[4] == "." else int(things[4])
self.score = "." if things[5] == "." else float(things[5])
self.strand = "." if things[6] == "." else urllib.parse.unquote(things[6])
self.phase = "." if things[7] == "." else urllib.parse.unquote(things[7])
self.attributes = {}
if things[8] != "." and things[8] != "":
self.attributes = splitAttributes(urllib.parse.unquote(things[8]))
def getAlias(self):
"""Returns value of alias if exists, and False if it doesn't exist"""
if 'alias' in self.attributes:
return self.attributes['alias']
else:
return False
def as_string(self):
record=str(self.seqid) + "\t" + str(self.source) + "\t" + str(self.type)
record=record + "\t" + str(self.start) + "\t" + str(self.end) + "\t" + str(self.score)
record=record + "\t" + str(self.strand) + "\t" + str(self.phase) + "\t"
first=True
for key in self.attributes.keys():
if first:
record=record + str(key) + "=" + str(self.attributes[key])
first=False
else:
record=record + ";" + str(key) + "=" + str(self.attributes[key])
return(record)
#file format:
#1 per line:
#chr1:1-1000
#...
def read_regions(r):
with open(r, 'w') as fh:
try:
for line in fh:
line = line.strip() #strip leading/trailing whitespace
if not line: #skip empty lines
continue
yield(ChromRegion(line))
finally:
fh.close()
#function to read a GFF file
#Generator function, yields individual elements
def read_gff(g):
bad = 0 #tracker for if we have bad lines
gf = open(g)
try:
with gf as file_object:
for line in file_object:
if line.startswith("#"): continue
line = line.strip() #strip leading/trailing whitespace
if not line: #skip empty lines
continue
things = line.split("\t") #split lines
if len(things) != 9:
if bad == 0:
print("Warning: GFF file does not appear to be standard-compatible. See https://github.com/The-Sequence-Ontology/Specifications/blob/master/gff3.md")
bad = 1
continue
elif bad == 1:
sys.exit("Fatal error: GFF file does not appear to be standard-compatible. See https://github.com/The-Sequence-Ontology/Specifications/blob/master/gff3.md")
#line = utils.removeURL(line) #Sanitize any URLs out
rec = GFFRecord(things)
yield(rec)
finally:
gf.close()
#Object to parse command-line arguments
class parseArgs():
def __init__(self):
#Define options
try:
options, remainder = getopt.getopt(sys.argv[1:], 'hg:o:i:prc', \
["help", "gff=", "out=", "printAll", "remove", "id=", "correct"])
except getopt.GetoptError as err:
print(err)
self.display_help("\nExiting because getopt returned non-zero exit status.")
#Default values for params
#Input params
self.gff=None
self.out=None
self.gffid="protein_id"
self.remove=False
self.correct=False
self.printAll=False
#First pass to see if help menu was called
for o, a in options:
if o in ("-h", "-help", "--help"):
self.display_help("Exiting because help menu was called.")
#Second pass to set all args.
for opt, arg_raw in options:
arg = arg_raw.replace(" ","")
arg = arg.strip()
opt = opt.replace("-","")
#print(opt,arg)
if opt == "h" or opt == "help":
continue
elif opt=="gff" or opt=="g":
self.gff=arg
elif opt=="o" or opt=="out":
self.out=arg
elif opt=="p" or opt=="printAll":
self.printAll=True
elif opt=="i" or opt=="id":
self.gffid=arg
elif opt=="c" or opt=="correct":
self.correct=True
else:
assert False, "Unhandled option %r"%opt
#Check manditory options are set
if not self.gff:
self.display_help("Must provide a GFF file")
if not self.correct:
self.remove=True
if self.correct and not self.out:
self.display_help("Cannot use --correct without -o/--out")
def display_help(self, message=None):
if message is not None:
print()
print (message)
print ("\ncheck_cds.py\n")
print("Author: Tyler K Chafin, University of Arkansas")
print ("Contact: tkchafin@uark.edu")
print ("Description: Checks that the sum of CDS blocks for a gene is divisible by 3")
print("""
-g,--gff : GFF File (may contain non-CDS regions but these will be skipped)
-o,--out : Output file for new CDS (default=None)
-c,--correct : Walk back end coordinate for genes not summing to %3 (only relevant if --out)
-i,--id : Field in GFF attributes (last column) giving the identifier to use
-p,--printAll: Print all fields (not just CDS)(only relevant if --out)
""")
print()
sys.exit()
#Call main function
if __name__ == '__main__':
main()