| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
Interface for gzipped mzML files. |
| 5 |
""" |
| 6 |
|
| 7 |
|
| 8 |
n |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
import codecs |
| 30 |
import gzip |
| 31 |
from xml.etree.ElementTree import iterparse |
| 32 |
|
| 33 |
from .. import regex_patterns |
| 34 |
from .. import spec |
| 35 |
|
| 36 |
|
| 37 |
class StandardGzip(object): |
| 38 |
def __init__(self, path, encoding): |
| 39 |
""" |
| 40 |
Initalize Wrapper object for gzipped mzML files. |
| 41 |
|
| 42 |
Arguments: |
| 43 |
path (str) : path to the file |
| 44 |
encoding (str) : encoding of the file |
| 45 |
""" |
| 46 |
self.path = path |
| 47 |
self.file_handler = codecs.getreader(encoding)(gzip.open(path)) |
| 48 |
self.offset_dict = self._build_index() |
| 49 |
return |
| 50 |
|
| 51 |
def close(self): |
| 52 |
self.file_handler.close() |
| 53 |
|
| 54 |
def _build_index(self): |
| 55 |
""" |
| 56 |
Cant build index for standard gzip files |
| 57 |
""" |
| 58 |
|
| 59 |
pass |
| 60 |
|
| 61 |
def read(self, size=-1): |
| 62 |
""" |
| 63 |
Read binary data from file handler. |
| 64 |
|
| 65 |
Keyword Arguments: |
| 66 |
size (int): Number of bytes to read from file, -1 to read to end of file |
| 67 |
|
| 68 |
Returns: |
| 69 |
data (str): byte string of len size of input data |
| 70 |
""" |
| 71 |
return self.file_handler.read(size) |
| 72 |
|
| 73 |
def __getitem__(self, identifier): |
| 74 |
""" |
| 75 |
Access the item with id 'identifier' in the file by iterating the xml-tree. |
| 76 |
|
| 77 |
Arguments: |
| 78 |
identifier (str): native id of the item to access |
| 79 |
|
| 80 |
Returns: |
| 81 |
data (str): text associated with the given identifier |
| 82 |
""" |
| 83 |
old_pos = self.file_handler.tell() |
| 84 |
self.file_handler.seek(0, 0) |
| 85 |
mzml_iter = iter(iterparse(self.file_handler, events=["end"])) |
| 86 |
while True: |
| 87 |
event, element = next(mzml_iter) |
| 88 |
if event == "end": |
| 89 |
if element.tag.endswith("}spectrum"): |
| 90 |
if ( |
| 91 |
int( |
| 92 |
regex_patterns.SPECTRUM_ID_PATTERN.search( |
| 93 |
element.get("id") |
| 94 |
).group(1) |
| 95 |
) |
| 96 |
== identifier |
| 97 |
): |
| 98 |
self.file_handler.seek(old_pos, 0) |
| 99 |
return spec.Spectrum(element, measured_precision=5e-6) |
| 100 |
elif element.tag.endswith("}chromatogram"): |
| 101 |
if element.get("id") == identifier: |
| 102 |
self.file_handler.seek(old_pos, 0) |
| 103 |
return spec.Chromatogram(element, measured_precision=5e-6) |
| 104 |
|
| 105 |
|
| 106 |
if __name__ == "__main__": |
| 107 |
print(__doc__) |