### Initialize pymzml run reader Source: https://pymzml.github.io/pymzML/_sources/obo.rst.txt Setup the environment by importing pymzml and opening an example file to create a run reader. ```python >>> example_file = get_example_file.open_example('dta_example.mzML') >>> import pymzml >>> msrun = pymzml.run.Reader(example_file) ``` -------------------------------- ### Clone pymzML Repository and Install Dependencies Source: https://pymzml.github.io/pymzML/intro.html Clone the pymzML repository from GitHub, navigate into the directory, and install required dependencies using pip. Then, install the package using setup.py. ```bash user@localhost:~$ git clone https://github.com/pymzML/pymzml.git user@localhost:~$ cd pymzml user@localhost:~$ pip install -r requirements.txt user@localhost:~$ python setup.py install ``` -------------------------------- ### Test pymzML Installation Source: https://pymzml.github.io/pymzML/intro.html Run the 'tox' command to test the package and verify a correct installation. ```bash tox ``` -------------------------------- ### Install pymzML via PyPI Source: https://pymzml.github.io/pymzML/intro.html Install the standard version of pymzML using pip. For extended functionality, install with optional dependencies like plotting, pynumpress, deconvolution, or a full feature set. ```bash user@localhost:~$ pip install pymzml # install standard version ``` ```bash user@localhost:~$ pip install "pymzml[plot]" # with plotting support ``` ```bash user@localhost:~$ pip install "pymzml[pynumpress]" # with pynumpress support ``` ```bash user@localhost:~$ pip install "pymzml[deconvolution]" # with deconvolution support using ms_deisotope ``` ```bash user@localhost:~$ pip install "pymzml[full]" # full featured ``` -------------------------------- ### Implement Custom SQLite File Handler Source: https://pymzml.github.io/pymzML/example_scripts.html Example class structure for a custom database connector that implements read and __getitem__ methods for spectrum retrieval. ```python class SQLiteDatabase(object): """ Example implementation of a database Conncetor, which can be used to make run accept paths to sqlite db files. We initialize with a path to a database and implement a custom __getitem__ function to retrieve the spectra """ def __init__(self, path): """ """ connection = sqlite3.connect(path) self.cursor = connection.cursor() def __getitem__(self, key): """ Execute a SQL request, process the data and return a spectrum object. Args: key (str or int): unique identifier for the given spectrum in the database """ self.cursor.execute('SELECT * FROM spectra WHERE id=?', key) ID, element = self.cursor.fetchone() element = et.XML(element) if 'spectrum' in element.tag: spectrum = spec.Spectrum(element) elif 'chromatogram' in element.tag: spectrum = spec.Chromatogram(element) return spectrum def get_spectrum_count(self): self.cursor.execute("SELECT COUNT(*) from spectra") num = self.cursor.fetchone()[0] return num def read(self, size=-1): # implement read so it starts reading in first ID, # if end reached switches to next id and so on ... return '\n' ``` -------------------------------- ### Define MS precision configuration Source: https://pymzml.github.io/pymzML/pymzml_run.html Example dictionary structure for specifying MS precision levels when initializing the Reader. ```python { 1 : 5e-6, 2 : 20e-6 } ``` -------------------------------- ### SQLiteDatabase Class Definition Source: https://pymzml.github.io/pymzML/pymzml_utils.html Example implementation of a database connector for SQLite files. ```python .. class SQLiteDatabase(object): .. """ .. Example implementation of a database Connector, .. which can be used to make run accept paths to .. sqlite db files. ``` -------------------------------- ### MZML Iterator Initialization Source: https://pymzml.github.io/pymzML/_modules/pymzml/run.html Initializes the iterator for mzML files, setting it to the start of the spectrumList element and extracting metadata. ```APIDOC ## _init_iter ### Description Initalize the iterator for the spectra and sets it to the start of the spectrumList element. ### Returns - mzml_iter (xml.etree.ElementTree._IterParseIterator): Iterator over all elements in the file starting with the first spectrum ### Code Example ```python mzml_iter = iter(ElementTree.iterparse(self.info["file_object"], events=("end", "start"))) _, self.root = next(mzml_iter) # ... (rest of the initialization logic) ``` ``` -------------------------------- ### Check Gzip Magic Bytes Source: https://pymzml.github.io/pymzML/_modules/pymzml/utils/GSGR.html Verifies if the opened file starts with the standard gzip magic bytes (\x1f\x8b) to confirm it is a valid gzip file. ```python def _check_magic_bytes(self): """ Check if file is a gzip file. """ # self.file_in.seek(0) # make sure file pointer is at start mb = self.file_in.read(2) return mb == self.magic_bytes ``` -------------------------------- ### Reader Initialization with Optional Arguments Source: https://pymzml.github.io/pymzML/_modules/pymzml/run.html Demonstrates initializing the Reader with various optional parameters like build_index_from_scratch, skip_chromatogram, and index_regex. ```python reader = mzml.Reader( path_or_file, MS_precisions=None, obo_version=None, build_index_from_scratch=False, skip_chromatogram=True, index_regex=None, **kwargs ) ``` -------------------------------- ### Method: _build_index_from_scratch Source: https://pymzml.github.io/pymzML/_modules/pymzml/file_classes/standardMzml.html Parses the entire file to manually identify the byte offsets for spectra and chromatograms. ```APIDOC ## _build_index_from_scratch ### Description Builds an index of spectra/chromatogram data with offsets by parsing the file content directly using regex patterns, bypassing standard XML parsers to maintain file pointer accuracy. ### Parameters #### Request Body - **seeker** (file-like object) - Required - The binary file handler to parse. ``` -------------------------------- ### Dictionary-like Get Function Source: https://pymzml.github.io/pymzML/_modules/pymzml/spec.html Provides a dictionary-like 'get' method to retrieve values, returning a default if the accession is not found. ```APIDOC ## GET /api/get_value ### Description Mimics the `get` method of a dictionary. It attempts to retrieve a value associated with a given accession. If the accession is not found (returns None), it returns a specified default value. ### Method GET ### Endpoint /api/get_value ### Parameters #### Query Parameters - **acc** (str) - Required - The accession or OBO tag to look up. - **default** (any, optional) - Optional - The value to return if `acc` is not found. Defaults to None. ### Response #### Success Response (200) - **value** (any) - The retrieved value for the accession, or the default value if not found. #### Response Example ```json { "value": "some_data" } ``` ```json { "value": null } ``` ``` -------------------------------- ### Mimic Dictionary Get Function Source: https://pymzml.github.io/pymzML/_modules/pymzml/spec.html Provides a dictionary-like get method to retrieve values by accession, returning a default value if the accession is not found. Requires the object to support item access `self[acc]`. ```python def get(self, acc, default=None): """Mimic dicts get function. Args: acc (str): accession or obo tag to return default (None, optional): default value if acc is not found """ val = self[acc] if val is None: val = default return val ``` -------------------------------- ### Initialize StandardMzml Wrapper Source: https://pymzml.github.io/pymzML/_modules/pymzml/file_classes/standardMzml.html Initializes a wrapper object for standard mzML files, setting up file handlers and parsing parameters. ```python def __init__( self, path, encoding, build_index_from_scratch=False, index_regex=None, ): """ Initalize Wrapper object for standard mzML files. Arguments: path (str) : path to the file encoding (str) : encoding of the file """ self.index_regex = index_regex self.path = path self.file_handler = self.get_file_handler(encoding) self.offset_dict = {} self.spec_open = regex_patterns.SPECTRUM_OPEN_PATTERN self.spec_close = regex_patterns.SPECTRUM_CLOSE_PATTERN self.seek_list = self._read_extremes() self._build_index(from_scratch=build_index_from_scratch) ``` -------------------------------- ### Parse mzML File (New Syntax) Source: https://pymzml.github.io/pymzML/example_scripts.html Demonstrates parsing an mzML file using the current pymzML syntax where MS level is a property of the spectrum class. Requires an mzML file path as a command-line argument. ```python #!/usr/bin/env python import sys import pymzml def main(mzml_file): """ Basic example script to demonstrate the usage of pymzML. Requires a mzML file as first argument. usage: ./simple_parser.py Note: This script uses the new syntax with the MS level being a property of the spectrum class ( Spectrum.ms_level ). The old syntax can be found in the script simple_parser_v2.py where the MS level can be queried as a key (Spectrum['ms level']) """ run = pymzml.run.Reader(mzml_file) for n, spec in enumerate(run): print( "Spectrum {0}, MS level {ms_level} @ RT {scan_time:1.2f}".format( spec.ID, ms_level=spec.ms_level, scan_time=spec.scan_time_in_minutes() ) ) print("Parsed {0} spectra from file {1}".format(n, mzml_file)) print() if __name__ == "__main__": if len(sys.argv) < 2: print(main.__doc__) exit() mzml_file = sys.argv[1] main(mzml_file) ``` -------------------------------- ### GET /get_array Source: https://pymzml.github.io/pymzML/_modules/pymzml/spec.html Retrieves a specific binary data array from the spectrum by name. ```APIDOC ## GET /get_array ### Description Retrieves and decodes a specific binary data array (e.g., 'm/z array', 'intensity array'). ### Parameters #### Query Parameters - **arr_name** (str) - Required - The name of the binary array to retrieve. ``` -------------------------------- ### Parse mzML File (Old Syntax) Source: https://pymzml.github.io/pymzML/example_scripts.html Demonstrates parsing an mzML file using the older pymzML syntax where MS level is accessed as a key in the spectrum dictionary. Requires an mzML file path as a command-line argument. ```python #!/usr/bin/env python import sys import pymzml from collections import defaultdict as ddict def main(mzml_file): """ Basic example script to demonstrate the usage of pymzML. Requires a mzML file as first argument. usage: ./simple_parser_v2.py Note: This script uses the old syntax where the MS level can be queried as a key (Spectrum['ms level']). The current syntax can be found in simple_parser.py """ run = pymzml.run.Reader(mzml_file) # print( run[10000].keys() ) stats = ddict(int) for n, spec in enumerate(run): print( "Spectrum {0}, MS level {ms_level}".format(n, ms_level=spec["ms level"]), end="\r", ) # the old method to obtain peaks from the Spectrum class stats[spec.ID] = len(spec.centroidedPeaks) print("Parsed {0} spectra from file {1}".format(len(stats.keys()), mzml_file)) print() if __name__ == "__main__": if len(sys.argv) < 2: print(main.__doc__) exit() mzml_file = sys.argv[1] main(mzml_file) ``` -------------------------------- ### Get Spectrum Count Source: https://pymzml.github.io/pymzML/_modules/pymzml/run.html Retrieves the total count of spectra present in the mzML file. ```APIDOC ## get_spectrum_count ### Description Get the total number of spectra in the mzML file. ### Returns - The number of spectra (int) or None if not specified. ``` -------------------------------- ### Main Execution Entry Point Source: https://pymzml.github.io/pymzML/_modules/plot_spectrum_with_annotation.html Standard Python entry point for script execution. ```python if __name__ == "__main__": main() ``` -------------------------------- ### GET /peaks Source: https://pymzml.github.io/pymzML/_modules/pymzml/spec.html Retrieves decoded peak data as a list or numpy array of mz/i tuples. ```APIDOC ## GET /peaks ### Description Decode and return a list of mz/i tuples for a specified peak type. ### Parameters #### Query Parameters - **peak_type** (str) - Required - The type of peaks to retrieve. Supported types: 'raw', 'centroided', 'reprofiled'. ### Response #### Success Response (200) - **peaks** (list or ndarray) - A list or numpy array of mz/i tuples. ``` -------------------------------- ### Plotly Import Block Source: https://pymzml.github.io/pymzML/_modules/pymzml/plot.html Imports necessary Plotly modules for plotting. Includes a fallback with a warning if Plotly is not installed. ```python try: import plotly as plt # import plotly.offline as plt import plotly.graph_objs as go from plotly import subplots except ImportError: warnings.warn("Plotly is required for plotting support.", ImportWarning) ``` -------------------------------- ### Initialize and use StandardGzip Source: https://pymzml.github.io/pymzML/_modules/pymzml/file_classes/standardGzip.html The StandardGzip class handles gzipped file streams. It requires a file path and encoding for initialization. ```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Interface for gzipped mzML files. """ # Python mzML module - pymzml # Copyright (C) 2010-2019 M. Kösters, C. Fufezan # The MIT License (MIT) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import codecs import gzip from xml.etree.ElementTree import iterparse from .. import regex_patterns from .. import spec from .. import chromatogram [docs] class StandardGzip(object): [docs] def __init__(self, path, encoding): """ Initalize Wrapper object for gzipped mzML files. Arguments: path (str) : path to the file encoding (str) : encoding of the file """ self.path = path self.file_handler = codecs.getreader(encoding)(gzip.open(path)) self.offset_dict = self._build_index() return def close(self): self.file_handler.close() [docs] def _build_index(self): """ Cant build index for standard gzip files """ # raise Exception('Cant build index for gzip files') pass [docs] def read(self, size=-1): """ Read binary data from file handler. Keyword Arguments: size (int): Number of bytes to read from file, -1 to read to end of file Returns: data (str): byte string of len size of input data """ return self.file_handler.read(size) [docs] def __getitem__(self, identifier): """ Access the item with id 'identifier' in the file by iterating the xml-tree. Arguments: identifier (str): native id of the item to access Returns: data (str): text associated with the given identifier """ old_pos = self.file_handler.tell() self.file_handler.seek(0, 0) mzml_iter = iter(iterparse(self.file_handler, events=["end"])) while True: event, element = next(mzml_iter) if event == "end": if element.tag.endswith("}spectrum"): if ( int( regex_patterns.SPECTRUM_ID_PATTERN.search( element.get("id") ).group(1) ) == identifier ): self.file_handler.seek(old_pos, 0) return spec.Spectrum(element, measured_precision=5e-6) elif element.tag.endswith("}chromatogram"): if element.get("id") == identifier: self.file_handler.seek(old_pos, 0) return chromatogram.Chromatogram( element, measured_precision=5e-6 ) if __name__ == "__main__": print(__doc__) ``` -------------------------------- ### Get File Handler with Encoding Source: https://pymzml.github.io/pymzML/_modules/pymzml/file_classes/standardMzml.html Returns a file handler opened with a specified encoding for reading the mzML file. ```python def get_file_handler(self, encoding): return codecs.open(self.path, mode="r", encoding=encoding) ``` -------------------------------- ### Get Binary File Handler Source: https://pymzml.github.io/pymzML/_modules/pymzml/file_classes/standardMzml.html Returns a file handler opened in binary read mode for the mzML file. ```python def get_binary_file_handler(self): return open(self.path, "rb") ``` -------------------------------- ### Method info() Source: https://pymzml.github.io/pymzML/_modules/pymzml/plot.html Prints a summary of the plotting factory, detailing the number of plots, datasets per plot, and datapoints per dataset. ```APIDOC ## info() ### Description Prints a summary about the plotting factory, i.e. how many plots and how many datasets per plot. ### Response - **Output** (stdout) - Prints the count of unique plots, datasets per plot, and datapoints per dataset to the console. ``` -------------------------------- ### Initialize GSGW Class Source: https://pymzml.github.io/pymzML/_modules/pymzml/utils/GSGW.html Initializes the Generalized Gzip writer class with options for file output, index size, and compression settings. The output path defaults to './test.dat.igzip'. ```python import struct import time import zlib from collections import OrderedDict class GSGW(object): """ Generalized Gzip writer class with random access to indexed offsets. Keyword Arguments: file (string) : Filename for the resulting file max_idx (int) : max number of indices which can be saved in this file max_idx_len (int) : maximal length of the index in bytes, must be between 1 and 255 max_offset_len (int) : maximal length of the offset in bytes output_path (str) : path to the output file """ def __init__( self, file=None, max_idx=10000, max_idx_len=8, max_offset_len=8, output_path="./test.dat.igzip", comp_str=-1, ): self.Lock = False self._format_version = 1 # max 255!!! self.file_name = output_path self.max_idx_num = max_idx self.max_idx_len = max_idx_len self.max_offset_len = max_offset_len self.generic_header = OrderedDict( [ ("MAGIC_BYTE_1", b"\x1f"), ("MAGIC_BYTE_2", b"\x8b"), ("COMPRESSION", b"\x08"), ("FLAGS", b"\x00"), ("DATE", b"\x00\x00\x00\x00"), ("XFL", b"\x02"), ("OS", b"\x03"), ] ) self.index = OrderedDict() self.first_header_set = False self._file_out = None self._encoding = "latin-1" # magic bytes. FU+version self.index_magic_bytes = b"FU" + struct.pack(">> import pymzml >>> example_file = 'tests/data/example.mzML' >>> run = pymzml.run.Reader( ... example_file, ... MS_precisions = { ... 1 : 5e-6, ... 2 : 20e-6 ... } ... ) >>> for spectrum in run: ... if spectrum.ms_level == 2: ... peak_to_find = spectrum.has_peak(1016.5404) ... print(peak_to_find) [(1016.5404, 19141.735187697403)] ``` -------------------------------- ### Access mzML Run Information Source: https://pymzml.github.io/pymzML/example_scripts.html Demonstrates how to read an mzML file and print summary information using the run.info dictionary. ```python >>> run.info = { 'encoding': 'utf-8', 'file_name': '/Users/joe/Dev/pymzml_2.0/tests/data/BSA1.mzML.gz', 'file_object': , 'obo_version': '1.1.0', 'offset_dict': None, 'run_id': 'ru_0', 'spectrum_count': 1684, 'start_time': '2009-08-09T22:32:31' } ``` ```python #!/usr/bin/env python import sys import pymzml def main(mzml_file): """ Basic example script to access basic run info of an mzML file. Requires a mzML file as first command line argument. usage: ./access_run_info.py >>> run.info = { 'encoding': 'utf-8', 'file_name': '/Users/joe/Dev/pymzml_2.0/tests/data/BSA1.mzML.gz', 'file_object': , 'obo_version': '1.1.0', 'offset_dict': None, 'run_id': 'ru_0', 'spectrum_count': 1684, 'start_time': '2009-08-09T22:32:31' } """ run = pymzml.run.Reader(mzml_file) print( """ Summary for mzML file: {file_name} Run was measured on {start_time} using obo version {obo_version} File contains {spectrum_count} spectra """.format( **run.info ) ) if __name__ == "__main__": if len(sys.argv) < 2: print(main.__doc__) exit() mzml_file = sys.argv[1] main(mzml_file) ``` -------------------------------- ### Get and Set GSGW Encoding Source: https://pymzml.github.io/pymzML/_modules/pymzml/utils/GSGW.html Allows retrieval and modification of the encoding used for the output file. The encoding must be a string. ```python @property def encoding(self): """ Returns the encoding used for this file """ return self._encoding @encoding.setter def encoding(self, encoding): """ Set the file encoding for the output file. """ assert type(encoding) == str, "encoding must be a string" self._encoding = encoding ``` -------------------------------- ### Transform m/z values and probe spectra Source: https://pymzml.github.io/pymzML/pymzml_spec.html Demonstrates how to initialize a reader with specific MS precisions and check for deconvoluted peaks in MS2 spectra. ```python >>> import pymzml >>> run = pymzml.run.Reader( ... "test.mzML.gz" , ... MS_precisions = { ... 1 : 5e-6, ... 2 : 20e-6 ... } ... ) >>> >>> for spectrum in run: ... if spectrum.ms_level == 2: ... peak_to_find = spectrum.has_deconvoluted_peak( ... 1044.5804 ... ) ... print(peak_to_find) [(1044.5596, 3809.4356300564586)] ``` -------------------------------- ### Get Plot Data Source: https://pymzml.github.io/pymzML/_modules/pymzml/plot.html Retrieves the plot data, applying function mappings to 'y' values. Returns the data in a JSON-compatible dictionary format. ```python def get_data(self): """ Return data and layout in JSON format. Returns: plots (dict): JSON compatible python dict """ for i, plot in enumerate(self.plots): for j, trace in enumerate(plot): self.plots[i][j]["y"] = [ self.function_mapper[x](i) if x in self.function_mapper else x for x in trace["y"] ] return self.plots ``` -------------------------------- ### Run Deprecation Check Script Source: https://pymzml.github.io/pymzML/_modules/deprecation_check.html Executes the deprecation_check.py script to validate Spectrum class method usage against an example mzML file. ```python #!/usr/bin/env python3 import os import pymzml [docs] def main(): """ Testscript to highlight the function name changes in the Spectrum class. Note: Please adjust any old scripts to the new syntax. usage: ./deprecation_check.py """ example_file = os.path.join( os.path.dirname(__file__), os.pardir, "tests", "data", "example.mzML" ) run = pymzml.run.Reader(example_file) spectrum_list = [] for pos, spectrum in enumerate(run): spectrum_list.append(spectrum) spectrum.hasPeak((813.19073486)) spectrum.extremeValues("mz") spectrum.hasOverlappingPeak(813.19073486) spectrum.highestPeaks(1) spectrum.estimatedNoiseLevel() spectrum.removeNoise() spectrum.transformMZ(813.19073486) if pos == 1: spectrum.similarityTo(spectrum_list[0]) break if __name__ == "__main__": main() ``` -------------------------------- ### StandardMzml Class Initialization Source: https://pymzml.github.io/pymzML/_modules/pymzml/file_classes/standardMzml.html Initializes the StandardMzml wrapper object for standard mzML files. ```APIDOC ## StandardMzml Class ### Description Initializes a wrapper object for standard mzML files, allowing access to spectrum and chromatogram data. ### Method __init__ ### Parameters #### Path Parameters - **path** (str) - Required - The file path to the mzML file. - **encoding** (str) - Required - The encoding of the file. - **build_index_from_scratch** (bool) - Optional - If True, the index will be built from scratch. Defaults to False. - **index_regex** (str) - Optional - A regular expression pattern for indexing. ### Request Example ```python from pymzml.file_methods import StandardMzml wrapper = StandardMzml(path='/path/to/your/file.mzML', encoding='utf-8') ``` ### Response This method does not return a value; it initializes the object. ``` -------------------------------- ### Get Element by Name Source: https://pymzml.github.io/pymzML/_modules/pymzml/spec.html Retrieves an XML element from the spectrum's original tree based on its unit name. Useful for accessing specific parameters. ```python def get_element_by_name(self, name): """ Get element from the original tree by it's unit name. Arguments: name (str): unit name of the mzml element. Keyword Arguments: obo_version (str, optional): obo version number. """ iterator = self.element.iter() return_ele = None for ele in iterator: if ele.get("name", default=None) == name: return_ele = ele break return return_ele ``` -------------------------------- ### Enable With Syntax for Class Source: https://pymzml.github.io/pymzML/_modules/pymzml/utils/GSGW.html Enables the use of the 'with' statement for managing the file object, providing a convenient entry point for resource management. ```python def __enter__(self): """ Enable the with syntax for this class (entry point). """ return self ``` -------------------------------- ### Enter Context Manager Source: https://pymzml.github.io/pymzML/_modules/pymzml/utils/GSGR.html Enables the use of the 'with' statement for the GSGR class, ensuring proper resource management. ```python def __enter__(self): """ Enable the with syntax for this class (entry point) """ return self.file_in ``` -------------------------------- ### Initialize File Interface Source: https://pymzml.github.io/pymzML/file_handlers.html Initializes an object interface to mzML files. Specify the path, encoding, and optionally whether to build the index from scratch or provide a custom index regex. ```python FileInterface(_path_ , _encoding_ , _build_index_from_scratch =False_, _index_regex =None_) ``` -------------------------------- ### Compile Moby Dick Chapter Pattern Source: https://pymzml.github.io/pymzML/pymzml_regex_patterns.html This regex is used to extract chapter numbers from text, specifically mentioned for use in an index gezip writer example. ```python pymzml.regex_patterns.MOBY_DICK_CHAPTER_PATTERN = re.compile('CHAPTER ([0-9]+).*')_ ``` -------------------------------- ### FileInterface Initialization Source: https://pymzml.github.io/pymzML/_modules/pymzml/file_interface.html Initializes the FileInterface to handle different mzML file formats. It determines the appropriate file handler based on the file extension and encoding. ```APIDOC ## FileInterface Initialization ### Description Initializes an object interface to mzML files. It automatically detects the file type (standard mzML, gzip, or indexed gzip) and sets up the corresponding file handler. ### Method ``` __init__(self, path, encoding, build_index_from_scratch=False, index_regex=None) ``` ### Parameters #### Path Parameters - **path** (str) - Required - The path to the mzML file. - **encoding** (str) - Required - The encoding of the file. - **build_index_from_scratch** (bool) - Optional - If True, builds the index from scratch. Defaults to False. - **index_regex** (str) - Optional - A regular expression to use for indexing. Defaults to None. ``` -------------------------------- ### Get Transformed Peaks Source: https://pymzml.github.io/pymzML/_modules/pymzml/spec.html Returns a list of peaks where the m/z values are transformed by multiplying them with the internal precision. This converts float m/z values to integers for faster processing. ```python @property def transformed_peaks(self): """ m/z value is multiplied by the internal precision. Returns: Transformed peaks (list): Returns a list of peaks (tuples of mz and intensity). Float m/z values are adjusted by the internal precision to integers. """ if self._transformed_peaks is None: self._transformed_peaks = [ (self.transform_mz(mz), i) for mz, i in self.peaks("centroided") ] ``` -------------------------------- ### GSGR Class Initialization Source: https://pymzml.github.io/pymzML/_modules/pymzml/utils/GSGR.html Initializes the GSGR object, opens the specified file, checks for gzip magic bytes, and reads the basic header. It also handles optional fields like FEXTRA, FNAME, and FCOMMENT to determine indexing and read the index if present. ```APIDOC ## GSGR Class ### Description Generalized Gzip reader class which enables random access in files written with the :class:`~pymzml.utils.GSGW.GSGW` class. ### Keyword Arguments - **file** (str) - path to file to read ### Initialization Example ```python from pymzml.utils.GSGR import GSGR gsgr_reader = GSGR(file='path/to/your/file.gz') ``` ``` -------------------------------- ### Gzip Header Hex Dump Example Source: https://pymzml.github.io/pymzML/_sources/index_gzip.rst.txt A hex dump representing the Moby Dick igz header, showing the gzip header, comment field, and index-to-offset mapping. ```hex 00000000: 1f8b 0810 ea57 4f5a 0203 4655 0109 06ac 4368 6170 7465 7230 :.....WOZ..FU....Chapter0 00000018: acac ac36 3436 ac43 6861 7074 6572 31ac 3136 3033 32ac 4368 :...646.Chapter1.16032.Ch 00000030: 6170 7465 7232 ac32 3137 3831 ac43 6861 7074 6572 33ac 3235 :apter2.21781.Chapter3.25 00000048: 3534 37ac 4368 6170 7465 7234 ac33 3932 3436 ac43 6861 7074 :547.Chapter4.39246.Chapt 00000060: 6572 35ac 3433 3435 38ac 4368 6170 7465 7236 ac34 3535 3437 :er5.43458.Chapter6.45547 00000078: ac43 6861 7074 6572 37ac 3437 3936 39ac 4368 6170 7465 7238 :.Chapter7.47969.Chapter8 00000090: ac35 3037 3033 ac43 6861 7074 6572 39ac 3533 3239 3943 6861 :.50703.Chapter9.53299Cha 000000a8: 7074 6572 3130 ac36 3230 3138 4368 6170 7465 7231 31ac 3636 :pter10.62018Chapter11.66 000000c0: 3032 3843 6861 7074 6572 3132 ac36 3739 3536 4368 6170 7465 :028Chapter12.67956Chapte 000000d8: 7231 33ac 3730 3333 3043 6861 7074 6572 3134 ac37 3438 3331 :r13.70330Chapter14.74831 000000f0: 4368 6170 7465 7231 35ac 3736 3938 3443 6861 7074 6572 3136 :Chapter15.76984Chapter16 00000108: ac38 3030 3937 4368 6170 7465 7231 37ac 3933 3134 3743 6861 :.80097Chapter17.93147Cha 00000120: 7074 6572 3138 ac39 3838 3534 4368 6170 7465 7231 3931 3032 :pter18.98854Chapter19102 00000138: 3430 3343 6861 7074 6572 3230 3130 3533 3932 4368 6170 7465 :403Chapter20105392Chapte 00000150: 7232 3131 3037 3739 3043 6861 7074 6572 3232 3131 3037 3232 :r21107790Chapter22110722 00000168: 4368 6170 7465 7232 3331 3134 3936 3143 6861 7074 6572 3234 :Chapter23114961Chapter24 00000180: 3131 3631 3134 4368 6170 7465 7232 3531 3230 3731 3943 6861 :116114Chapter25120719Cha 00000198: 7074 6572 3236 3132 3135 3633 4368 6170 7465 7232 3731 3234 :pter26121563Chapter27124 000001b0: 3839 3343 6861 7074 6572 3238 3132 3933 3138 4368 6170 7465 :893Chapter28129318Chapte 000001c8: 7232 3931 3333 3134 3843 6861 7074 6572 3330 3133 3633 3436 :r29133148Chapter30136346 000001e0: 4368 6170 7465 7233 3131 3337 3230 3043 6861 7074 6572 3332 :Chapter31137200Chapter32 000001f8: 3133 3933 3137 4368 6170 7465 7233 3331 3532 3031 3743 6861 :139317Chapter33152017Cha 00000210: 7074 6572 3334 3135 3437 3635 4368 6170 7465 7233 3531 3630 :pter34154765Chapter35160 00000228: 3536 3743 6861 7074 6572 3336 3136 3732 3736 4368 6170 7465 :567Chapter36167276Chapte 00000240: 7233 3731 3734 3530 3243 6861 7074 6572 3338 3137 3630 3330 :r37174502Chapter38176030 00000258: 4368 6170 7465 7233 3931 3737 3230 3043 6861 7074 6572 3430 :Chapter39177200Chapter40 00000270: 3137 3830 3338 4368 6170 7465 7234 3131 3832 3531 3900 ``` -------------------------------- ### GSGW Class Initialization Source: https://pymzml.github.io/pymzML/pymzml_utils.html Initializes the GSGW writer for creating indexed Gzip files. ```APIDOC ## CLASS pymzml.utils.GSGW.GSGW ### Description Generalized Gzip writer class with random access to indexed offsets. ### Parameters #### Keyword Arguments - **file** (string) - Optional - Filename for the resulting file - **max_idx** (int) - Optional - Max number of indices which can be saved in this file - **max_idx_len** (int) - Optional - Maximal length of the index in bytes (1-255) - **max_offset_len** (int) - Optional - Maximal length of the offset in bytes - **output_path** (str) - Optional - Path to the output file ``` -------------------------------- ### Add Two PyMZML Spectra Source: https://pymzml.github.io/pymzML/_modules/pymzml/spec.html Adds another spectrum to the current spectrum. Requires both spectra to be of type Spectrum. The example demonstrates reading an mzML file and accumulating spectra. ```python import pymzml s = pymzml.spec.Spectrum( measuredPrescision = 20e-6 ) file_to_read = "../mzML_example_files/xy.mzML.gz" run = pymzml.run.Reader( file_to_read , MS1_Precision = 5e-6 , MSn_Precision = 20e-6 ) for spec in run: s += spec ``` -------------------------------- ### Factory Initialization Source: https://pymzml.github.io/pymzML/_modules/pymzml/plot.html Initializes the plotting factory with an optional filename for output. ```APIDOC ## Factory Class ### Description Interface to visualize m/z or profile data using plotly (https://plot.ly/). ### Method __init__ ### Parameters #### Path Parameters - **filename** (str) - Optional - Name for the output file. Default = "spectrum_plot.html" ### Request Example ```python factory = Factory(filename="my_spectrum.html") ``` ### Response N/A (Constructor) ``` -------------------------------- ### GSGR Read Block Method Source: https://pymzml.github.io/pymzML/_modules/pymzml/utils/GSGR.html Reads and returns a specific data block identified by its index. It uses the internal index to find the start and end offsets of the block, then decompresses the data. ```APIDOC ## read_block ### Description Read and return the data block with the unique index `index`. ### Method `read_block(index)` ### Arguments - **index** (int or str) - identifier associated with a specific block ### Returns - data (str) - indexed text block as string ### Example ```python block_data = gsgr_reader.read_block('some_block_id') ``` ``` -------------------------------- ### Open file with FileInterface Source: https://pymzml.github.io/pymzML/_modules/pymzml/run.html Wraps the file path using the FileInterface class. ```python def _open_file(self, path_or_file, build_index_from_scratch=False): """ Open the path using the FileInterface class as a wrapper. Arguments: path (str): path to the file to parse Returns: (FileInterface): Wrapper class for compressed and uncompressed mzml files """ return FileInterface( path_or_file, self.info["encoding"], build_index_from_scratch=build_index_from_scratch, index_regex=self.index_regex, ) ``` -------------------------------- ### Get Transformed m/z with Error Source: https://pymzml.github.io/pymzML/_modules/pymzml/spec.html Returns a dictionary of transformed m/z values, including error ranges. Each key represents a transformed m/z with error, and its value is a list of (m/z, intensity) tuples. ```python @property def transformed_mz_with_error(self): """ Returns transformed m/z value with error Returns: tmz values (dict): Transformed m/z values in dictionary\n {\n m/z_with_error : [(m/z,intensity), ...], ...\n }\n """ if self._transformed_mz_with_error is None: self._transformed_mz_with_error = ddict(list) for mz, i in self.peaks("centroided"): for t_mz_with_error in range( int( round( (mz - (mz * self.measured_precision)) * self.internal_precision ) ), int( round( (mz + (mz * self.measured_precision)) * self.internal_precision ) ) + 1, ): self._transformed_mz_with_error[t_mz_with_error].append((mz, i)) return self._transformed_mz_with_error ``` -------------------------------- ### Create SQLite Database from mzML File Source: https://pymzml.github.io/pymzML/_sources/custom_fileclass.rst.txt This function creates an SQLite database and populates it with spectra from an mzML file. Each spectrum's ID and XML string are stored in separate columns. ```python import sqlite3 import os from pymzml import spec from pymzml.run import Reader def create_database_from_file(db_name, mzml_path): conn = sqlite3.connect(db_name+'.db') Run = Reader(os.path.abspath(mzml_path)) with conn: cursor = conn.cursor() cursor.execute("CREATE TABLE Spectra(ID INT, xml TEXT)") for spec in Run: params = (spec.ID, spec.to_string()) cursor.execute("INSERT INTO Spectra VALUES(?, ?)", params) return True ```