File: _sequence_feature_vocabulary.py

package info (click to toggle)
python-skbio 0.5.1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 16,556 kB
  • ctags: 7,222
  • sloc: python: 42,085; ansic: 670; makefile: 180; sh: 10
file content (351 lines) | stat: -rw-r--r-- 10,702 bytes parent folder | download | duplicates (2)
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
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------

import re

from skbio.metadata import IntervalMetadata
from skbio.io.format._base import _line_generator
from skbio.io import FileFormatError


def _vocabulary_change(format='insdc', read_in=True):
    '''Return a dict that converts between memory and output vocabulary.'''
    convert = {'phase': {'insdc': 'codon_start'},
               'source': {'insdc': 'inference'},
               'db_xref': {'gff3': 'Dbxref'},
               'note': {'gff3': 'Note'}}
    if read_in:
        return {v[format]: k for k, v in convert.items() if format in v}
    else:
        return {k: v[format] for k, v in convert.items() if format in v}


def _vocabulary_skip(format='insdc'):
    '''Return a list of vocabularies that should be skipped when auto
    output to disk for the specified format.

    '''
    skip = {'type': ('insdc', 'gff3'),
            'ID': ('insdc'),
            'translation': ('gff3'),
            'strand': ('insdc')}
    return [k for k, v in skip.items() if format in v]


def _yield_section(is_another_section, **kwargs):
    '''Returns function that returns successive sections from file.

    Parameters
    ----------
    is_another_section : callable
        It takes a string as input and return a boolean indicating
        a new section starts.
    kwargs : dict, optional
        Keyword arguments will be passed to `_line_generator`.

    Returns
    -------
    function
        A function accept a list of lines as input and return
        a generator to yield section one by one.
    '''
    def parser(lines):
        curr = []
        for line in _line_generator(lines, **kwargs):
            # if we find another, return the previous section
            if is_another_section(line):
                if curr:
                    yield curr
                    curr = []
            curr.append(line)
        # don't forget to return the last section in the file
        if curr:
            yield curr
    return parser


def _parse_section_default(
        lines, label_delimiter=None, join_delimiter=' ', return_label=False):
    '''Parse sections in default way.

    Do 2 things:
        1. split first line with label_delimiter for label
        2. join all the lines into one str with join_delimiter.
    '''
    data = []
    label = None
    line = lines[0]

    items = line.split(label_delimiter, 1)

    if len(items) == 2:
        label, section = items
    else:
        label = items[0]
        section = ""
    data.append(section)

    data.extend(lines[1:])
    data = join_delimiter.join(i.strip() for i in data)
    if return_label:
        return label, data
    else:
        return data


def _serialize_section_default(header, obj, indent=12):
    return '{header:<{indent}}{obj}\n'.format(
        header=header, obj=obj, indent=indent)


def _parse_feature_table(lines, length):
    '''parse DDBJ/ENA/GenBank Feature Table.'''
    imd = IntervalMetadata(length)
    # skip the 1st FEATURES line
    if lines[0].startswith('FEATURES'):
        lines = lines[1:]
    # magic number 21: the lines following header of each feature
    # are indented with 21 spaces.
    feature_indent = ' ' * 21
    section_splitter = _yield_section(
        lambda x: not x.startswith(feature_indent),
        skip_blanks=True, strip=False)

    for section in section_splitter(lines):
        _parse_single_feature(section, imd)
    return imd


def _parse_single_feature(lines, imd):
    '''Parse a feature.

    Parse a feature and add it to ``IntervalMetadata`` object.

    Parameters
    ----------
    imd : IntervalMetadata
    '''
    voca_change = _vocabulary_change('insdc')

    # each component of a feature starts with '/', except the 1st
    # component of location.
    section_splitter = _yield_section(
        lambda x: x.startswith('/'), strip=True)
    section_iter = section_splitter(lines)

    # 1st section is location
    section = next(section_iter)
    feature_type, feature_loc = _parse_section_default(
        section, join_delimiter='', return_label=True)

    metadata = {'type': feature_type, '__location': feature_loc}

    intvl = imd.add(*_parse_loc_str(feature_loc))

    for section in section_iter:
        # following sections are Qualifiers
        k, v = _parse_section_default(
            section, label_delimiter='=',
            join_delimiter=' ', return_label=True)
        # 1st char is '/'
        k = k[1:]
        if k in voca_change:
            k = voca_change[k]

        if k == 'phase':
            v = int(v) - 1

        # some Qualifiers can appear multiple times
        if k in metadata:
            if not isinstance(metadata[k], list):
                metadata[k] = [metadata[k]]
            metadata[k].append(v)
        else:
            metadata[k] = v

    intvl.metadata.update(metadata)


def _parse_loc_str(loc_str):
    '''Parse location string.

    .. warning: This converts coordinates to 0-based from 1-based
    GenBank coordinate system.

    The location descriptor can be one of the following [1]_:
    (a) a single base number. e.g. 467
    (b) a site between two indicated adjoining bases. e.g. 123^124
    (c) a single base chosen from within a specified range of bases (not
        allowed for new entries). e.g. 102.110
    (d) the base numbers delimiting a sequence span. e.g.340..565
    (e) a remote entry identifier followed by a local location
        descriptor (i.e., a-d). e.g. J00194.1:100..202

    Notes
    -----
    This does not fully handle (e) case. It will discard the remote
    entry part and only keep the local part. When it parses locations
    across strand (e.g. "complement(123..145),200..209"), it will
    record all the span parts but will record strand as negative.

    References
    ----------
    .. [1] http://www.insdc.org/files/feature_table.html#3.4

    '''
    # define the tokens
    operators = ['join', 'complement', 'order']
    LPAREN = r'(?P<LPAREN>\()'
    RPAREN = r'(?P<RPAREN>\))'
    COMMA = r'(?P<COMMA>,)'
    WS = r'(?P<WS>\s+)'
    a = r'(?P<A>\d+)'
    b = r'(?P<B>\d+\^\d+)'
    c = r'(?P<C>\d+\.\d+)'
    d = r'(?P<D><?\d+\.\.>?\d+)'
    e_left = r'(?P<EL><?[a-zA-Z_0-9\.]+:\d+\.\.>?\d+)'
    e_right = r'(?P<ER><?\d+\.\.>?[a-zA-Z_0-9\.]+:\d+)'
    illegal = r'(?P<ILLEGAL>.+)'
    # The order of tokens in the master regular expression also
    # matters. When matching, re tries to match pattens in the order
    # specified. Thus, if a pattern happens to be a substring of a
    # longer pattern, you need to make sure the longer pattern goes
    # first.
    master_pat = re.compile('|'.join(
        operators + [WS, LPAREN, RPAREN, COMMA,
                     b, c, d, e_left, e_right, a,
                     illegal]))

    scanner = master_pat.scanner(loc_str)

    bounds = []
    fuzzy = []

    metadata = {'strand': '+'}

    for m in iter(scanner.match, None):
        p, v = m.lastgroup, m.group()
        if v == 'complement':
            metadata['strand'] = '-'
        elif p == 'A':
            start = int(v)
            bounds.append((start-1, start))
            fuzzy.append((False, False))
        elif p == 'B':
            start, end = v.split('^')
            start = int(start)
            bounds.append((start-1, start))
            fuzzy.append((False, False))
        elif p == 'C' or p == 'D':
            if p == 'C':
                start, end = v.split('.')
            else:
                start, end = v.split('..')
            fuzzy_s = fuzzy_e = False
            if start.startswith('<'):
                start = start[1:]
                fuzzy_s = True
            if end.startswith('>'):
                end = end[1:]
                fuzzy_e = True
            bounds.append((int(start)-1, int(end)))
            fuzzy.append((fuzzy_s, fuzzy_e))
        elif p == 'ILLEGAL':
            raise FileFormatError(
                'Could not parse location string: "%s"' % loc_str)

    return bounds, fuzzy, metadata


def _serialize_feature_table(intervals, indent=21):
    '''
    Parameters
    ----------
    intervals : list of ``Interval``
    '''
    for intvl in intervals:
        yield _serialize_single_feature(intvl, indent)


def _serialize_single_feature(intvl, indent=21):
    '''
    Parameters
    ----------
    intvl : Interval
    '''
    # there are 5 spaces before Feature Key starts.
    padding = ' ' * 5
    qualifiers = []
    md = intvl.metadata
    voca_skip = _vocabulary_skip('insdc')
    voca_change = _vocabulary_change('insdc', read_in=False)
    # sort it so the output order is deterministic
    for k in sorted(md):
        if k.startswith('__') or k in voca_skip:
            continue
        v = md[k]
        if k == 'phase':
            v = str(v + 1)
        if k in voca_change:
            k = voca_change[k]
        if isinstance(v, list):
            for vi in v:
                qualifiers.append(_serialize_qualifier(k, vi))
        else:
            qualifiers.append(_serialize_qualifier(k, v))

    if '__location' in md:
        loc = md['__location']
    else:
        loc = _serialize_location(intvl)
    # the qualifiers start at column 22
    qualifiers = [' ' * indent + i for i in qualifiers]
    return '{header:<{indent}}{loc}\n{qualifiers}\n'.format(
        header=padding + md['type'],
        loc=loc,
        indent=indent,
        qualifiers='\n'.join(qualifiers))


def _serialize_location(intvl):
    loc = []
    for bound, fuzzy in zip(intvl.bounds, intvl.fuzzy):
        start, end = bound
        start += 1
        if start == end:
            s = str(start)
        elif fuzzy[0] and fuzzy[1]:
            s = '<%d..>%d' % (start, end)
        elif fuzzy[0] and not fuzzy[1]:
            s = '<%d..%d' % (start, end)
        elif not fuzzy[0] and fuzzy[1]:
            s = '%d..>%d' % (start, end)
        else:
            s = '%d..%d' % (start, end)
        loc.append(s)
    if len(loc) > 1:
        loc_str = 'join({})'.format(','.join(loc))
    else:
        loc_str = loc[0]
    if intvl.metadata.get('strand') == '-':
        loc_str = 'complement({})'.format(loc_str)
    return loc_str


def _serialize_qualifier(key, value):
    '''Serialize a Qualifier in a feature.

    Parameters
    ----------
    value : int, str
    '''
    # if value is empty
    if not value:
        return '/%s' % key

    return '/{k}={v}'.format(k=key, v=value)