| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
Interface for indexed gzipped files |
| 5 |
|
| 6 |
@author: Manuel Koesters |
| 7 |
""" |
| 8 |
|
| 9 |
|
| 10 |
n |
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
import codecs |
| 32 |
import gzip |
| 33 |
from xml.etree.ElementTree import XML |
| 34 |
|
| 35 |
from .. import spec |
| 36 |
from ..utils.GSGR import GSGR |
| 37 |
|
| 38 |
|
| 39 |
class IndexedGzip: |
| 40 |
def __init__(self, path, encoding): |
| 41 |
""" |
| 42 |
Initialize Wrapper object for indexed gzipped files. |
| 43 |
|
| 44 |
Arguments: |
| 45 |
path (str) : path to the file |
| 46 |
encoding (str) : encoding of the file |
| 47 |
""" |
| 48 |
self.path = path |
| 49 |
self.file_handler = codecs.getreader(encoding)(gzip.open(path)) |
| 50 |
self.offset_dict = dict() |
| 51 |
self._build_index() |
| 52 |
|
| 53 |
def __del__(self): |
| 54 |
"""Close handlers when deleting object.""" |
| 55 |
self.Reader.close() |
| 56 |
self.file_handler.close() |
| 57 |
|
| 58 |
def _build_index(self): |
| 59 |
"""Use the GSGR class to retrieve the index from the file and save it.""" |
| 60 |
self.Reader = GSGR(self.path) |
| 61 |
self.offset_dict = self.Reader.index |
| 62 |
|
| 63 |
def read(self, size=-1): |
| 64 |
""" |
| 65 |
Read binary data from file handler. |
| 66 |
|
| 67 |
Keyword Arguments: |
| 68 |
size (int): Number of bytes to read from file, -1 to read to end of file |
| 69 |
|
| 70 |
Returns: |
| 71 |
data (str): byte string of len size of input data |
| 72 |
""" |
| 73 |
return self.file_handler.read(size) |
| 74 |
|
| 75 |
def __getitem__(self, identifier): |
| 76 |
""" |
| 77 |
Access the item with id 'identifier' in the file. |
| 78 |
|
| 79 |
Arguments: |
| 80 |
identifier (str): native id of the item to access |
| 81 |
|
| 82 |
Returns: |
| 83 |
data (str): text associated with the given identifier |
| 84 |
""" |
| 85 |
|
| 86 |
|
| 87 |
ns_prefix = '<mzML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://psi.hupo.org/ms/mzml http://psidev.info/files/ms/mzML/xsd/mzML1.1.0.xsd" id="test_Creinhardtii_QE_pH8" version="1.1.0" xmlns="http://psi.hupo.org/ms/mzml">' |
| 88 |
ns_suffix = "</mzML>" |
| 89 |
data = self.Reader.read_block(identifier) |
| 90 |
element = XML(ns_prefix + data.decode("utf-8") + ns_suffix) |
| 91 |
if "chromatogram" in element[0].tag: |
| 92 |
return spec.Chromatogram(list(element)[0], measured_precision=5e-6) |
| 93 |
else: |
| 94 |
return spec.Spectrum(list(element)[0], measured_precision=5e-6) |
| 95 |
|
| 96 |
def close(self): |
| 97 |
"""Close the handlers.""" |
| 98 |
self.Reader.close() |
| 99 |
self.file_handler.close() |
| 100 |
|
| 101 |
|
| 102 |
if __name__ == "__main__": |
| 103 |
print(__doc__) |