/
parsers.py
384 lines (323 loc) · 11.7 KB
/
parsers.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
#!/usr/bin/env python
import csv
import sys
import numpy as np
import pandas as pd
from blast import remap_blast_coords_df as remap_blast
blast_cols = [('qseqid', str),
('sseqid', str),
('pident', float),
('length', int),
('mismatch', int),
('gapopen', int),
('qstart', int),
('qend', int),
('sstart', int),
('send', int),
('evalue', float),
('bitscore', float)]
hmmscan_cols = [('target_name', str),
('target_accession', str),
('tlen', int),
('query_name', str),
('query_accession', str),
('query_len', int),
('full_evalue', float),
('full_score', float),
('full_bias', float),
('domain_num', int),
('domain_total', int),
('domain_c_evalue', float),
('domain_i_evalue', float),
('domain_score', float),
('domain_bias', float),
('hmm_coord_from', int),
('hmm_coord_to', int),
('ali_coord_from', int),
('ali_coord_to', int),
('env_coord_from', int),
('env_coord_to', int),
('accuracy', float),
('description', str)]
cmscan_cols = [('target_name', str),
('target_accession', str),
('query_name', str),
('query_accession', str),
('mdl', str),
('mdl_from', int),
('mdl_to', int),
('seq_from', int),
('seq_to', int),
('strand', str),
('trunc', str),
('pass', str),
('gc', float),
('bias', float),
('score', float),
('e_value', float),
('inc', str),
('description', str)]
gff3_transdecoder_cols = [('seqid', str),
('feature_type', str),
('start', int),
('end', int),
('strand', str)]
crb_cols = [('query', str),
('subject', str),
('id', str),
('aln_len', int),
('evalue', float),
('bitscore', float),
('qrange', str),
('srange', str),
('qlen', int),
('slen', int)]
def convert_dtypes(df, dtypes):
'''Convert the columns of a DataFrame to the types specified
in the given dictionary, inplace.
Args:
df (DataFrame): The DataFrame to convert.
dtypes (dict): Dictionary mapping columns to types.
'''
for c in df.columns:
df[c] = df[c].astype(dtypes[c])
def blast_to_df_iter(fn, delimiter='\t', chunksize=10000, remap=False):
'''Iterator of DataFrames of length chunksize parsed from an
NCBI BLAST+ `-outfmt6` file.
Args:
fn (str): The results file.
chunksize (int): Hits per iteration.
Yields:
DataFrame: Pandas DataFrme with the BLAST+ hits.
'''
for group in pd.read_table(fn, header=None, skipinitialspace=True,
names=[k for k, _ in blast_cols],
delimiter=delimiter, chunksize=chunksize):
convert_dtypes(group, dict(blast_cols))
if remap:
remap_blast(group)
yield group
def crb_to_df_iter(fn, chunksize=10000, remap=False):
'''Iterator of DataFrames of length chunksize parsed from
the results from CRBB version crb-blast 0.6.6.
Args:
fn (str): The results file.
chunksize (int): Hits per iteration.
Yields:
DataFrame: Pandas DataFrame with the CRBB hits.
'''
for group in pd.read_table(fn, header=None, names=[k for k, _ in crb_cols],
delimiter='\t', chunksize=chunksize):
convert_dtypes(group, dict(crb_cols))
group['qstart'], _, group['qend'] = group.qrange.str.partition('..')
del group['qrange']
group['sstart'], _, group['send'] = group.srange.str.partition('..')
del group['srange']
if remap:
remap_blast(group)
yield group
def parse_busco(fn):
'''Parse a single BUSCO summary file to a dictionary.
Args:
fn (str): The results file.
Returns:
dict: The parsed results.
'''
res = {}
with open(fn) as fp:
for ln in fp:
if ln.strip().startswith('C:'):
tokens = ln.split(',')
for token in tokens:
key, _, val = token.partition(':')
key = key.strip()
val = val.strip().strip('%')
if key == 'C':
valc, _, vald = val.partition('%')
valc = valc.strip()
vald = vald.strip('D:][%')
res['C(%)'] = valc
res['D(%)'] = vald
else:
if key != 'n':
key += '(%)'
res[key] = val.strip().strip('%')
return res
def busco_to_df(fn_list, dbs=['metazoa', 'vertebrata']):
''' Given a list of BUSCO results from different databases, produce
an appropriately multi-indexed DataFrame of the results.
Args:
fn_list (list): The BUSCO summary files.
dbs (list): The BUSCO databases used for these runs.
Returns:
DataFrame: The BUSCO results.
'''
data = []
for fn in fn_list:
data.append(parse_busco(fn))
df = pd.DataFrame(data)
df['fn'] = [os.path.basename(fn)[14:-14].strip('.') for fn in fn_list]
df['db'] = None
for db in dbs:
idx = df.fn.str.contains(db)
df.loc[idx,'db'] = db
df.loc[idx,'fn'] = df.loc[idx, 'fn'].apply(lambda fn: fn[:fn.find(db)].strip('. '))
return df
def hmmscan_to_df_iter(fn, chunksize=10000):
'''Iterator over DataFrames of length chunksize from a given
hmmscan result file.
Args:
fn (str): Path to the hmmscan file.
chunksize (int): Hits per iteration.
Yields:
DataFrame: Pandas DataFrame with the hmmscan hits.
'''
def split_query(item):
q, _, _ = item.rpartition('|')
return q
def build_df(data):
df = pd.DataFrame(data, columns=[k for k, _ in hmmscan_cols])
convert_dtypes(df, dict(hmmscan_cols))
df['full_query_name'] = df.query_name
df['query_name'] = df.query_name.apply(split_query)
return df
data = []
with open(fn) as fp:
for n, ln in enumerate(fp):
if not ln or ln.startswith('#'):
continue
tokens = ln.split()
data.append(tokens[:len(hmmscan_cols)-1] + \
[' '.join(tokens[len(hmmscan_cols)-1:])])
if len(data) >= chunksize:
yield build_df(data)
data = []
if data:
yield build_df(data)
def cmscan_to_df_iter(fn, chunksize=10000):
'''Iterator over DataFrames of length chunksize from a given
cmscan result file.
Args:
fn (str): Path to the cmscan file.
chunksize (int): Hits per iteration.
Yields:
DataFrame: Pandas DataFrame with the cmscan hits.
'''
def build_df(data):
df = pd.DataFrame(data, columns=[k for k, _ in cmscan_cols])
convert_dtypes(df, dict(cmscan_cols))
return df
data = []
with open(fn) as fp:
for ln in fp:
ln = ln.strip()
if not ln or ln.startswith('#'):
continue
tokens = ln.split()
data.append(tokens[:len(cmscan_cols)-1] + \
[' '.join(tokens[len(cmscan_cols)-1:])])
if len(data) >= chunksize:
yield build_df(data)
data = []
if data:
yield build_df(data)
def gff3_transdecoder_to_df_iter(fn, chunksize=10000):
'''Iterator yeilding DataFrames of length chunksize
from a given TransDecoder GFF file.
Args:
fn (str): Path to the TransDecoder gff file.
chunksize (int): Rows per iteration.
Yields:
DataFrame: Pandas DataFrame with the predict gene features.
'''
def build_df(data):
df = pd.DataFrame(data, columns=[k for k, _ in gff3_transdecoder_cols])
convert_dtype(df, dict(gff3_transdecoder_cols))
return df
data = []
with open(fn) as fp:
for ln in fp:
if ln == '\n':
continue
tokens = ln.split('\t')
try:
data.append([tokens[0]] + tokens[2:5] + [tokens[6]])
except IndexError as e:
print e
print tokens
break
if len(data) >= chunksize:
yield build_df(data)
data = []
if data:
yield build_df(data)
def maf_to_df_iter(fn, chunksize=10000):
'''Iterator yielding DataFrames of length chunksize holding MAF alignments.
An extra column is added for bitscore, using the equation described here:
http://last.cbrc.jp/doc/last-evalues.html
Args:
fn (str): Path to the MAF alignment file.
chunksize (int): Alignments to parse per iteration.
Yields:
DataFrame: Pandas DataFrame with the alignments.
'''
def fix_sname(name):
new, _, _ = name.partition(',')
return new
def build_df(data, LAMBDA, K):
df = pd.DataFrame(data)
df['s_name'] = df['s_name'].apply(fix_sname)
setattr(df, 'LAMBDA', LAMBDA)
setattr(df, 'K', K)
df['bitscore'] = (LAMBDA * df['score'] - np.log(K)) / np.log(2)
return df
data = []
LAMBDA = None
K = None
with open(fn) as fp:
while (True):
try:
line = fp.next().strip()
except StopIteration:
break
if not line:
continue
if line.startswith('#'):
if 'lambda' in line:
meta = line.strip(' #').split()
meta = {k:v for k, _, v in map(lambda x: x.partition('='), meta)}
LAMBDA = float(meta['lambda'])
K = float(meta['K'])
else:
continue
if line.startswith('a'):
cur_aln = {}
# Alignment info
tokens = line.split()
for token in tokens[1:]:
key, _, val = token.strip().partition('=')
cur_aln[key] = float(val)
# First sequence info
line = fp.next()
tokens = line.split()
cur_aln['s_name'] = tokens[1]
cur_aln['s_start'] = int(tokens[2])
cur_aln['s_aln_len'] = int(tokens[3])
cur_aln['s_strand'] = tokens[4]
cur_aln['s_len'] = int(tokens[5])
# First sequence info
line = fp.next()
tokens = line.split()
cur_aln['q_name'] = tokens[1]
cur_aln['q_start'] = int(tokens[2])
cur_aln['q_aln_len'] = int(tokens[3])
cur_aln['q_strand'] = tokens[4]
cur_aln['q_len'] = int(tokens[5])
data.append(cur_aln)
if len(data) >= chunksize:
if LAMBDA is None:
raise Exception("old version of lastal; please update")
yield build_df(data, LAMBDA, K)
data = []
if data:
yield build_df(data, LAMBDA, K)