featureio.py 14.4 KB
Newer Older
Jerome Mariette's avatar
Jerome Mariette committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#
# Copyright (C) 2012 INRA
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import os

from jflow.xopen import xopen
from jflow.seqio import FormatError
from jflow.seqio import UnknownFileType
Jerome Mariette's avatar
Jerome Mariette committed
23
import re
Jerome Mariette's avatar
Jerome Mariette committed
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

def boolify(s):
    return {'True': True, 'False': False}[s]

def autocast(s):
    for fn in (boolify, int, float):
        try:
            return fn(s)
        except:
            pass
    return s

class Entry(object):
    def __init__(self, **kwargs):
        self.attrib = kwargs
    
    def addattr(self, k, v):
        self.attrib[k] = v
        
    def __getattr__(self, key):
        return self.attrib[key]
    
    def __str__(self):
        return str(self.attrib)

    def __getitem__(self, key):
        return self.attrib[key]

Jerome Mariette's avatar
Jerome Mariette committed
52
53
54
    def has(self,attr):
        return self.attrib.has_key(attr)
        
Jerome Mariette's avatar
Jerome Mariette committed
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
class _AbstractFeatureReader(object):
    '''
        Abstract file reader
    '''
    def __init__(self, file, wholefile=False):
        """
            @param file : filename or a file-like object. 
            @param wholefile: If True, then it is ok to read the entire file  into memory. This is faster when there are 
                many newlines in the file, but may obviously need a lot of memory.
        """
        if isinstance(file, basestring):
            file = xopen(file, "r")
        self.fp = file
        self.wholefile = wholefile
    
    def __iter__(self):
        return self._wholefile_iter() if self.wholefile else self._streaming_iter()
    
    def _streaming_iter(self):
        raise NotImplementedError('not implemented')

    def _wholefile_iter(self):
        raise NotImplementedError('not implemented')
    
    def __enter__(self):
        if self.fp is None:
            raise ValueError("I/O operation on closed {0}".format(self.__class__.__name__) )
        return self

    def __exit__(self, *args):
        self.fp.close()


class GFF3Reader(_AbstractFeatureReader):
    '''
        Reader for GFF3 files
    '''
    def _process_line(self, line):
        row = line.rstrip().split('\t')
        if len(row) != 9 : raise FormatError('Invalid number of columns in your GFF3 file {0}'.format( len(row)))
        attributes = {}
        if row[8] and row[8] != '.' :
Jerome Mariette's avatar
Jerome Mariette committed
97
98
            for p in row[8].split(';') :
                if p != ""  :
99
100
101
102
                    if len(p.partition('=')) == 3 :
                        attributes[p.partition('=')[0]] = p.partition('=')[2]
                    else :
                        print "Warn : Attribute "+ p +" gff3 for "+ "\t".join(row) + "\n"
Jerome Mariette's avatar
Jerome Mariette committed
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
        
        return Entry(**{'seqid' : row[0], 'source' : row[1], 'type' : row[2], 'start' : int(row[3]), 'end' : int(row[4]),
                      'score' : row[5], 'strand' : row[6], 'phase' : row[7], 'attributes' : attributes  })
        
    def _streaming_iter(self):
        """
            Read next entry from the file (single entry at a time).
        """
        for line in self.fp:
            if line.startswith('#') :
                continue
            yield self._process_line(line)
    
    def _wholefile_iter(self):
        """
            This reads in the entire file at once, but is faster than the above code when there are lots of newlines.
            The idea comes from the TAMO package (http://fraenkel.mit.edu/TAMO/), module TAMO.seq.Fasta (author is
            David Benjamin Gordon).
        """
        wholefile = self.fp.read()
        assert '\r' not in wholefile, "Sorry, currently don't know how to deal with files that contain \\r linebreaks"
        assert len(wholefile) == 0 , "Empty gff3 file"
        for line in wholefile.split('\n') :
            if line.startswith('#') :
                continue
            yield self._process_line(line)

class BEDReader(_AbstractFeatureReader):
    '''
        Reader for BED
    '''
    def _process_line(self,line):
        row = line.rstrip().split('\t')
        if len(row) not in range(3,13) : raise FormatError('Invalid number of columns in your BED file {0}'.format( len(row)))
        return Entry(**{ 'chrom' : row[0], 'chromStart' : row[1], 'chromEnd' : row[2] })
        
    def _streaming_iter(self):
        for line in self.fp :
            if line.startswith('#') :
                continue
            yield self._process_line(line)
    
    def _wholefile_iter(self):
        wholefile = self.fp.read()
        assert '\r' not in wholefile, "Sorry, currently don't know how to deal with files that contain \\r linebreaks"
        assert len(wholefile) == 0 , "Empty BED file"
        
        for line in wholefile.split('\n') :
            if line.startswith('#') :
                continue
            yield self._process_line(line)

class WEGOReader(_AbstractFeatureReader):
    '''
        Reader for WEGO files
    '''
    
    def _process_line(self,line):
        row = line.rstrip().split('\t')
        name, ids = row[0], []
        if len(row) > 1 :
            ids = row[1:]
        return (name, ids)  
        
    def _streaming_iter(self):
        
        # first line must be !WGOP
        if not self.fp.readline().startswith('!WGOP'):
            raise FormatError('WEGO header not found (!WEGOP_), invalid WEGO file ')
        
        for line in fp :
            if line.startswith('!WEGO') :
                continue
            yield self._process_line(line)  
    
    def _wholefile_iter(self):
        wholefile = self.fp.read()
        assert '\r' not in wholefile, "Sorry, currently don't know how to deal with files that contain \\r linebreaks"
        assert len(wholefile) == 0 , "Empty WEGO file"
        if not wholefile.startswith('!WGOP') :
            raise FormatError('WEGO header not found (!WEGOP_), invalid WEGO file ')
        
        for line in wholefile.split('\n') :
            if line.startswith('!WEGO') :
                continue
            yield self._process_line(line)  


class VCFReader(_AbstractFeatureReader):
    '''
        Reader for VCF files
        Read a vcf file and yield an entry object. Each line will be yield as an Entry object. To access samples for 
        variation, use entry.samples, which will be an array of Entry
        
        Fields for a variation entry :
            entry.chrom, entry.pos, entry.id, entry.ref, entry.alt, entry.qual, entry.filter, entry.info, entry.format
            entry.is_indel
            special case :
                * entry.alt     : array of string
                * entry.info    : dictionary
                * entry.samples : array of entries
            
        Fields of a sample entry :
            entry.name, entry.path
            all other fields depends on the FORMAT column
    '''
    def __init__(self, file, wholefile=False):
        """
            @param file : filename or a file-like object. 
            @param wholefile: If True, then it is ok to read the entire file  into memory. This is faster when there are 
                many newlines in the file, but may obviously need a lot of memory.
        """
        if isinstance(file, basestring):
            file = xopen(file, "r")
        self.fp = file
        self.wholefile = wholefile
        self.samples_name=[]
Jerome Mariette's avatar
Jerome Mariette committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
        self._init_sample_names()

    def _init_sample_names(self):
        for line in self.fp :
            if line.startswith('#') :
                if line.startswith('#CHROM') :
                    row = line.rstrip().split('\t')
                    if len(row) <= 9 : 
                        raise FormatError( 'Invalid number of columns in your vcf header file {0}'.format(len(row)) )
                    for i in range(9, len(row)) :
                        self.samples_name.append( ( row[i] , os.path.splitext(os.path.basename(row[i]))[0]  ) )
                    break
            else :
                raise FormatError( 'The vcf file {0}must start with header lines (#) !!!'.format(self.fp.name) )
        self.fp.seek(0,0)
        if len(self.samples_name) < 0 :
            raise FormatError(  "Invalid VCF file {0}. Could not retrieve the sample names headers".format(self.fp.name) )
    
Jerome Mariette's avatar
Jerome Mariette committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
    def _process_line(self,line):
        row = line.rstrip().split('\t')
        variation = Entry(**{ 
           'chrom'   : row [0], 
           'pos'     : int(row[1]), 
           'id'      : row[2], 
           'ref'     : row[3], 
           'alt'     : row[4].split(',') , 
           'qual'    : autocast(row[5]),
           'filter'  : row[6],
           'info'    : {},
           'format'  : row[8].split(';'),
           'samples' : [],
           'is_indel': False
          })
        
        if len(variation.alt) > 1 :
            variation.addattr( 'is_indel', True)
        
Jerome Mariette's avatar
Jerome Mariette committed
257
        regexp_none=re.compile("\.(\/\.)*")
258
259
260
261
        
        #if row[7] != '.' :
        #    variation.addattr( 'info', { p.split('=')[0] : autocast(p.split('=')[1])  for p in row[7].split(';') })
        
Jerome Mariette's avatar
Jerome Mariette committed
262
263
        format = row[8].split(':')
        for lib_infos in range (9,len(row)) :
Jerome Mariette's avatar
Jerome Mariette committed
264
            if not regexp_none.match(row[lib_infos]):
Jerome Mariette's avatar
Jerome Mariette committed
265
                sformat = row[lib_infos].split(':')
Jerome Mariette's avatar
Jerome Mariette committed
266
                variation.samples.append( Entry(**{ autocast(format[i]) : autocast(sformat[i]) if sformat[i] != '.' else None for i in range(0,len(format)) } )  )
Jerome Mariette's avatar
Jerome Mariette committed
267
            else :
Jerome Mariette's avatar
Jerome Mariette committed
268
                variation.samples.append( Entry(**{ autocast(format[i]) : None for i in range(0,len(format)) }) )
Jerome Mariette's avatar
Jerome Mariette committed
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
        return variation
    
    def _streaming_iter(self):
        for line in self.fp :
            if line.startswith('#') :
                continue
            yield self._process_line(line)
    
    def _wholefile_iter(self):
        wholefile = self.fp.read()
        assert '\r' not in wholefile, "Sorry, currently don't know how to deal with files that contain \\r linebreaks"
        assert len(wholefile) == 0 , "Empty VCF file"
        for line in wholefile.split('\n') :
            if line.startswith('#') :
                continue
            yield self._process_line(line) 

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
class MpileupReader(_AbstractFeatureReader):
    """
    Reader for Mpileup files.
    """
    
    def _streaming_iter(self):
        for line in self.fp :
            if line == None or line == "" : continue
            row = line.rstrip().split('\t')
            if len(row) < 4 : continue
            
            libs_count=[]
            i=3
            while (i < len(row) ) :
                libs_count.append(int(row[i]))
                i += 3
            
            pileup = Entry(**{ 
               'chrom'   : row [0], 
               'pos'     : int(row[1]), 
               'ref'     : row[2], 
               'libs'     : libs_count , 
              })
            yield pileup
            libs_count=[]
    
    def _wholefile_iter(self):
        wholefile = self.fp.read()
        assert '\r' not in wholefile, "Sorry, currently don't know how to deal with files that contain \\r linebreaks"
        assert len(wholefile) == 0 , "Empty VCF file"
        
        for line in wholefile.split('\n') :
            row = line.rstrip().split('\t')
            libs_count=[]
            i=3
            while (i < len(row) ) :
                libs_count.append(int(row[i]))
                i += 3
            
            pileup = Entry(**{ 
               'chrom'   : row [0], 
               'pos'     : int(row[1]), 
               'ref'     : row[2], 
               'lib'     : libs_count , 
              })
            yield pileup
            libs_count=[]

Jerome Mariette's avatar
Jerome Mariette committed
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
class OboReader(_AbstractFeatureReader):
    """
    Reader for OBO files.
    """

    def _streaming_iter(self):
        """
        Read next entry from the file (single entry at a time).

        # TODO this can be quadratic since += is used for the obo record
        """
        id = None
        name = ""
        namespace = ""
        parents = []
        for line in self.fp:
            # strip() should also take care of DOS line breaks
            line = line.strip()
            if line=="" :
                if id is not None:
                    yield Entry(**{ 'id' : id, 'name' : name, 'namespace' : namespace, "parents" : parents })
                    id=None
                    parents = []
            else:
                if line.startswith("id: "):
                    id=line.split(": ")[1]
                elif line.startswith("name: "):
                    name=line.split(": ")[1]
                elif line.startswith("namespace: "):
Jerome Mariette's avatar
Jerome Mariette committed
363
                    namespace=line.split()[1][0].upper()
Jerome Mariette's avatar
Jerome Mariette committed
364
                elif line.startswith("is_a: "):
Jerome Mariette's avatar
Jerome Mariette committed
365
                    parents.append(line.split()[1])
Jerome Mariette's avatar
Jerome Mariette committed
366
                elif line.startswith("relationship: part_of: ") :
Jerome Mariette's avatar
Jerome Mariette committed
367
                    parents.append(line.split()[3])
Jerome Mariette's avatar
Jerome Mariette committed
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
                    
        if id is not None:
            yield Entry(**{ 'id' : id, 'name' : name, 'namespace' : namespace, "parents" : parents })

    def _wholefile_iter(self):
        """
        This reads in the entire file at once, but is faster than the above code when there are lots of newlines.
        The idea comes from the TAMO package (http://fraenkel.mit.edu/TAMO/), module TAMO.seq.Fasta (author is
        David Benjamin Gordon).
        """
        wholefile = self.fp.read()
        assert '\r' not in wholefile, "Sorry, currently don't know how to deal with files that contain \\r linebreaks"
        parts = wholefile.split('\n[Term]')

        id = None
        name = ""
        namespace = ""
        parents = []
        for part in parts:
            
            for line in part.split('\n'):
                line.strip()
                if line.startswith("id: "):
                    id=line.split(": ")[1]
                elif line.startswith("name: "):
                    name=line.split(": ")[1]
                elif line.startswith("namespace: "):
Jerome Mariette's avatar
Jerome Mariette committed
395
                    namespace=line.split()[1][0].upper()
Jerome Mariette's avatar
Jerome Mariette committed
396
                elif line.startswith("is_a: "):
Jerome Mariette's avatar
Jerome Mariette committed
397
                    parents.append(line.split()[1])
Jerome Mariette's avatar
Jerome Mariette committed
398
                elif line.startswith("relationship: part_of: ") :
Jerome Mariette's avatar
Jerome Mariette committed
399
                    parents.append(line.split()[3])
Jerome Mariette's avatar
Jerome Mariette committed
400
401
402
403

            yield Entry(**{ 'id' : id, 'name' : name, 'namespace' : namespace, "parents" : parents })
            parents = []