| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
The class :py:class:`Reader` has been designed to selectively extract data |
| 5 |
from a mzML file and to expose the data as a python object. |
| 6 |
Necessary information are read in and stored in a fast |
| 7 |
accessible format. |
| 8 |
The reader itself is an iterator, thus looping over all spectra |
| 9 |
follows the classical pythonian syntax. |
| 10 |
Additionally one can random access spectra by their nativeID |
| 11 |
if the file if not truncated by a conversion Program. |
| 12 |
|
| 13 |
Note: |
| 14 |
The class :py:class:`Writer` is still in development. |
| 15 |
|
| 16 |
""" |
| 17 |
|
| 18 |
|
| 19 |
n |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
import re |
| 42 |
import os |
| 43 |
import xml.etree.ElementTree as ElementTree |
| 44 |
from collections import defaultdict as ddict |
| 45 |
from io import BytesIO |
| 46 |
from pathlib import Path |
| 47 |
|
| 48 |
from . import spec |
| 49 |
from . import obo |
| 50 |
from . import regex_patterns |
| 51 |
from .file_interface import FileInterface |
| 52 |
from .file_classes.standardMzml import StandardMzml |
| 53 |
|
| 54 |
|
| 55 |
class Reader(object): |
| 56 |
""" |
| 57 |
Initialize Reader object for a given mzML file. |
| 58 |
|
| 59 |
Arguments: |
| 60 |
path (str): path to the mzml file to parse. |
| 61 |
|
| 62 |
Keyword Arguments: |
| 63 |
MS_precisions (dict): measured precisions for the different MS levels. |
| 64 |
e.g.:: |
| 65 |
|
| 66 |
{ |
| 67 |
1 : 5e-6, |
| 68 |
2 : 20e-6 |
| 69 |
} |
| 70 |
|
| 71 |
obo_version (str, optional): obo version number as string. If not |
| 72 |
specified the version will be extracted from the mzML file |
| 73 |
|
| 74 |
Note: |
| 75 |
Setting the precision for MS1 and MSn spectra has changed in version 1.2. |
| 76 |
However, the old syntax as kwargs is still compatible ( e.g. 'MS1_Precision=5e-6'). |
| 77 |
""" |
| 78 |
|
| 79 |
def __init__( |
| 80 |
self, |
| 81 |
path_or_file, |
| 82 |
MS_precisions=None, |
| 83 |
obo_version=None, |
| 84 |
build_index_from_scratch=False, |
| 85 |
skip_chromatogram=True, |
| 86 |
index_regex=None, |
| 87 |
**kwargs |
| 88 |
): |
| 89 |
"""Initialize and set required attributes.""" |
| 90 |
self.index_regex = index_regex |
| 91 |
self.build_index_from_scratch = build_index_from_scratch |
| 92 |
self.skip_chromatogram = skip_chromatogram |
| 93 |
if MS_precisions is None: |
| 94 |
MS_precisions = {} |
| 95 |
if "MS1_Precision" in kwargs.keys(): |
| 96 |
MS_precisions[1] = kwargs["MS1_Precision"] |
| 97 |
if "MSn_Precision" in kwargs.keys(): |
| 98 |
MS_precisions[2] = kwargs["MSn_Precision"] |
| 99 |
MS_precisions[3] = kwargs["MSn_Precision"] |
| 100 |
|
| 101 |
|
| 102 |
self.ms_precisions = { |
| 103 |
None: 0.0001, |
| 104 |
|
| 105 |
|
| 106 |
0: 0.0001, |
| 107 |
1: 5e-6, |
| 108 |
2: 20e-6, |
| 109 |
3: 20e-6, |
| 110 |
} |
| 111 |
self.ms_precisions.update(MS_precisions) |
| 112 |
|
| 113 |
|
| 114 |
self.info = ddict() |
| 115 |
self.path_or_file = path_or_file |
| 116 |
if isinstance(self.path_or_file, Path): |
| 117 |
self.path_or_file = str(self.path_or_file) |
| 118 |
if isinstance(self.path_or_file, str): |
| 119 |
self.info["file_name"] = self.path_or_file |
| 120 |
self.info["encoding"] = self._determine_file_encoding(self.path_or_file) |
| 121 |
else: |
| 122 |
self.info["encoding"] = self._guess_encoding(self.path_or_file) |
| 123 |
|
| 124 |
self.info["file_object"] = self._open_file( |
| 125 |
self.path_or_file, build_index_from_scratch=self.build_index_from_scratch |
| 126 |
) |
| 127 |
self.info["offset_dict"] = self.info["file_object"].offset_dict |
| 128 |
if obo_version: |
| 129 |
self.info["obo_version"] = self._obo_version_validator(obo_version) |
| 130 |
else: |
| 131 |
|
| 132 |
self.info["obo_version"] = None |
| 133 |
|
| 134 |
self.iter = self._init_iter() |
| 135 |
self.OT = self._init_obo_translator() |
| 136 |
|
| 137 |
def __next__(self): |
| 138 |
""" |
| 139 |
Iterator for the class :py:class:`Run`. |
| 140 |
|
| 141 |
Iterates all of the spectra in the file. |
| 142 |
|
| 143 |
Returns: |
| 144 |
Spectrum (:py:class:`Spectrum`): a spectrum object with interface |
| 145 |
to the original spectrum element. |
| 146 |
|
| 147 |
Example: |
| 148 |
|
| 149 |
>>> for spectrum in Reader: |
| 150 |
... print(spectrum.mz, end='\\r') |
| 151 |
|
| 152 |
""" |
| 153 |
has_ref_group = self.info.get("referenceable_param_group_list", False) |
| 154 |
while True: |
| 155 |
event, element = next(self.iter, ("END", "END")) |
| 156 |
if event == "end": |
| 157 |
if element.tag.endswith("}spectrum"): |
| 158 |
spectrum = spec.Spectrum(element, obo_version=self.OT.version) |
| 159 |
if has_ref_group: |
| 160 |
spectrum._set_params_from_reference_group( |
| 161 |
self.info["referenceable_param_group_list_element"] |
| 162 |
) |
| 163 |
ms_level = spectrum.ms_level |
| 164 |
spectrum.measured_precision = self.ms_precisions[ms_level] |
| 165 |
return spectrum |
| 166 |
if element.tag.endswith("}chromatogram"): |
| 167 |
if self.skip_chromatogram: |
| 168 |
continue |
| 169 |
spectrum = spec.Chromatogram(element, obo_version=self.OT.version) |
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
return spectrum |
| 175 |
elif event == "END": |
| 176 |
|
| 177 |
self.info["file_object"].close() |
| 178 |
self.info["file_object"] = self._open_file( |
| 179 |
self.path_or_file, build_index_from_scratch=False |
| 180 |
) |
| 181 |
self.iter = self._init_iter() |
| 182 |
raise StopIteration |
| 183 |
|
| 184 |
def __getitem__(self, identifier): |
| 185 |
""" |
| 186 |
Access spectrum with native id 'identifier'. |
| 187 |
|
| 188 |
Arguments: |
| 189 |
identifier (str or int): last number in the id tag of the spectrum |
| 190 |
element |
| 191 |
|
| 192 |
Returns: |
| 193 |
spectrum (Spectrum or Chromatogram): spectrum/chromatogram object |
| 194 |
with native id 'identifier' |
| 195 |
""" |
| 196 |
try: |
| 197 |
if int(identifier) > self.get_spectrum_count(): |
| 198 |
raise Exception("Requested identifier is out of range") |
| 199 |
except: |
| 200 |
pass |
| 201 |
spectrum = self.info["file_object"][identifier] |
| 202 |
spectrum.obo_translator = self.OT |
| 203 |
if isinstance(spectrum, spec.Spectrum): |
| 204 |
spectrum.measured_precision = self.ms_precisions[spectrum.ms_level] |
| 205 |
return spectrum |
| 206 |
|
| 207 |
def __enter__(self): |
| 208 |
return self |
| 209 |
|
| 210 |
def __exit__(self, type, value, traceback): |
| 211 |
self.close() |
| 212 |
|
| 213 |
@property |
| 214 |
def file_class(self): |
| 215 |
"""Return file object in use.""" |
| 216 |
return type(self.info["file_object"].file_handler) |
| 217 |
|
| 218 |
def _open_file(self, path_or_file, build_index_from_scratch=False): |
| 219 |
""" |
| 220 |
Open the path using the FileInterface class as a wrapper. |
| 221 |
|
| 222 |
Arguments: |
| 223 |
path (str): path to the file to parse |
| 224 |
|
| 225 |
Returns: |
| 226 |
(FileInterface): Wrapper class for compressed and uncompressed |
| 227 |
mzml files |
| 228 |
""" |
| 229 |
return FileInterface( |
| 230 |
path_or_file, |
| 231 |
self.info["encoding"], |
| 232 |
build_index_from_scratch=build_index_from_scratch, |
| 233 |
index_regex=self.index_regex, |
| 234 |
) |
| 235 |
|
| 236 |
def _guess_encoding(self, mzml_file): |
| 237 |
""" |
| 238 |
Determine the encoding used for the file. |
| 239 |
|
| 240 |
Arguments: |
| 241 |
mzml_file (IOBase): an mzml file |
| 242 |
|
| 243 |
Returns: |
| 244 |
mzml_encoding (str): encoding type of the file |
| 245 |
""" |
| 246 |
match = regex_patterns.FILE_ENCODING_PATTERN.search(mzml_file.readline()) |
| 247 |
if match: |
| 248 |
return bytes.decode(match.group("encoding")) |
| 249 |
else: |
| 250 |
return "utf-8" |
| 251 |
|
| 252 |
def _determine_file_encoding(self, path): |
| 253 |
""" |
| 254 |
Determine the encoding used for the file in path. |
| 255 |
|
| 256 |
Arguments: |
| 257 |
path (str): path to the mzml files |
| 258 |
|
| 259 |
Returns: |
| 260 |
mzml_encoding (str): encoding type of the file |
| 261 |
""" |
| 262 |
if os.path.exists(path): |
| 263 |
if path.endswith(".gz") or path.endswith(".igz"): |
| 264 |
import gzip |
| 265 |
|
| 266 |
_open = gzip.open |
| 267 |
else: |
| 268 |
_open = open |
| 269 |
with _open(path, "rb") as sniffer: |
| 270 |
return self._guess_encoding(sniffer) |
| 271 |
|
| 272 |
@staticmethod |
| 273 |
def _obo_version_validator(version): |
| 274 |
""" |
| 275 |
The obo version should fit file names in the obo folder. |
| 276 |
However, some software generate mzML with built in obo version string like: |
| 277 |
'23:06:2017' or even newer version that not in obo folder yet. |
| 278 |
This is to check obo version and try to fit the best obo version |
| 279 |
to the obo version in the mzML file. |
| 280 |
|
| 281 |
Arguments: |
| 282 |
version (str): The original version to check. |
| 283 |
|
| 284 |
Returns: |
| 285 |
version_fixed (str): The checked obo version. |
| 286 |
""" |
| 287 |
obo_rgx = re.compile(r"(\d\.\d{1,2}\.\d{1,2})(_[rR][cC]\d{0,2})?") |
| 288 |
obo_years_rgx = re.compile(r"20\d\d") |
| 289 |
obo_year_version_dct = { |
| 290 |
2012: "3.40.0", |
| 291 |
2013: "3.50.0", |
| 292 |
2014: "3.60.0", |
| 293 |
2015: "3.75.0", |
| 294 |
2016: "4.0.1", |
| 295 |
2017: "4.1.0", |
| 296 |
2018: "4.1.10", |
| 297 |
2019: "4.1.22", |
| 298 |
} |
| 299 |
version_fixed = None |
| 300 |
if obo_rgx.match(version): |
| 301 |
version_fixed = version |
| 302 |
else: |
| 303 |
if obo_years_rgx.search(version): |
| 304 |
years_found = obo_years_rgx.search(version) |
| 305 |
if years_found: |
| 306 |
try: |
| 307 |
year = int(years_found.group(0)) |
| 308 |
except ValueError: |
| 309 |
year = 2000 |
| 310 |
|
| 311 |
if year in obo_year_version_dct: |
| 312 |
version_fixed = obo_year_version_dct[year] |
| 313 |
else: |
| 314 |
if year > 2019: |
| 315 |
version_fixed = "4.1.0" |
| 316 |
|
| 317 |
if version_fixed: |
| 318 |
|
| 319 |
obo_root = os.path.dirname(__file__) |
| 320 |
obo_file = os.path.join( |
| 321 |
obo_root, |
| 322 |
"obo", |
| 323 |
"psi-ms{0}.obo".format("-" + version_fixed if version_fixed else ""), |
| 324 |
) |
| 325 |
if os.path.exists(obo_file) or os.path.exists(obo_file + ".gz"): |
| 326 |
pass |
| 327 |
else: |
| 328 |
version_fixed = "1.1.0" |
| 329 |
else: |
| 330 |
version_fixed = "1.1.0" |
| 331 |
|
| 332 |
return version_fixed |
| 333 |
|
| 334 |
def _init_obo_translator(self): |
| 335 |
""" |
| 336 |
Initialize the obo translator with the minimum requirement |
| 337 |
and extra Accessions. |
| 338 |
|
| 339 |
Returns: |
| 340 |
obo_translator (OboTranslator): translator class to translate |
| 341 |
accessions to names |
| 342 |
""" |
| 343 |
|
| 344 |
|
| 345 |
if self.info.get("obo_version", None) is None: |
| 346 |
self.info["obo_version"] = "1.1.0" |
| 347 |
obo_translator = obo.OboTranslator.from_cache(version=self.info["obo_version"]) |
| 348 |
|
| 349 |
return obo_translator |
| 350 |
|
| 351 |
def _init_iter(self): |
| 352 |
""" |
| 353 |
Initalize the iterator for the spectra and sets it to the start |
| 354 |
of the spectrumList element. |
| 355 |
|
| 356 |
Returns: |
| 357 |
mzml_iter (xml.etree.ElementTree._IterParseIterator): Iterator over |
| 358 |
all element in the file starting with the first spectrum |
| 359 |
""" |
| 360 |
mzml_iter = iter( |
| 361 |
ElementTree.iterparse(self.info["file_object"], events=("end", "start")) |
| 362 |
) |
| 363 |
_, self.root = next(mzml_iter) |
| 364 |
self.info["chromatogram_count"] = None |
| 365 |
self.info["spectrum_count"] = None |
| 366 |
while True: |
| 367 |
event, element = next(mzml_iter, ("END", "END")) |
| 368 |
if element.tag.endswith("}mzML"): |
| 369 |
if "version" in element.attrib and len(element.attrib["version"]) > 0: |
| 370 |
self.info["mzml_version"] = element.attrib["version"] |
| 371 |
else: |
| 372 |
s = element.attrib[ |
| 373 |
"{http://www.w3.org/2001/XMLSchema-instance}" "schemaLocation" |
| 374 |
] |
| 375 |
self.info["mzml_version"] = re.search( |
| 376 |
r"[0-9]*\.[0-9]*\.[0-9]*", s |
| 377 |
).group() |
| 378 |
elif element.tag.endswith("}cv"): |
| 379 |
if ( |
| 380 |
not self.info["obo_version"] |
| 381 |
and element.attrib.get("id", None) == "MS" |
| 382 |
): |
| 383 |
obo_in_mzml = element.attrib.get("version", "1.1.0") |
| 384 |
self.info["obo_version"] = self._obo_version_validator(obo_in_mzml) |
| 385 |
|
| 386 |
elif element.tag.endswith("}fileDescription"): |
| 387 |
self.info["file_description"] = True |
| 388 |
self.info["file_description_element"] = element |
| 389 |
elif element.tag.endswith("}sampleList"): |
| 390 |
self.info["sample_list"] = True |
| 391 |
self.info["sample_list_element"] = element |
| 392 |
|
| 393 |
elif element.tag.endswith("}referenceableParamGroupList"): |
| 394 |
self.info["referenceable_param_group_list"] = True |
| 395 |
self.info["referenceable_param_group_list_element"] = element |
| 396 |
|
| 397 |
elif element.tag.endswith("}softwareList"): |
| 398 |
self.info["software_list"] = True |
| 399 |
self.info["software_list_element"] = element |
| 400 |
elif element.tag.endswith("}instrumentConfigurationList"): |
| 401 |
self.info["instrument_configuration_list"] = True |
| 402 |
self.info["instrument_configuration_list_element"] = element |
| 403 |
elif element.tag.endswith("}dataProcessingList"): |
| 404 |
self.info["data_processing_list"] = True |
| 405 |
self.info["data_processing_list_element"] = element |
| 406 |
|
| 407 |
elif element.tag.endswith("}spectrumList"): |
| 408 |
spec_cnt = element.attrib.get("count") |
| 409 |
self.info["spectrum_count"] = int(spec_cnt) if spec_cnt else None |
| 410 |
break |
| 411 |
elif element.tag.endswith("}chromatogramList"): |
| 412 |
chrom_cnt = element.attrib.get("count", None) |
| 413 |
if chrom_cnt: |
| 414 |
self.info["chromatogram_count"] = int(chrom_cnt) |
| 415 |
break |
| 416 |
elif element.tag.endswith("}run"): |
| 417 |
run_id = element.attrib.get("id") |
| 418 |
start_time = element.attrib.get("startTimeStamp") |
| 419 |
self.info["run_element"] = element |
| 420 |
self.info["run_id"] = run_id |
| 421 |
self.info["start_time"] = start_time |
| 422 |
else: |
| 423 |
pass |
| 424 |
self.root.clear() |
| 425 |
return mzml_iter |
| 426 |
|
| 427 |
def __iter__(self): |
| 428 |
"""Return self.""" |
| 429 |
return self |
| 430 |
|
| 431 |
def next(self): |
| 432 |
"""Function to return the next Spectrum element.""" |
| 433 |
return self.__next__() |
| 434 |
|
| 435 |
def get_spectrum_count(self): |
| 436 |
""" |
| 437 |
Number of spectra in file. |
| 438 |
|
| 439 |
Returns: |
| 440 |
spectrum count (int): Number of spectra in file. |
| 441 |
""" |
| 442 |
return self.info["spectrum_count"] |
| 443 |
|
| 444 |
def get_chromatogram_count(self): |
| 445 |
""" |
| 446 |
Number of chromatograms in file. |
| 447 |
|
| 448 |
Returns: |
| 449 |
chromatogram count (int): Number of chromatograms in file. |
| 450 |
""" |
| 451 |
return self.info["chromatogram_count"] |
| 452 |
|
| 453 |
def close(self): |
| 454 |
self.info["file_object"].close() |
| 455 |
|
| 456 |
|
| 457 |
if __name__ == "__main__": |
| 458 |
print(__doc__) |