Debian Codegraph @

pymzml/spec.py

raw symbols SCIP
1 #!usr/bin/env python3
2 # -*- coding: latin-1 -*-
3 """
4 The spectrum class offers a python object for mass spectrometry data.
5 The spectrum object holds the basic information of the spectrum and offers
6 methods to interrogate properties of the spectrum.
7 Data, i.e. mass over charge (m/z) and intensity decoding is performed on demand
8 and can be accessed via their properties, e.g. :py:attr:`~pymzml.spec.Spectrum.peaks`.
9
10 The Spectrum class is used in the :py:class:`~pymzml.run.Reader` class.
11 There each spectrum is accessible as a spectrum object.
12
13 Theoretical spectra can also be created using the setter functions.
14 For example, m/z values, intensities, and peaks can be set by the
15 corresponding properties: :py:attr:`pymzml.spec.Spectrum.mz`,
16 :py:attr:`pymzml.spec.Spectrum.i`, :py:attr:`pymzml.spec.Spectrum.peaks`.
17
18 Similar to the spectrum class, the chromatogram class allows interrogation
19 with profile data (time, intensity) in an total ion chromatogram.
20 """
21
22 # Python mzML module - pymzml
23 # Copyright (C) 2010-2019 M. Kösters, C. Fufezan
24 # The MIT License (MIT)
25
26 # Permission is hereby granted, free of charge, to any person obtaining a copy
27 # of this software and associated documentation files (the "Software"), to deal
28 # in the Software without restriction, including without limitation the rights
29 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30 # copies of the Software, and to permit persons to whom the Software is
31 # furnished to do so, subject to the following conditions:
32
33 # The above copyright notice and this permission notice shall be included in all
34 # copies or substantial portions of the Software.
35
36 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
41 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
42 # SOFTWARE.
43
44 import math
45 import re
46 import sys
47 import warnings
48 import xml.etree.ElementTree as ElementTree
49 import zlib
50 from base64 import b64decode as b64dec
51 from collections import defaultdict as ddict
52 from functools import lru_cache
53 from operator import itemgetter as itemgetter
54 from struct import unpack
55
56 import numpy as np
57
58 try:
59 DECON_DEP = True
60 from ms_deisotope.deconvolution import deconvolute_peaks
61 from ms_peak_picker import simple_peak
62 except (ImportError, ModuleNotFoundError) as e:
63 DECON_DEP = False
64 pass
65 from . import regex_patterns
66 from .decoder import MSDecoder
67 from .obo import OboTranslator
68
69 PROTON = 1.00727646677
70 ISOTOPE_AVERAGE_DIFFERENCE = 1.002
71
72
73 class MS_Spectrum(object):
74 """
75 General spectrum class for data handling.
76 """
77
78 def _read_accessions(self):
79 """Set all required variables for this spectrum."""
80 self.accessions = {}
81 for element in self.element.iter():
82 accession = element.get("accession")
83 name = element.get("name")
84 if accession is not None:
85 self.accessions[name] = accession
86 if "profile spectrum" in self.accessions.keys():
87 self._profile = True
88
89 def get_element_by_name(self, name):
90 """
91 Get element from the original tree by it's unit name.
92
93 Arguments:
94 name (str): unit name of the mzml element.
95
96 Keyword Arguments:
97 obo_version (str, optional): obo version number.
98
99 """
100 iterator = self.element.iter()
101 return_ele = None
102 for ele in iterator:
103 if ele.get("name", default=None) == name:
104 return_ele = ele
105 break
106 return return_ele
107
108 def get_element_by_path(self, hooks):
109 """
110 Find elements in spectrum by its path.
111
112 Arguments:
113 hooks (list): list of parent elements for the target element.
114
115 Returns:
116 elements (list): list of XML objects
117 found in the path
118
119 Example:
120
121 To access cvParam in scanWindow tag:
122
123 >>> spec.get_element_by_path(['scanList', 'scan', 'scanWindowList',
124 ... 'scanWindow', 'cvParam'])
125
126 """
127 return_ele = None
128 if len(hooks) > 0:
129 path_array = ["."]
130 for hook in hooks:
131 path_array.append("{ns}{hook}".format(ns=self.ns, hook=hook))
132 path = "/".join(path_array)
133 return_ele = self.element.findall(path)
134
135 return return_ele
136
137 def _register(self, decoded_tuple):
138 d_type, array = decoded_tuple
139 if d_type == "mz":
140 self._mz = array
141 elif d_type == "i":
142 self._i = array
143 elif d_type == "time":
144 self._time = array
145 else:
146 raise Exception("Unknown data Type ({0})".format(d_type))
147
148 def _get_encoding_parameters(self, array_type):
149 """
150 Find the correct parameter for decoding and return them as tuple.
151
152 Arguments:
153 array_type (str): data type of the array, e.g. m/z, time or
154 intensity
155 Returns:
156 data (str) : encoded data
157 comp (str) : compression method
158 d_type (str) : data type
159 d_array_length (str) : length of the data array
160 """
161 numpress_encoding = False
162
163 b_data_string = "./{ns}binaryDataArrayList/{ns}binaryDataArray/{ns}cvParam[@name='{name}']/..".format(
164 ns=self.ns, name=array_type
165 )
166 float_type_string = "./{ns}cvParam[@accession='{Acc}']"
167
168 b_data_array = self.element.find(b_data_string)
169 if not b_data_array:
170 # non-standard data array
171 b_data_string = "./{ns}binaryDataArrayList/{ns}binaryDataArray/{ns}cvParam[@value='{value}']/..".format(
172 ns=self.ns, value=array_type
173 )
174 b_data_array = self.element.find(b_data_string)
175
176 comp = []
177 if b_data_array:
178 for cvParam in b_data_array.iterfind("./{ns}cvParam".format(ns=self.ns)):
179 if "compression" in cvParam.get("name"):
180 if "numpress" in cvParam.get("name").lower():
181 numpress_encoding = True
182 comp.append(cvParam.get("name"))
183 d_array_length = self.element.get("defaultArrayLength")
184 if not numpress_encoding:
185 try:
186 # 32-bit float
187 d_type = b_data_array.find(
188 float_type_string.format(
189 ns=self.ns,
190 Acc=self.obo_translator["32-bit float"]["id"],
191 )
192 ).get("name")
193 except:
194 try:
195 # 64-bit Float
196 d_type = b_data_array.find(
197 float_type_string.format(
198 ns=self.ns,
199 Acc=self.obo_translator["64-bit float"]["id"],
200 )
201 ).get("name")
202 except:
203 try:
204 # 32-bit integer
205 d_type = b_data_array.find(
206 float_type_string.format(
207 ns=self.ns,
208 Acc=self.obo_translator["32-bit integer"]["id"],
209 )
210 ).get("name")
211 except:
212 try:
213 # 64-bit integer
214 d_type = b_data_array.find(
215 float_type_string.format(
216 ns=self.ns,
217 Acc=self.obo_translator["64-bit integer"]["id"],
218 )
219 ).get("name")
220 except:
221 # null-terminated ASCII string
222 d_type = b_data_array.find(
223 float_type_string.format(
224 ns=self.ns,
225 Acc=self.obo_translator[
226 "null-terminated ASCII string"
227 ]["id"],
228 )
229 ).get("name")
230 else:
231 # compression is numpress, dont need data type here
232 d_type = None
233 data = b_data_array.find("./{ns}binary".format(ns=self.ns))
234 if data is not None:
235 data = data.text
236 else:
237 data = None
238 d_array_length = 0
239 d_type = "64-bit float"
240 if data is not None:
241 data = data.encode("utf-8")
242 else:
243 data = ""
244 return (data, d_array_length, d_type, comp)
245
246 @property
247 def measured_precision(self):
248 """
249 Set the measured and internal precision.
250
251 Returns:
252 value (float): measured Precision (e.g. 5e-6)
253 """
254 return self._measured_precision
255
256 @measured_precision.setter
257 def measured_precision(self, value):
258 self._measured_precision = value
259 self.internal_precision = int(round(50000.0 / (value * 1e6)))
260 return
261
262 def _decode_to_numpy(self, data, d_array_length, data_type, comp):
263 """
264 Decode the b64 encoded and packed strings from data as numpy arrays.
265
266 Returns:
267 data (np.ndarray): Returns the unpacked data as a tuple. Returns an
268 empty list if there is no raw data or raises an
269 exception if data could not be decoded.
270
271 d_array_length just for compatibility
272 """
273 out_data = b64dec(data)
274 if len(out_data) != 0:
275 if "zlib" in comp or "zlib compression" in comp:
276 out_data = zlib.decompress(out_data)
277 if (
278 "ms-np-linear" in comp
279 or "ms-np-pic" in comp
280 or "ms-np-slof" in comp
281 or "MS-Numpress linear prediction compression" in comp
282 or "MS-Numpress short logged float compression" in comp
283 ):
284 out_data = self._decodeNumpress_to_array(out_data, comp)
285 if data_type == "32-bit float":
286 # one character code may be sufficient too (f)
287 f_type = np.float32
288 out_data = np.frombuffer(out_data, f_type)
289 elif data_type == "64-bit float":
290 # one character code may be sufficient too (d)
291 f_type = np.float64
292 out_data = np.frombuffer(out_data, f_type)
293 elif data_type == "32-bit integer":
294 # one character code may be sufficient too (i)
295 i_type = np.int32
296 out_data = np.frombuffer(out_data, i_type)
297 elif data_type == "64-bit integer":
298 # one character code may be sufficient too (l)
299 i_type = np.int64
300 out_data = np.frombuffer(out_data, i_type)
301 # TODO elif data_type == "null-terminated ASCII string":
302 else:
303 raise ValueError(f"Unsupported data type: {data_type}")
304 else:
305 out_data = np.array([])
306 return out_data
307
308 def _decode_to_tuple(self, data, d_array_length, float_type, comp):
309 """
310 Decode b64 encoded and packed strings.
311
312 Returns:
313 data (tuple): Returns the unpacked data as a tuple.
314 Returns an empty list if there is no raw data or
315 raises an exception if data could not be decoded.
316 """
317 dec_data = b64dec(data)
318 if len(dec_data) != 0:
319 if "zlib" in comp or "zlib compression" in comp:
320 dec_data = zlib.decompress(dec_data)
321 if set(["ms-np-linear", "ms-np-pic", "ms-np-slof"]) & set(comp):
322 self._decodeNumpress(data, comp)
323 # else:
324 # print(
325 # 'New data compression ({0}) detected, cant decompress'.format(
326 # comp
327 # )
328 # )
329 # sys.exit(1)
330 if float_type == "32-bit float":
331 f_type = "f"
332 elif float_type == "64-bit float":
333 f_type = "d"
334 fmt = "{endian}{array_length}{float_type}".format(
335 endian="<", array_length=d_array_length, float_type=f_type
336 )
337 ret_data = unpack(fmt, dec_data)
338 else:
339 ret_data = []
340 return ret_data
341
342 def _decodeNumpress_to_array(self, data, compression):
343 """
344 Decode golomb-rice encoded data (aka numpress encoded data).
345
346 Arguments:
347 data (str) : Encoded data string
348 compression (str) : Decompression algorithm to be used
349 (valid are 'ms-np-linear', 'ms-np-pic', 'ms-np-slof')
350
351 Returns:
352 array (list): Returns the unpacked data as an array of floats.
353
354 """
355 result = []
356 comp_ms_tags = [self.calling_instance.OT[comp]["id"] for comp in compression]
357 data = np.frombuffer(data, dtype=np.uint8)
358 if "MS:1002312" in comp_ms_tags:
359 result = MSDecoder.decode_linear(data)
360 elif "MS:1002313" in comp_ms_tags:
361 result = MSDecoder.decode_pic(data)
362 elif "MS:1002314" in comp_ms_tags:
363 result = MSDecoder.decode_slof(data)
364 return result
365
366 def _median(self, data):
367 """
368 Compute median.
369
370 Arguments:
371 data (list): list of numeric values
372
373 Returns:
374 median (float): median of the input data
375 """
376 return np.median(data)
377
378 def to_string(self, encoding="latin-1", method="xml"):
379 """
380 Return string representation of the xml element the
381 spectrum was initialized with.
382
383 Keyword Arguments:
384 encoding (str) : text encoding of the returned string.\n
385 Default is latin-1.
386 method (str) : text format of the returned string.\n
387 Default is xml, alternatives are html and text.
388
389 Returns:
390 element (str) : xml string representation of the spectrum.
391 """
392 return ElementTree.tostring(self.element, encoding=encoding, method=method)
393
394
395 class Spectrum(MS_Spectrum):
396 """
397 Spectrum class which inherits from class :py:attr:`pymzml.spec.MS_Spectrum`
398
399 Arguments:
400 element (xml.etree.ElementTree.Element): spectrum as xml element
401
402 Keyword Arguments:
403 measured_precision (float): in ppm, i.e. 5e-6 equals to 5 ppm.
404
405 """
406
407 def __init__(
408 self,
409 element=ElementTree.Element(""),
410 measured_precision=5e-6,
411 *,
412 obo_version=None,
413 ):
414 __slots__ = [
415 "_centroided_peaks",
416 "_centroided_peaks_sorted_by_i",
417 "_deconvoluted_peaks",
418 "_extreme_values",
419 "_i",
420 "_ID",
421 "_id_dict",
422 "_index",
423 "_measured_precision",
424 "_peaks",
425 "_profile",
426 "_reprofiled_peaks",
427 "_t_mass_set",
428 "_t_mz_set",
429 "_time",
430 "_transformed_mass_with_error",
431 "_transformed_mz_with_error",
432 "_transformed_peaks" "calling_instance" "element",
433 "internal_precision" "noise_level_estimate",
434 "selected_precursors",
435 ]
436
437 self._centroided_peaks = None
438 self._centroided_peaks_sorted_by_i = None
439 self._extreme_values = None
440 self._i = None
441 self._ID = None
442 self._id_dict = None
443 self._index = None
444 self._ms_level = None
445 self._mz = None
446 self._peak_dict = {
447 "raw": None,
448 "centroided": None,
449 "reprofiled": None,
450 "deconvoluted": None,
451 }
452 self._selected_precursors = None
453 self._profile = None
454 self.reprofiled = False
455 self._reprofiled_peaks = None
456 self._scan_time = None
457 self._scan_time_unit = None
458 self._scan_time_in_minutes = None
459 self._t_mass_set = None
460 self._t_mz_set = None
461 self._TIC = None
462 self._precursors = None
463 self._transformed_mass_with_error = None
464 self._transformed_mz_with_error = None
465 self._transformed_peaks = None
466 self.obo_translator = OboTranslator.from_cache(obo_version)
467 self.element = element
468 self.measured_precision = measured_precision
469 self.noise_level_estimate = {}
470
471 self.ns = ""
472 if self.element:
473 self.ns = (
474 re.match(r"\{.*\}", element.tag).group(0)
475 if re.match(r"\{.*\}", element.tag)
476 else ""
477 )
478
479 self._decode = self._decode_to_numpy
480 self._array = np.array
481 self._ms_deisotop_warning_printed = False
482
483 def __del__(self):
484 """
485 Clear self.element to limit RAM usage
486 """
487 if self.element:
488 self.element.clear()
489
490 def __add__(self, other_spec):
491 """
492 Adds two pymzml spectra
493
494 Arguments:
495 other_spec (Spectrum): spectrum to add to the current spectrum
496
497 Returns:
498 self (Spectrum): reference to the edited spectrum
499
500 Example:
501
502 >>> import pymzml
503 >>> s = pymzml.spec.Spectrum( measuredPrescision = 20e-6 )
504 >>> file_to_read = "../mzML_example_files/xy.mzML.gz"
505 >>> run = pymzml.run.Reader(
506 ... file_to_read ,
507 ... MS1_Precision = 5e-6 ,
508 ... MSn_Precision = 20e-6
509 ... )
510 >>> for spec in run:
511 ... s += spec
512
513 """
514 assert isinstance(other_spec, Spectrum)
515 if self._peak_dict["reprofiled"] is None:
516 reprofiled = self._reprofile_Peaks()
517 self.set_peaks(reprofiled, "reprofiled")
518 if other_spec._peak_dict["reprofiled"] is None:
519 other_spec.set_peaks(other_spec._reprofile_Peaks(), "reprofiled")
520 for mz, i in other_spec.peaks("reprofiled"):
521 self._peak_dict["reprofiled"][mz] += i
522 return self
523
524 def __sub__(self, other_spec):
525 """
526 Subtracts two pymzml spectra.
527
528 Arguments:
529 other_spec (spec.Spectrum): spectrum to subtract from the current
530 spectrum
531
532 Returns:
533 self (spec.Spectrum): returns self after other_spec was subtracted
534 """
535 assert isinstance(other_spec, Spectrum)
536 if self._peak_dict["reprofiled"] is None:
537 self.set_peaks(self._reprofile_Peaks(), "reprofiled")
538 if other_spec._peak_dict["reprofiled"] is None:
539 other_spec.set_peaks(other_spec._reprofile_Peaks(), "reprofiled")
540 for mz, i in other_spec.peaks("reprofiled"):
541 self._peak_dict["reprofiled"][mz] -= i
542 self.set_peaks(None, "centroided")
543 self.set_peaks(None, "raw")
544 return self
545
546 def __mul__(self, value):
547 """
548 Multiplies each intensity with a float, i.e. scales the spectrum.
549
550 Arguments:
551 value (int, float): value to multiply the intensities with
552
553 Returns:
554 self (spec.Spectrum): returns self after intensities were scaled
555 by value
556 """
557 assert isinstance(value, (int, float))
558 if self._peak_dict["raw"] is not None:
559 self.set_peaks(
560 np.column_stack(
561 (self.peaks("raw")[:, 0], self.peaks("raw")[:, 1] * value)
562 ),
563 "raw",
564 )
565 if self._peak_dict["centroided"] is not None:
566 self.set_peaks(
567 np.column_stack(
568 (self.centroided_peaks[:, 0], self.centroided_peaks[:, 1] * value)
569 ),
570 "centroided",
571 )
572 if self._peak_dict["reprofiled"] is not None:
573 for mz in self._peak_dict["reprofiled"].keys():
574 self._peak_dict["reprofiled"][mz] *= float(value)
575 return self
576
577 def __truediv__(self, value):
578 """
579 Divides each intensity by a float, i.e. scales the spectrum.
580
581 Arguments:
582 value (int, float): value to divide the intensities by
583
584 Returns:
585 self (spec.Spectrum): returns self after intensities were scaled
586 by value.
587 """
588 if self._peak_dict["reprofiled"] is not None:
589 for mz, i in self.peaks("reprofiled"):
590 self._peak_dict["reprofiled"][mz] /= float(value)
591 if self._peak_dict["raw"] is not None:
592 if len(self._peak_dict["raw"]) != 0:
593 self.set_peaks(
594 np.column_stack(
595 (
596 self.peaks("raw")[:, 0],
597 self.peaks("raw")[:, 1] / float(value),
598 )
599 ),
600 "raw",
601 )
602 if self._peak_dict["centroided"] is not None:
603 peaks = self._peak_dict["centroided"]
604 scaled_peaks = peaks[:, 1] / value
605 peaks[:, 1] = scaled_peaks
606 self._peak_dict["centroided"] = peaks
607 return self
608
609 def __div__(self, value):
610 """
611 Integer division is the same as __truediv__ for this class
612 """
613 return self.__truediv__(value)
614
615 def __repr__(self):
616 """
617 Returns representative string for a spectrum object class
618 """
619 return "<__main__.Spectrum object with native ID {0} at {1}>".format(
620 self.ID, hex(id(self))
621 )
622
623 def __str__(self):
624 """
625 Returns representative string for a spectrum object class
626 """
627 return "<__main__.Spectrum object with native ID {0} at {1}>".format(
628 self.ID, hex(id(self))
629 )
630
631 @lru_cache()
632 def __getitem__(self, accession):
633 """
634 Access spectrum XML information by tag name
635
636 Args:
637 accession(str): name of the XML tag
638
639 Returns:
640 value (float or str): value of the XML tag
641 """
642 # TODO implement cache???
643 if accession == "id":
644 return_val = self.ID
645 else:
646 if not accession.startswith("MS:"):
647 try:
648 accession = self.obo_translator[accession]["id"]
649 except TypeError:
650 accession = "---"
651 search_string = './/*[@accession="{0}"]'.format(accession)
652 elements = []
653 for x in self.element.iterfind(search_string):
654 val = x.attrib.get("value", "")
655 try:
656 val = float(val)
657 except:
658 pass
659 elements.append(val)
660
661 if len(elements) == 0:
662 return_val = None
663 elif len(elements) == 1:
664 return_val = elements[0]
665 else:
666 return_val = elements
667 if return_val == "":
668 return_val = True
669 return return_val
670
671 def get(self, acc, default=None):
672 """Mimic dicts get function.
673
674 Args:
675 acc (str): accession or obo tag to return
676 default (None, optional): default value if acc is not found
677 """
678 val = self[acc]
679 if val is None:
680 val = default
681 return val
682
683 def __contains__(self, value):
684 """Check if MS tag or name can be found in spectrum.
685
686 Args:
687 value (str): MS tag or OBO name
688
689 Returns:
690 bool
691 """
692 r = False
693 if self[value] is not None:
694 r = True
695 return r
696
697 @property
698 def measured_precision(self):
699 """
700 Sets the measured and internal precision
701
702 Returns:
703 value (float): measured precision (e.g. 5e-6)
704 """
705 return self._measured_precision
706
707 @measured_precision.setter
708 def measured_precision(self, value):
709 self._measured_precision = value
710 self.internal_precision = int(round(50000.0 / (value * 1e6)))
711 return
712
713 @property
714 def t_mz_set(self):
715 """
716 Creates a set of integers out of transformed m/z values
717 (including all values in the defined imprecision).
718 This is used to accelerate has_peak function and similar.
719
720 Returns:
721 t_mz_set (set): set of transformed m/z values
722 """
723 if self._t_mz_set is None:
724 self._t_mz_set = set()
725 for mz, i in self.peaks("centroided"):
726 self._t_mz_set |= set(
727 range(
728 int(
729 round(
730 (mz - (mz * self.measured_precision))
731 * self.internal_precision
732 )
733 ),
734 int(
735 round(
736 (mz + (mz * self.measured_precision))
737 * self.internal_precision
738 )
739 )
740 + 1,
741 )
742 )
743 return self._t_mz_set
744
745 @property
746 def transformed_mz_with_error(self):
747 """
748 Returns transformed m/z value with error
749
750 Returns:
751 tmz values (dict): Transformed m/z values in dictionary\n
752 {\n
753 m/z_with_error : [(m/z,intensity), ...], ...\n
754 }\n
755 """
756 if self._transformed_mz_with_error is None:
757 self._transformed_mz_with_error = ddict(list)
758 for mz, i in self.peaks("centroided"):
759 for t_mz_with_error in range(
760 int(
761 round(
762 (mz - (mz * self.measured_precision))
763 * self.internal_precision
764 )
765 ),
766 int(
767 round(
768 (mz + (mz * self.measured_precision))
769 * self.internal_precision
770 )
771 )
772 + 1,
773 ):
774 self._transformed_mz_with_error[t_mz_with_error].append((mz, i))
775 return self._transformed_mz_with_error
776
777 @property
778 def transformed_peaks(self):
779 """
780 m/z value is multiplied by the internal precision.
781
782 Returns:
783 Transformed peaks (list): Returns a list of peaks (tuples of mz and
784 intensity).
785 Float m/z values are adjusted by the internal precision
786 to integers.
787 """
788 if self._transformed_peaks is None:
789 self._transformed_peaks = [
790 (self.transform_mz(mz), i) for mz, i in self.peaks("centroided")
791 ]
792 return self._transformed_peaks
793
794 @property
795 def TIC(self):
796 """
797 Property to access the total ion current for this spectrum.
798
799 Returns:
800 TIC (float): Total Ion Current of the spectrum.
801 """
802 if self._TIC is None:
803 self._TIC = float(
804 self.element.find(
805 "./{ns}cvParam[@accession='MS:1000285']".format(ns=self.ns)
806 ).get("value")
807 ) # put hardcoded MS tags in minimum.py???
808 return self._TIC
809
810 @property
811 def ID(self):
812 """
813 Access the native id (last number in the id attribute) of the spectrum.
814
815 Returns:
816 ID (str): native ID of the spectrum
817 """
818 if self._ID is None:
819 if self.element:
820 match = regex_patterns.SPECTRUM_ID_PATTERN.search(
821 self.element.get("id", None)
822 )
823 if match:
824 try:
825 self._ID = int(match.group(1))
826 except ValueError:
827 self._ID = match.group(1)
828 else:
829 self._ID = self.element.get("id")
830 return self._ID
831
832 @property
833 def id_dict(self):
834 """
835 Access to all entries stored the id attribute of a spectrum.
836
837 Returns:
838 id_dict (dict): key value pairs for all entries in id attribute of a spectrum
839 """
840 if self._id_dict is None:
841 tuples = []
842 match = regex_patterns.SPECTRUM_PATTERN3.match(self.element.attrib["id"])
843 if match is not None:
844 captures = match.captures(1)
845 for element in captures:
846 k, v = element.strip().split("=")
847 v = int(v)
848 tuples.append([k, v])
849 self._id_dict = dict(tuples)
850 else:
851 self._id_dict = {}
852 return self._id_dict
853
854 @property
855 def index(self):
856 """
857 Access the index of the spectrum.
858
859 Returns:
860 index (int): index of the spectrum
861
862 Note:
863 This does not necessarily correspond to the native spectrum ID
864 """
865 if self._index is None:
866 self._index = self.element.get("index")
867 try:
868 self._index = int(self._index)
869 except:
870 pass
871 return self._index
872
873 @property
874 def ms_level(self):
875 """
876 Property to access the ms level.
877
878 Returns:
879 ms_level (int):
880 """
881 if self._ms_level is None:
882 sub_element = self.element.find(
883 ".//{ns}cvParam[@accession='MS:1000511']".format(ns=self.ns)
884 )
885 if sub_element is not None:
886 self._ms_level = int(
887 sub_element.get("value")
888 ) # put hardcoded MS tags in minimum.py???
889 return self._ms_level
890
891 @property
892 def scan_time(self):
893 """
894 Property to access the retention time and retention time unit.
895 Please note, that we do not assume the retention time unit,
896 if it is not correctly defined in the mzML.
897 It is set to 'unicorns' in this case.
898
899 Returns:
900 scan_time (float):
901 scan_time_unit (str):
902 """
903 if self._scan_time is None or self._scan_time_unit is None:
904 scan_time_ele = self.element.find(
905 ".//*[@accession='MS:1000016']".format(ns=self.ns)
906 )
907 if scan_time_ele is not None:
908 self._scan_time = float(scan_time_ele.attrib.get("value"))
909 self._scan_time_unit = scan_time_ele.get("unitName", "unicorns")
910 return self._scan_time, self._scan_time_unit
911
912 # @property
913 def scan_time_in_minutes(self):
914 """
915 Property to access the retention time in minutes.
916 If the retention time unit is defined within the mzML,
917 the retention time is converted into minutes and returned
918 without the unit.
919
920 Returns:
921 scan_time (float):
922 """
923 if self._scan_time_in_minutes is None:
924 self._scan_time, time_unit = self.scan_time
925 if self._scan_time_unit.lower() == "millisecond":
926 self._scan_time_in_minutes = self._scan_time / 1000.0 / 60.0
927 if self._scan_time_unit.lower() == "second":
928 self._scan_time_in_minutes = self._scan_time / 60.0
929 elif self._scan_time_unit.lower() == "minute":
930 self._scan_time_in_minutes = self._scan_time
931 elif self._scan_time_unit.lower() == "hour":
932 self._scan_time_in_minutes = self._scan_time * 60.0
933 else:
934 raise Exception("Time unit '{0}' unknown".format(self._scan_time_unit))
935 return self._scan_time_in_minutes
936
937 @property
938 def selected_precursors(self):
939 """
940 Property to access the selected precursors of a MS2 spectrum. Returns
941 a list of dicts containing the precursors mz and, if available intensity
942 and charge for each precursor.
943
944 Returns:
945 selected_precursors (list):
946 """
947 if self._selected_precursors is None:
948 selected_precursor_mzs = self.element.findall(
949 ".//*[@accession='MS:1000744']"
950 )
951 selected_precursor_is = self.element.findall(
952 ".//*[@accession='MS:1000042']"
953 )
954 selected_precursor_cs = self.element.findall(
955 ".//*[@accession='MS:1000041']"
956 )
957 precursors = self.element.findall(
958 "./{ns}precursorList/{ns}precursor".format(ns=self.ns)
959 )
960
961 mz_values = []
962 i_values = []
963 charges = []
964 ids = []
965 for obj in selected_precursor_mzs:
966 mz = obj.get("value")
967 mz_values.append(float(mz))
968 for obj in selected_precursor_is:
969 i = obj.get("value")
970 i_values.append(float(i))
971 for obj in selected_precursor_cs:
972 c = obj.get("value")
973 charges.append(int(c))
974 for prec in precursors:
975 spec_ref = prec.get("spectrumRef")
976 if spec_ref is not None:
977 ids.append(
978 regex_patterns.SPECTRUM_ID_PATTERN.search(spec_ref).group(1)
979 )
980 else:
981 ids.append(None)
982 # ids.append()
983 self._selected_precursors = []
984 for pos, mz in enumerate(mz_values):
985 dict_2_save = {"mz": mz}
986 for key, list_of_values in [
987 ("i", i_values),
988 ("charge", charges),
989 ("precursor id", ids),
990 ("element", precursors),
991 ]:
992 try:
993 dict_2_save[key] = list_of_values[pos]
994 except:
995 continue
996 self._selected_precursors.append(dict_2_save)
997
998 return self._selected_precursors
999
1000 @property
1001 def precursors(self):
1002 """
1003 List the precursor information of this spectrum, if available.
1004 Returns:
1005 precursor(list): list of precursor ids for this spectrum.
1006 """
1007 self.deprecation_warning(sys._getframe().f_code.co_name)
1008 if not self._precursors:
1009 precursors = self.element.findall(
1010 "./{ns}precursorList/{ns}precursor".format(ns=self.ns)
1011 )
1012 self._precursors = []
1013 for prec in precursors:
1014 spec_ref = prec.get("spectrumRef")
1015 self._precursors.append(
1016 regex_patterns.SPECTRUM_ID_PATTERN.search(spec_ref).group(1)
1017 )
1018 return self._precursors
1019
1020 def remove_precursor_peak(self):
1021 peaks = self.peaks("centroided")
1022 for precursor in self.selected_precursors:
1023 mz = precursor["mz"]
1024 hp = self.has_peak(mz)
1025 if hp:
1026 for p in hp:
1027 peaks = peaks[(peaks[:, 0] != p[0])]
1028 self.set_peaks(peaks, "centroided")
1029 self.set_peaks(peaks, "raw")
1030 return peaks
1031
1032 @property
1033 def mz(self):
1034 """
1035 Returns the list of m/z values. If the m/z values are encoded, the
1036 function :func:`~spec.MS_Spectrum._decode` is used to decode the encoded data.
1037 The mz property can also be set, e.g. for theoretical data.
1038 However, it is recommended to use the peaks property to set mz and
1039 intensity tuples at same time.
1040
1041 Returns:
1042 mz (list): list of m/z values of spectrum.
1043 """
1044 if self._mz is None:
1045 params = self._get_encoding_parameters("m/z array")
1046 self._mz = self._decode(*params)
1047 return self._mz
1048
1049 @mz.setter
1050 def mz(self, mz_list):
1051 """"""
1052 mz_list = np.array(mz_list, dtype=np.float64)
1053 mz_list.sort()
1054 self._mz = mz_list
1055
1056 @property
1057 def i(self):
1058 """
1059 Returns the list of the intensity values.
1060 If the intensity values are encoded, the function :func:`~spec.MS_Spectrum._decode`
1061 is used to decode the encoded data.\n
1062 The i property can also be set, e.g. for theoretical data. However,
1063 it is recommended to use the peaks property to set mz and intensity
1064 tuples at same time.
1065
1066 Returns
1067 i (list): list of intensity values from the analyzed spectrum
1068 """
1069 if self._i is None:
1070 params = self._get_encoding_parameters("intensity array")
1071 self._i = self._decode(*params)
1072 return self._i
1073
1074 @i.setter
1075 def i(self, intensity_list):
1076 self._i = intensity_list
1077
1078 def peaks(self, peak_type):
1079 """
1080 Decode and return a list of mz/i tuples.
1081
1082 Args:
1083 peak_type(str): currently supported types are:
1084 raw, centroided and reprofiled
1085
1086 Returns:
1087 peaks (list or ndarray): list or numpy array of mz/i tuples or arrays
1088 """
1089 if self._peak_dict[peak_type] is None:
1090 if self._peak_dict["raw"] is None:
1091 mz_params = self._get_encoding_parameters("m/z array")
1092 i_params = self._get_encoding_parameters("intensity array")
1093 mz = self._decode(*mz_params)
1094 i = self._decode(*i_params)
1095 arr = np.stack((mz, i), axis=-1)
1096 self._peak_dict[peak_type] = arr
1097 if peak_type == "raw":
1098 pass
1099 elif peak_type == "centroided":
1100 self._peak_dict["centroided"] = self._centroid_peaks()
1101 elif peak_type == "reprofiled":
1102 self._peak_dict["reprofiled"] = self._reprofile_Peaks()
1103 elif peak_type == "deconvoluted":
1104 self._peak_dict["deconvoluted"] = self._deconvolute_peaks()
1105 else:
1106 raise KeyError
1107
1108 if not isinstance(self._peak_dict[peak_type], np.ndarray):
1109 peaks = self._array(self._peak_dict[peak_type])
1110 else:
1111 peaks = self._peak_dict[peak_type]
1112 if peak_type == "reprofiled":
1113 peaks = list(self._peak_dict[peak_type].items())
1114 peaks.sort(key=itemgetter(0))
1115 return peaks
1116
1117 @lru_cache()
1118 def get_array(self, arr_name):
1119 array_params = self._get_encoding_parameters(arr_name)
1120 array = self._decode(*array_params)
1121 if len(array) == 0:
1122 array = None
1123 _ = self.get_all_arrays_in_spec(not_found_array=arr_name)
1124 return array
1125
1126 def get_tims_tof_ion_mobility(
1127 self, array_name="mean inverse reduced ion mobility array"
1128 ):
1129 arr = self.get_array(array_name)
1130 if arr is None:
1131 _ = self.get_all_arrays_in_spec(not_found_array=array_name)
1132 return arr
1133
1134 def get_all_arrays_in_spec(self, not_found_array=None):
1135 b_data_string = "./{ns}binaryDataArrayList/{ns}binaryDataArray/{ns}cvParam[@unitCvRef='MS']".format(
1136 ns=self.ns
1137 )
1138 b_data_arrays = self.element.findall(b_data_string)
1139 array_names = [arr.attrib["name"] for arr in b_data_arrays]
1140 formatted_array_names = []
1141 for name in array_names:
1142 formatted_array_names.append("\t- {name}".format(name=name))
1143 if not_found_array is not None:
1144 print(
1145 "Requested array ({not_found_array}) not found.\nAvailable arrays are:".format(
1146 not_found_array=not_found_array
1147 )
1148 )
1149 print("\n".join(formatted_array_names))
1150 return array_names
1151
1152 def _deconvolute_peaks(self, *args, **kwargs):
1153 if DECON_DEP is True:
1154 peaks = self.peaks("centroided")
1155 # pack peak matrix into expected structure
1156 peaks = [simple_peak(p[0], p[1], 0.01) for p in peaks]
1157 decon_result = deconvolute_peaks(peaks, *args, **kwargs)
1158 dpeaks = decon_result.peak_set
1159 # pack deconvoluted peak list into matrix structure
1160 dpeaks_mat = np.zeros((len(dpeaks), 3), dtype=float)
1161 for i, dp in enumerate(dpeaks):
1162 dpeaks_mat[i, :] = dp.neutral_mass, dp.intensity, dp.charge
1163 return dpeaks_mat
1164 else:
1165 if self._ms_deisotop_warning_printed is False:
1166 print(
1167 "ms_deisotope is missing, please install using pip install ms_deisotope"
1168 )
1169 self._ms_deisotop_warning_printed = True
1170
1171 def set_peaks(self, peaks, peak_type):
1172 """
1173 Assign a custom peak array of type peak_type
1174
1175 Args:
1176 peaks(list or ndarray): list or array of mz/i values
1177 peak_type(str): Either raw, centroided or reprofiled
1178
1179 """
1180 peak_type = peak_type.lower()
1181 # reset after changing peaks
1182 self._transformed_mass_with_error = None
1183 self._transformed_mz_with_error = None
1184 if peak_type == "raw":
1185 # if not isinstance(peaks, np.ndarray):
1186 # peaks = np.array(peaks)
1187 self._peak_dict["raw"] = peaks
1188 try:
1189 self._mz = self.peaks("raw")[:, 0]
1190 self._i = self.peaks("raw")[:, 1]
1191 except IndexError:
1192 self._mz = np.array([])
1193 self._i = np.array([])
1194
1195 elif peak_type == "centroided":
1196 # if not isinstance(peaks, np.ndarray):
1197 # peaks = np.array(peaks)
1198 self._peak_dict["centroided"] = peaks
1199 try:
1200 self._mz = self.peaks("raw")[:, 0]
1201 self._i = self.peaks("raw")[:, 1]
1202 except IndexError:
1203 self._mz = np.array([])
1204 self._i = np.array([])
1205
1206 elif peak_type == "reprofiled":
1207 try:
1208 self._peak_dict["reprofiled"] = peaks
1209 except TypeError:
1210 self._peak_dict["reprofiled"] = None
1211 elif peak_type == "deconvoluted":
1212 self._peak_dict["deconvoluted"] = peaks
1213 try:
1214 self._mz = self.peaks("raw")[:, 0]
1215 self._i = self.peaks("raw")[:, 1]
1216 except IndexError:
1217 self._mz = np.array([])
1218 else:
1219 raise Exception(
1220 "Peak type is not suppported\n"
1221 'Choose either "raw", "centroided" or "reprofiled"'
1222 )
1223
1224 def _centroid_peaks(self):
1225 """
1226 Perform a Gauss fit to centroid the peaks for the property
1227 centroided_peaks.
1228
1229 Returns:
1230 centroided_peaks (list): list of centroided m/z, i tuples
1231 """
1232
1233 try:
1234 profile_ot = self.obo_translator.name.get("profile spectrum", None)
1235 if profile_ot is None:
1236 profile_ot = self.obo_translator.name.get("profile mass spectrum", None)
1237 acc = profile_ot["id"]
1238 is_profile = (
1239 True
1240 if self.element.find(
1241 ".//*[@accession='{acc}']".format(ns=self.ns, acc=acc)
1242 )
1243 is not None
1244 else None
1245 )
1246
1247 except (TypeError, AttributeError) as e:
1248 # user creadted spectrum objects without xml and calling instance cant determine if they are reprofiled or not
1249 is_profile = None
1250
1251 if is_profile is not None or self.reprofiled: # check if spec is a profile spec
1252 tmp = []
1253 if self._peak_dict["reprofiled"] is not None:
1254 i_array = [i for mz, i in self.peaks("reprofiled")]
1255 mz_array = [mz for mz, i in self.peaks("reprofiled")]
1256 else:
1257 i_array = self.i
1258 mz_array = self.mz
1259 for pos, i in enumerate(i_array[:-1]):
1260 if pos <= 1:
1261 continue
1262 if 0 < i_array[pos - 1] < i > i_array[pos + 1] > 0:
1263 x1 = float(mz_array[pos - 1])
1264 y1 = float(i_array[pos - 1])
1265 x2 = float(mz_array[pos])
1266 y2 = float(i_array[pos])
1267 x3 = float(mz_array[pos + 1])
1268 y3 = float(i_array[pos + 1])
1269 if x2 - x1 > (x3 - x2) * 10 or (x2 - x1) * 10 < x3 - x2:
1270 continue
1271 if y3 == y1:
1272 y3 += 0.01 * y1
1273
1274 try:
1275 double_log = math.log(y2 / y1) / math.log(y3 / y1)
1276 mue = (double_log * (x1 * x1 - x3 * x3) - x1 * x1 + x2 * x2) / (
1277 2 * (x2 - x1) - 2 * double_log * (x3 - x1)
1278 )
1279 c_squarred = (
1280 x2 * x2 - x1 * x1 - 2 * x2 * mue + 2 * x1 * mue
1281 ) / (2 * math.log(y1 / y2))
1282 A = y1 * math.exp((x1 - mue) * (x1 - mue) / (2 * c_squarred))
1283 except ZeroDivisionError:
1284 continue
1285 tmp.append((mue, A))
1286 return tmp
1287 else:
1288 return self.peaks("raw")
1289
1290 def _reprofile_Peaks(self):
1291 """
1292 Performs reprofiling for property reprofiled_peaks.
1293
1294 Returns:
1295 reprofiled_peaks (list): list of reprofiled m/z, i tuples
1296 """
1297 tmp = ddict(int)
1298 for mz, i in self.peaks("centroided"):
1299 # Let the measured precision be 2 sigma of the signal width
1300 # When using normal distribution
1301 # FWHM = 2 sqt(2 * ln(2)) sigma = 2.3548 sigma
1302 s = mz * self.measured_precision * 2 # in before 2
1303 s2 = s * s
1304 floor = mz - 5.0 * s # Gauss curve +- 3 sigma
1305 ceil = mz + 5.0 * s
1306 ip = self.internal_precision / 4
1307 # more spacing, i.e. less points describing the gauss curve
1308 # -> faster adding
1309 for _ in range(int(round(floor * ip)), int(round(ceil * ip)) + 1):
1310 if _ % int(5) == 0:
1311 a = float(_) / float(ip)
1312 y = i * math.exp(-1 * ((mz - a) * (mz - a)) / (2 * s2))
1313 tmp[a] += y
1314 self.reprofiled = True
1315 self.set_peaks(None, "centroided")
1316 return tmp
1317
1318 def _mz_2_mass(self, mz, charge):
1319 """
1320 Calculate the uncharged mass for a given mz value
1321
1322 Arguments:
1323 mz (float) : m/z value
1324 charge(int) : charge
1325
1326 Returns:
1327 mass (float): Returns mass of a given m/z value
1328 """
1329 return (mz - PROTON) * charge
1330
1331 def _set_params_from_reference_group(self, ref_element):
1332 ref = self.element.find("{ns}referenceableParamGroupRef".format(ns=self.ns))
1333 if ref is not None:
1334 ref = ref.get("ref")
1335 ele = ref_element.find(".//*[@id='{ref}']".format(ref=ref, ns=self.ns))
1336 if ele is not None and ref == ele.get("id"):
1337 for param in ele.iter():
1338 self.element.append(ele)
1339 acc = param.get("accession")
1340
1341 # Public functions
1342
1343 def reduce(self, peak_type="raw", mz_range=(None, None)):
1344 """
1345 Remove all m/z values outside the given range.
1346
1347 Arguments:
1348 mz_range (tuple): tuple of min, max values
1349
1350 Returns:
1351 peaks (list): list of mz, i tuples in the given range.
1352 """
1353 arr = self.peaks(peak_type)
1354 peaks = arr[
1355 np.where(np.logical_and(arr[:, 0] >= mz_range[0], arr[:, 0] <= mz_range[1]))
1356 ]
1357 self.set_peaks(peaks, peak_type)
1358 return peaks
1359
1360 def remove_noise(
1361 self, mode="median", noise_level=None, signal_to_noise_threshold=1.0
1362 ):
1363 """
1364 Function to remove noise from peaks, centroided peaks and reprofiled
1365 peaks.
1366
1367 Keyword arguments:
1368 mode (str): define mode for removing noise. Default = "median"
1369 (other modes: "mean", "mad")
1370 noise_level (float): noise threshold
1371 signal_to_noise_threshold (float): S/N threshold for a peak to be accepted
1372
1373 Returns:
1374 reprofiled peaks (list): Returns a list with tuples of
1375 m/z-intensity pairs above the noise threshold
1376
1377 """
1378 # Thanks to JD Hogan for pointing it out!
1379 callPeaks = self.peaks("raw")
1380 # callcentPeaks = self.peaks("centroided")
1381 if noise_level is None:
1382 noise_level = self.estimated_noise_level(mode=mode)
1383 if len(self.peaks("centroided")) != 0:
1384 self._peak_dict["centroided"] = self.peaks("centroided")[
1385 self.peaks("centroided")[:, 1] / noise_level
1386 >= signal_to_noise_threshold
1387 ]
1388 if len(self.peaks("raw")) != 0:
1389 self._peak_dict["raw"] = self.peaks("raw")[
1390 self.peaks("raw")[:, 1] / noise_level >= signal_to_noise_threshold
1391 ]
1392 self._peak_dict["reprofiled"] = None
1393 return self
1394
1395 def estimated_noise_level(self, mode="median"):
1396 """
1397 Calculates noise threshold for function remove_noise.
1398
1399 Different modes are available. Default is 'median'
1400
1401 Keyword Arguments:
1402 mode (str): define mode for removing noise. Default = "median"
1403 (other modes: "mean", "mad")
1404
1405 Returns:
1406 noise_level (float): estimate noise threshold
1407
1408
1409 """
1410 if len(self.peaks("centroided")) == 0: # or is None?
1411 return 0
1412
1413 self.noise_level_estimate = {}
1414 if mode not in self.noise_level_estimate.keys():
1415 if mode == "median":
1416 self.noise_level_estimate["median"] = np.median(
1417 self.peaks("centroided")[:, 1]
1418 )
1419 elif mode == "mad":
1420 median = self.estimated_noise_level(mode="median")
1421 self.noise_level_estimate["mad"] = np.median(
1422 abs(self.peaks("centroided")[:, 1] - median)
1423 )
1424 elif mode == "mean":
1425 self.noise_level_estimate["mean"] = sum(
1426 self.peaks("centroided")[:, 1]
1427 ) / float(len(self.peaks("centroided")))
1428 else:
1429 print(
1430 "Do not understand noise level estimation method call with given mode: {0}".format(
1431 mode
1432 )
1433 )
1434 return_value = self.noise_level_estimate[mode]
1435 return return_value
1436
1437 def highest_peaks(self, n):
1438 """
1439 Function to retrieve the n-highest centroided peaks of the spectrum.
1440
1441 Arguments:
1442 n (int): number of highest peaks to return.
1443
1444 Returns:
1445 centroided peaks (list): list mz, i tupls with n-highest
1446
1447 Example:
1448
1449 >>> run = pymzml.run.Reader(
1450 ... "tests/data/example.mzML.gz",
1451 ... MS_precisions = {
1452 ... 1 : 5e-6,
1453 ... 2 : 20e-6
1454 ... }
1455 ... )
1456 >>> for spectrum in run:
1457 ... if spectrum.ms_level == 2:
1458 ... if spectrum.ID == 1770:
1459 ... for mz,i in spectrum.highest_peaks(5):
1460 ... print(mz, i)
1461
1462 """
1463 if self._centroided_peaks_sorted_by_i is None:
1464 self._centroided_peaks_sorted_by_i = self.peaks("centroided")[
1465 self.peaks("centroided")[:, 1].argsort()
1466 ]
1467 return self._centroided_peaks_sorted_by_i[-n:]
1468
1469 def ppm2abs(self, value, ppm_value, direction=1, factor=1):
1470 """
1471 Returns the value plus (or minus, dependent on direction) the
1472 error (measured precision ) for this value.
1473
1474 Arguments:
1475 value (float) : m/z value
1476 ppm_value (int) : ppm value
1477
1478 Keyword Arguments:
1479 direction (int) : plus or minus the considered m/z value.
1480 The argument *direction* should be 1 or -1
1481 factor (int) : multiplication factor for the imprecision.
1482 The argument *factor* should be bigger than 0
1483
1484 Returns:
1485 imprecision (float): imprecision for the given value
1486
1487 """
1488 result = value + (value * (ppm_value * factor)) * direction
1489 return result
1490
1491 def extreme_values(self, key):
1492 """
1493 Find extreme values, minimal and maximum m/z and intensity
1494
1495 Arguments:
1496 key (str) : m/z : "mz" or intensity : "i"
1497
1498 Returns:
1499 extrema (tuple) : tuple of minimal and maximum m/z or intensity
1500
1501 """
1502 available_extreme_values = ["mz", "i"]
1503 if key not in available_extreme_values:
1504 print(
1505 "Do not understand extreme request: '{0}'; available values are: {1}".format(
1506 key, available_extreme_values
1507 )
1508 )
1509 exit()
1510 if self._extreme_values is None:
1511 self._extreme_values = {}
1512 try:
1513 if key == "mz":
1514 all_mz_values = self.peaks("raw")[:, 0]
1515 self._extreme_values["mz"] = (all_mz_values.min(), all_mz_values.max())
1516 self._extreme_values["mz"] = (
1517 self.peaks("raw")[:, 0].min(),
1518 self.peaks("raw")[:, 0].max(),
1519 )
1520 else:
1521 all_i_values = self.peaks("raw")[:, 1]
1522 self._extreme_values["i"] = (
1523 self.peaks("raw")[:, 1].min(),
1524 self.peaks("raw")[:, 1].max(),
1525 )
1526 except ValueError:
1527 # emtpy spectrum
1528 self._extreme_values[key] = ()
1529 return self._extreme_values[key]
1530
1531 def has_peak(self, mz2find):
1532 """
1533 Checks if a Spectrum has a certain peak.
1534 Requires a m/z value as input and returns a list of peaks if the m/z
1535 value is found in the spectrum, otherwise ``[]`` is returned.
1536 Every peak is a tuple of m/z and intensity.
1537
1538 Note:
1539 Multiple peaks may be found, depending on the defined precisions
1540
1541 Arguments:
1542 mz2find (float): m/z value which should be found
1543
1544 Returns:
1545 peaks (list): list of m/z, i tuples
1546
1547 Example:
1548
1549 >>> import pymzml
1550 >>> example_file = 'tests/data/example.mzML'
1551 >>> run = pymzml.run.Reader(
1552 ... example_file,
1553 ... MS_precisions = {
1554 ... 1 : 5e-6,
1555 ... 2 : 20e-6
1556 ... }
1557 ... )
1558 >>> for spectrum in run:
1559 ... if spectrum.ms_level == 2:
1560 ... peak_to_find = spectrum.has_peak(1016.5404)
1561 ... print(peak_to_find)
1562 [(1016.5404, 19141.735187697403)]
1563
1564 """
1565 value = self.transform_mz(mz2find)
1566 return self.transformed_mz_with_error[value]
1567
1568 def has_overlapping_peak(self, mz):
1569 """
1570 Checks if a spectrum has more than one peak for a given m/z value
1571 and within the measured precision
1572
1573 Arguments:
1574 mz (float): m/z value which should be checked
1575
1576 Returns:
1577 Boolean (bool): Returns ``True`` if a nearby peak is detected,
1578 otherwise ``False``
1579 """
1580 for minus_or_plus in [-1, 1]:
1581 target = self.ppm2abs(mz, self.measured_precision, minus_or_plus, 1)
1582 temp = self.has_peak(self.ppm2abs(mz, self.measured_precision))
1583 if temp and len(temp) > 1:
1584 return True
1585 return False
1586
1587 def similarity_to(self, spec2, round_precision=0):
1588 """
1589 Compares two spectra and returns cosine
1590
1591 Arguments:
1592 spec2 (Spectrum): another pymzml spectrum that is compared to the
1593 current spectrum.
1594
1595 Keyword Arguments:
1596 round_precision (int): precision mzs are rounded to, i.e. round( mz,
1597 round_precision )
1598
1599 Returns:
1600 cosine (float): value between 0 and 1, i.e. the cosine between the
1601 two spectra.
1602
1603 Note:
1604 Spectra data is transformed into an n-dimensional vector,
1605 where m/z values are binned in bins of 10 m/z and the intensities
1606 are added up. Then the cosine is calculated between those two
1607 vectors. The more similar the specs are, the closer the value is
1608 to 1.
1609 """
1610 assert isinstance(spec2, Spectrum), "Spectrum 2 is not a pymzML spectrum"
1611
1612 vector1 = ddict(int)
1613 vector2 = ddict(int)
1614 mzs = set()
1615 for mz, i in self.peaks("raw"):
1616 vector1[round(mz, round_precision)] += i
1617 mzs.add(round(mz, round_precision))
1618 for mz, i in spec2.peaks("raw"):
1619 vector2[round(mz, round_precision)] += i
1620 mzs.add(round(mz, round_precision))
1621
1622 z = 0
1623 n_v1 = 0
1624 n_v2 = 0
1625
1626 for mz in mzs:
1627 int1 = vector1[mz]
1628 int2 = vector2[mz]
1629 z += int1 * int2
1630 n_v1 += int1 * int1
1631 n_v2 += int2 * int2
1632 try:
1633 cosine = z / (math.sqrt(n_v1) * math.sqrt(n_v2))
1634 except:
1635 cosine = 0.0
1636 return cosine
1637
1638 def transform_mz(self, value):
1639 """
1640 pymzml uses an internal precision for different tasks. This precision
1641 depends on the measured precision and is calculated when
1642 :py:attr:`spec.Spectrum.measured_precision` is invoked. transform_mz
1643 can be used to transform m/z values into the internal standard.
1644
1645 Arguments:
1646 value (float): m/z value
1647
1648 Returns:
1649 transformed value (float): to internal standard transformed mz
1650 value this value can be used to probe internal dictionaries,
1651 lists or sets, e.g. :func:`pymzml.spec.Spectrum.t_mz_set`
1652
1653 Example:
1654
1655 >>> import pymzml
1656 >>> run = pymzml.run.Reader(
1657 ... "test.mzML.gz" ,
1658 ... MS_precisions = {
1659 ... 1 : 5e-6,
1660 ... 2 : 20e-6
1661 ... }
1662 ... )
1663 >>>
1664 >>> for spectrum in run:
1665 ... if spectrum.ms_level == 2:
1666 ... peak_to_find = spectrum.has_deconvoluted_peak(
1667 ... 1044.5804
1668 ... )
1669 ... print(peak_to_find)
1670 [(1044.5596, 3809.4356300564586)]
1671
1672 """
1673 return int(round(value * self.internal_precision))
1674
1675 def deprecation_warning(self, function_name):
1676 deprecation_lookup = {
1677 "similarityTo": "similarity_to",
1678 "hasPeak": "has_peak",
1679 "extremeValues": "extreme_values",
1680 "transformMZ": "transform_mz",
1681 "hasOverlappingPeak": "has_overlapping_peak",
1682 "highestPeaks": "highest_peaks",
1683 "estimatedNoiseLevel": "estimated_noise_level",
1684 "removeNoise": "remove_noise",
1685 "newPlot": "new_plot",
1686 "centroidedPeaks": "peaks",
1687 "precursors": "selected_precursors",
1688 }
1689 warnings.warn(
1690 """
1691 Function: "{0}" deprecated since version 1.0.0, please use new function: "{1}"
1692 """.format(
1693 function_name, deprecation_lookup.get(function_name, "not_defined_yet")
1694 ),
1695 DeprecationWarning,
1696 )
1697
1698 def similarityTo(self, spec2, round_precision=0):
1699 self.deprecation_warning(sys._getframe().f_code.co_name)
1700 return self.similarity_to(spec2, round_precision=round_precision)
1701
1702 def hasPeak(self, mz):
1703 self.deprecation_warning(sys._getframe().f_code.co_name)
1704 return self.has_peak(mz)
1705
1706 def extremeValues(self, key):
1707 self.deprecation_warning(sys._getframe().f_code.co_name)
1708 return self.extreme_values(key)
1709
1710 def transformMZ(self, value):
1711 self.deprecation_warning(sys._getframe().f_code.co_name)
1712 return self.transform_mz(value)
1713
1714 def hasOverlappingPeak(self, mz):
1715 self.deprecation_warning(sys._getframe().f_code.co_name)
1716 return self.has_overlapping_peak(mz)
1717
1718 def highestPeaks(self, n):
1719 self.deprecation_warning(sys._getframe().f_code.co_name)
1720 return self.highest_peaks(n)
1721
1722 def estimatedNoiseLevel(self, mode="median"):
1723 self.deprecation_warning(sys._getframe().f_code.co_name)
1724 return self.estimated_noise_level(mode=mode)
1725
1726 def removeNoise(self, mode="median", noiseLevel=None):
1727 self.deprecation_warning(sys._getframe().f_code.co_name)
1728 return self.remove_noise(mode=mode, noise_level=noiseLevel)
1729
1730 @property
1731 def centroidedPeaks(self):
1732 # self.deprecation_warning( sys._getframe().f_code.co_name )
1733 return self.peaks("centroided")
1734
1735
1736 class Chromatogram(MS_Spectrum):
1737 """
1738 Class for Chromatogram access and handling.
1739 """
1740
1741 def __init__(self, element, measured_precision=5e-6, *, obo_version=None):
1742 """
1743 Arguments:
1744 element (xml.etree.ElementTree.Element): spectrum as xml Element
1745
1746 Keyword Arguments:
1747 measured_precision (float): in ppm, i.e. 5e-6 equals to 5 ppm.
1748 param (dict): parameter mapping for this spectrum
1749 """
1750 self._measured_precision = measured_precision
1751 self.element = element
1752 self.noise_level_estimate = {}
1753 # Property variables
1754 self._time = None
1755 self._ms_level = None
1756 self._i = None
1757 self._t_mass_set = None
1758 self._peaks = None
1759 self._t_mz_set = None
1760 self._centroided_peaks = None
1761 self._reprofiled_peaks = None
1762 self._deconvoluted_peaks = None
1763 self._profile = None
1764 self._extreme_values = None
1765 self._centroided_peaks_sorted_by_i = None
1766 self._transformed_mz_with_error = None
1767 self._transformed_mass_with_error = None
1768 self._precursors = None
1769 self._ID = None
1770 self.obo_translator = OboTranslator.from_cache(obo_version)
1771
1772 if self.element:
1773 # self._read_accessions()
1774 self.ns = (
1775 re.match(r"\{.*\}", element.tag).group(0)
1776 if re.match(r"\{.*\}", element.tag)
1777 else ""
1778 )
1779 # self._ns_paths = {
1780 # 'mz' : "{ns}binaryDataArrayList/" \
1781 # "{ns}binaryDataArray/" \
1782 # "{ns}cvParam[@accession='{Acc}']/..".format(
1783 # ns=self.ns,
1784 # Acc=self.accessions['time array']
1785 # ),
1786 # 'i' : "{ns}binaryDataArrayList/" \
1787 # "{ns}binaryDataArray/" \
1788 # "{ns}cvParam[@accession='{Acc}']/..".format(
1789 # ns=self.ns,
1790 # Acc=self.accessions['intensity array']
1791 # ),
1792 # 'time' : "{ns}binaryDataArrayList/" \
1793 # "{ns}binaryDataArray/" \
1794 # "{ns}cvParam[@accession='{Acc}']/..".format(
1795 # ns=self.ns,
1796 # Acc=self.accessions['time array']
1797 # ),
1798 # 'float_type' : "./{ns}cvParam[@accession='{Acc}']"
1799 # }
1800
1801 self._decode = self._decode_to_numpy
1802 # assign function to create numpy array to list???
1803 self._array = np.array
1804
1805 def __repr__(self):
1806 return "<__main__.Chromatogram object with native ID {0} at {1}>".format(
1807 self.ID, hex(id(self))
1808 )
1809
1810 def __str__(self):
1811 return "<__main__.Chromatogram object with native ID {0} at {1}>".format(
1812 self.ID, hex(id(self))
1813 )
1814
1815 @property
1816 def ID(self):
1817 if self._ID is None:
1818 self._ID = self.element.get("id")
1819 return self._ID
1820
1821 @property
1822 def mz(self):
1823 """"""
1824 print("Chromatogram has no property mz.\nReturn retention time instead")
1825 return self.time
1826
1827 @property
1828 def time(self):
1829 """
1830 Returns the list of time values. If the time values are encoded, the
1831 function _decode() is used to decode the encoded data.\n
1832 The time property can also be set, e.g. for theoretical data.
1833 However, it is recommended to use the profile property to set time and
1834 intensity tuples at same time.
1835
1836 Returns:
1837 time (list): list of time values from the analyzed chromatogram
1838
1839 """
1840 if self._time is None:
1841 params = self._get_encoding_parameters("time array")
1842 self._time = self._decode(*params)
1843 return self._time
1844
1845 @property
1846 def i(self):
1847 if self._i is None:
1848 params = self._get_encoding_parameters("intensity array")
1849 self._i = self._decode(*params)
1850 return self._i
1851
1852 @property
1853 def profile(self):
1854 """
1855 Returns the list of peaks of the chromatogram as tuples (time, intensity).
1856
1857 Returns:
1858 peaks (list): list of time, i tuples
1859
1860 Example:
1861
1862 >>> import pymzml
1863 >>> run = pymzml.run.Reader(
1864 ... spectra.mzMl.gz,
1865 ... MS_precisions = {
1866 ... 1 : 5e-6,
1867 ... 2 : 20e-6
1868 ... }
1869 ... )
1870 >>> for entry in run:
1871 ... if isinstance(entry, pymzml.spec.Chromatogram):
1872 ... for time, intensity in entry.peaks:
1873 ... print(time, intensity)
1874
1875 Note:
1876 The peaks property can also be set, e.g. for theoretical data.
1877 It requires a list of time/intensity tuples.
1878
1879 """
1880 if self._profile is None:
1881 if self._time is None and self._i is None:
1882 self._profile = []
1883 for pos, t in enumerate(self.time):
1884 self._profile.append([t, self.i[pos]])
1885 # much faster than zip ... list(zip(self.mz, self.i))
1886 elif self._time is not None and self._i is not None:
1887 self._profile = []
1888 for pos, t in enumerate(self.time):
1889 self._profile.append([t, self.i[pos]])
1890 elif self._profile is None:
1891 self._profile = []
1892 return self._array(self._profile)
1893
1894 @profile.setter
1895 def profile(self, tuple_list):
1896 if len(tuple_list) == 0:
1897 return
1898 # self._mz, self._i = map(list, zip(*tuple_list))
1899 # same here .. zip is soooooo slow :)
1900 self._time = []
1901 self._i = []
1902 for time, i in tuple_list:
1903 self._time.append(time)
1904 self._i.append(i)
1905 self._peaks = tuple_list
1906 self._reprofiledPeaks = None
1907 self._centroidedPeaks = None
1908 return self
1909
1910 def peaks(self):
1911 """
1912 Return the list of peaks of the spectrum as tuples (time, intensity).
1913
1914 Returns:
1915 peaks (list): list of time, intensity tuples
1916
1917 Example:
1918
1919 >>> import pymzml
1920 >>> run = pymzml.run.Reader(
1921 ... spectra.mzMl.gz,
1922 ... MS_precisions = {
1923 ... 1 : 5e-6,
1924 ... 2 : 20e-6
1925 ... }
1926 ... )
1927 >>> for entry in run:
1928 ... if isinstance(entry, pymzml.spec.Chromatogram):
1929 ... for time, intensity in entry.peaks:
1930 ... print(time, intensity)
1931
1932 Note:
1933 The peaks property can also be set, e.g. for theoretical data.
1934 It requires a list of time/intensity tuples.
1935
1936 """
1937 return self.profile