### Download example MGF and pepXML files Source: https://pyteomics.readthedocs.io/en/latest/examples/example_msms.html Downloads example MGF and pepXML files if they are not already present in the current directory. This is useful for running the example locally. ```python for fname in ('mgf', 'pep.xml'): if not os.path.isfile('example.' + fname): headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'} url = 'http://pyteomics.readthedocs.io/en/latest/_static/example.' + fname request = Request(url, None, headers) target_name = 'example.' + fname with urlopen(request) as response, open(target_name, 'wb') as fout: print('Downloading ' + target_name + '...') fout.write(response.read()) ``` -------------------------------- ### Unitfloat Time Conversion Example Source: https://pyteomics.readthedocs.io/en/latest/data.html Example demonstrating the conversion of seconds to minutes using the in_minutes function. Requires importing unitfloat. ```python >>> seconds = unitfloat(93.5, "second") >>> minutes = in_minutes(seconds) >>> minutes 1.55833 ``` -------------------------------- ### startswith() Source: https://pyteomics.readthedocs.io/en/latest/api/auxiliary.html Returns True if the string starts with the specified prefix, False otherwise. Can check for multiple prefixes. ```APIDOC ## startswith() ### Description Return True if the string starts with the specified prefix, False otherwise. ### Parameters #### Positional Parameters - **prefix** (str or tuple of str) - A string or a tuple of strings to try. - **start** (int, optional) - Optional start position. Default: start of the string. - **end** (int, optional) - Optional stop position. Default: end of the string. ``` -------------------------------- ### Counter Prime Factors Example Source: https://pyteomics.readthedocs.io/en/latest/api/auxiliary.html Illustrates using Counter to store prime factors and calculating their product using math.prod. ```python >>> import math >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> math.prod(prime_factors.elements()) 1836 ``` -------------------------------- ### Counter Elements Example Source: https://pyteomics.readthedocs.io/en/latest/api/auxiliary.html Demonstrates iterating over elements of a Counter, repeating each as many times as its count. ```python >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] ``` -------------------------------- ### CVParamParser Initialization Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/xml.html The CVParamParser requires the 'psims' library to be installed. If 'psims' is not available, an error will be raised upon instantiation. ```APIDOC ## CVParamParser.__init__ ### Description Initializes the CVParamParser. This constructor checks for the presence of the 'psims' library and raises a PyteomicsError if it's not installed, as it's a dependency for parsing PSI formats. ### Method __init__(self, *args, **kwargs) ### Parameters *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. ### Raises PyteomicsError: If the 'psims' library is not available. ``` -------------------------------- ### CVParamParser Initialization Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/xml.html Initializes CVParamParser, ensuring the 'psims' library is available. Raises PyteomicsError if 'psims' is not installed. ```python def __init__(self, *args, **kwargs): super(CVParamParser, self).__init__(*args, **kwargs) if not _has_psims: raise PyteomicsError('Parsing PSI formats requires `psims`.') ``` -------------------------------- ### Get Entries Between Two Keys Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/auxiliary/file_helpers.html Retrieves all entries (keys or key-value pairs) between a start and stop key, inclusive. Handles cases where start or stop keys are None. ```python def between(self, start, stop, include_value=False): keys = list(self) if start is not None: try: start_index = keys.index(start) except ValueError: raise KeyError(start) else: start_index = 0 if stop is not None: try: stop_index = keys.index(stop) except ValueError: raise KeyError(stop) else: stop_index = len(keys) - 1 if start is None or stop is None: pass # won't switch indices else: start_index, stop_index = min(start_index, stop_index), max(start_index, stop_index) if include_value: return [(k, self[k]) for k in keys[start_index:stop_index + 1]] return keys[start_index:stop_index + 1] ``` -------------------------------- ### Get Original Indices of Digested Peptides Source: https://pyteomics.readthedocs.io/en/latest/parser.html Use `pyteomics.parser.xcleave()` to get the original indices of peptides after in silico digestion. This function is an alternative to `cleave()` when the starting position of each fragment is required. ```python >>> parser.xcleave('AKAKBK', 'trypsin', 0) [(0, 'AK'), (2, 'AK'), (4, 'BK')] ``` -------------------------------- ### Initialize PRIDEBackend Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/usi.html Instantiate the PRIDEBackend to query the PRIDE PROXI service. Accepts optional keyword arguments for configuration. ```python backend = PRIDEBackend() backend = PRIDEBackend(version='1.1') backend = PRIDEBackend(version='1.1', timeout=10) ``` -------------------------------- ### Change directory and set plot style Source: https://pyteomics.readthedocs.io/en/latest/_downloads/5f78846e64ec5a841c87d46d7e02f626/filtering.ipynb Changes the current working directory to the example data directory and applies a 'seaborn-darkgrid' style to plots. This is a setup step before data processing. ```python # switch to directory with data %cd example3 pylab.style.use('seaborn-darkgrid') ``` -------------------------------- ### Initialize MassIVEBackend Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/usi.html Instantiate the MassIVEBackend to query the MassIVE PROXI service. Accepts optional keyword arguments for configuration. ```python backend = MassIVEBackend() backend = MassIVEBackend(version='1.1') backend = MassIVEBackend(version='1.1', timeout=10) ``` -------------------------------- ### Initialize JPOSTBackend Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/usi.html Instantiate the JPOSTBackend to query the jPOST PROXI service. Accepts optional keyword arguments for configuration. ```python backend = JPOSTBackend() backend = JPOSTBackend(timeout=10) ``` -------------------------------- ### Install Pyteomics with optional XML dependencies Source: https://pyteomics.readthedocs.io/en/latest/installation.html Install Pyteomics along with specific dependencies for XML parsing by specifying an extra. This installs Pyteomics, NumPy, and lxml. ```bash pip install pyteomics[XML] ``` -------------------------------- ### Initialize PeptideAtlasBackend Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/usi.html Instantiate the PeptideAtlasBackend to query the PeptideAtlas PROXI service. Accepts optional keyword arguments for configuration. ```python backend = PeptideAtlasBackend() backend = PeptideAtlasBackend(version='1.1') backend = PeptideAtlasBackend(version='1.1', timeout=10) ``` -------------------------------- ### Install Pyteomics with conda Source: https://pyteomics.readthedocs.io/en/latest/installation.html Use this command to install Pyteomics from the Bioconda channel using the conda package manager. ```bash conda install -c bioconda pyteomics ``` -------------------------------- ### Install Pyteomics with pip Source: https://pyteomics.readthedocs.io/en/latest/installation.html Use this command to install the main Pyteomics package using the pip package manager. ```bash pip install pyteomics ``` -------------------------------- ### Initialize VersionInfo and Version Constants Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/version.html Initializes the global `version_info` and `version` constants using the `__version__` string. ```python version_info = VersionInfo(__version__) version = __version__ ``` -------------------------------- ### InformationTag.__init__ Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/proforma.html Initializes an InformationTag. ```APIDOC ## InformationTag.__init__ ### Description Initializes an InformationTag. ### Parameters #### Path Parameters - **value** (any) - Required - The information value. - **extra** (list) - Optional - Additional tags. - **group_id** (any) - Optional - The group identifier. ``` -------------------------------- ### pyteomics.mzid.MzIdentML.get_by_id Source: https://pyteomics.readthedocs.io/en/latest/api/mzid.html Retrieves a specified entity by its ID. If the entity is a spectrum described in the offset index, it will be retrieved by seeking to its starting position; otherwise, it falls back to parsing from the start of the file. ```APIDOC ## pyteomics.mzid.MzIdentML.get_by_id ### Description Retrieve the requested entity by its id. If the entity is a spectrum described in the offset index, it will be retrieved by immediately seeking to the starting position of the entry, otherwise falling back to parsing from the start of the file. ### Parameters: * **elem_id** (_str_) – The id value of the entity to retrieve. * **id_key** (_str_ _,__optional_) – The name of the XML attribute to use for lookup. Defaults to `self._default_id_attr`. ### Return type: dict ``` -------------------------------- ### USI Retrieval Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/usi.html The `get` method retrieves spectrum data for a given USI from a PROXI service. The `__call__` method provides a convenient way to call `get` directly on the object. ```APIDOC ## get(usi) ### Description Retrieve a ``USI`` from the host PROXI service over the network. ### Parameters * **usi** (str or :class:`USI`) - The universal spectrum identifier to retrieve. ### Returns * **dict**: The spectrum as represented by the requested PROXI host. ## __call__(usi) ### Description Allows the object to be called directly like a function to retrieve spectrum data. ### Parameters * **usi** (str or :class:`USI`) - The universal spectrum identifier to retrieve. ### Returns * **dict**: The spectrum as represented by the requested PROXI host. ``` -------------------------------- ### Create Spectrum with Utility Backend Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/pylab_aux.html Initializes a spectrum object using the `spectrum_utils` backend. Requires `spectrum_utils>=0.4`. Allows specifying various parameters for spectrum processing like m/z range, intensity thresholds, and scaling. ```python def _spectrum_utils_create_spectrum(spectrum, *args, **kwargs): if sus is None: raise PyteomicsError('This backend requires `spectrum_utils>=0.4`.') # backend-specific parameters mz_range = kwargs.pop('mz_range', None) min_intensity = kwargs.pop('min_intensity', 0.0) max_num_peaks = kwargs.pop('max_num_peaks', None) scaling = kwargs.pop('scaling', None) max_intensity = kwargs.pop('max_intensity', None) ``` -------------------------------- ### CVQueryEngine Instance Initialization Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/auxiliary/structures.html Creates a ready-to-use instance of the CVQueryEngine. This instance can then be used for indexing and querying controlled vocabulary data. ```python '''A ready-to-use instance of :class:`~.CVQueryEngine`''' cvquery = CVQueryEngine() ``` -------------------------------- ### IndexedSPD.get_by_id Source: https://pyteomics.readthedocs.io/en/latest/api/fasta.html Get the entry by value of header string or extracted field. ```APIDOC ## IndexedSPD.get_by_id ### Description Get the entry by value of header string or extracted field. ### Method `get_by_id` ### Parameters #### Parameters - **key** – The key to search for. ``` -------------------------------- ### Initialize ProteomeExchangeBackend Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/usi.html Instantiate the ProteomeExchangeBackend to query the ProteomeExchange PROXI service. Accepts optional keyword arguments for configuration. ```python backend = ProteomeExchangeBackend() backend = ProteomeExchangeBackend(version='1.1') backend = ProteomeExchangeBackend(version='1.1', timeout=10) ``` -------------------------------- ### IndexedMGF Get Spectrum Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/mgf.html Retrieves a spectrum by its key using the get_by_id method. ```python def get_spectrum(self, key): return self.get_by_id(key) ``` -------------------------------- ### Iterfind.__init__ Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/xml.html Initializes the Iterfind object. ```APIDOC ## Iterfind.__init__ ### Description Initializes the Iterfind object with a parser, tag name, and configuration. ### Parameters - **parser** - The XML parser instance. - **tag_name** (str) - The name of the tag or XPath expression to find. - **kwargs** - Additional configuration options. ``` -------------------------------- ### Get the next item from the iterator Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/auxiliary/file_helpers.html Retrieves the next item from the iterator, initializing it if it hasn't been already. ```python def __next__(self): if self._iterator is None: self._iterator = self._iterate_over_series() return next(self._iterator) ``` -------------------------------- ### LocalizationMarker.__init__ Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/proforma.html Initializes a LocalizationMarker tag. ```APIDOC ## LocalizationMarker.__init__ ### Description Initializes a LocalizationMarker tag. ### Parameters #### Path Parameters - **value** (any) - Required - The localization value. - **extra** (list) - Optional - Additional tags. - **group_id** (any) - Required - The group identifier. ``` -------------------------------- ### Basic Usage of Indexed Parsers Source: https://pyteomics.readthedocs.io/en/latest/data.html Demonstrates how to instantiate and use indexed parsers for MGF files, including opening files, accessing parser objects, and closing them. It also shows how to use the `read()` function with `use_index=True`. ```APIDOC ## Basic usage Indexed parsers can be instantiated using the class name or the `read()` function: ``` In [1]: from pyteomics import mgf In [2]: f = mgf.IndexedMGF('tests/test.mgf') In [3]: f Out[3]: In [4]: f.close() In [5]: f = mgf.read('tests/test.mgf', use_index=True) In [6]: f Out[6]: ``` They support direct assignment and iteration or the with syntax, the same way as the older, iterative parsers. ``` -------------------------------- ### pyteomics.tandem.DataFrame Source: https://pyteomics.readthedocs.io/en/latest/api/tandem.html Reads X!Tandem output files into a pandas DataFrame. Requires the pandas library to be installed. ```APIDOC ## pyteomics.tandem.DataFrame ### Description Read X!Tandem output files into a `pandas.DataFrame`. Requires `pandas`. ### Parameters #### Query Parameters - **sep** (str or None) - Optional - Some values related to PSMs (such as protein information) are variable-length lists. If sep is a `str`, they will be packed into single string using this delimiter. If sep is `None`, they are kept as lists. Default is `None`. - **pd_kwargs** (dict) - Optional - Keyword arguments passed to the `pandas.DataFrame` constructor. #### Args - ***args** - Passed to `chain()`. - ****kwargs** - Passed to `chain()`. ### Returns **out** - A pandas DataFrame containing the X!Tandem output data. ### Return type pandas.DataFrame ``` -------------------------------- ### DataFrame Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/pepxml.html Reads pepXML output files into a pandas DataFrame. This function requires the pandas library to be installed. ```APIDOC ## DataFrame(*args, **kwargs) ### Description Read pepXML output files into a :py:class:`pandas.DataFrame`. Requires :py:mod:`pandas`. ### Parameters *args pepXML file names or objects. Passed to :py:func:`chain`. **kwargs Passed to :py:func:`chain`. by : str, keyword only, optional Can be :py:const:`"spectrum_query"` (default) or :py:const:`"search_hit"`. One row in the resulting dataframe corresponds to one element of the given type. If :py:const:`"spectrum_query"` is set, only the top search hit is shown in the dataframe. sep : str or None, keyword only, optional Some values related to PSMs (such as protein information) are variable-length lists. If `sep` is a :py:class:`str`, they will be packed into single string using this delimiter. If `sep` is :py:const:`None`, they are kept as lists. Default is :py:const:`None`. recursive : bool, keyword only, optional If :py:const:`False`, subelements will not be processed when extracting info from elements. Default is :py:const:`True`. iterative : bool, keyword only, optional Specifies whether iterative XML parsing should be used. Iterative parsing significantly reduces memory usage and may be just a little slower. When `retrieve_refs` is :py:const:`True`, however, it is highly recommended to disable iterative parsing if possible. Default value is :py:const:`True`. read_schema : bool, keyword only, optional If :py:const:`True`, attempt to extract information from the XML schema mentioned in the mzIdentML header. Otherwise, use default parameters. Not recommended without Internet connection or if you don't like to get the related warnings. pd_kwargs : dict, optional Keyword arguments passed to the :py:class:`pandas.DataFrame` constructor. ### Returns out : pandas.DataFrame ``` -------------------------------- ### prebuild_byte_offset_file Class Method Source: https://pyteomics.readthedocs.io/en/latest/api/mgf.html Constructs a new XML reader, builds its byte offset index, and writes it to a file. ```APIDOC classmethod prebuild_byte_offset_file(_path_) Construct a new XML reader, build its byte offset index and write it to file Parameters: path (_str_) – The path to the file to parse ``` -------------------------------- ### Initialize FeatureXML Parser Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/openms/featurexml.html Instantiate the FeatureXML parser for a given source. Supports schema reading, iterative parsing, and indexing for spectrum elements. ```python FeatureXML(source, read_schema=True, iterative=True, use_index=False) ``` -------------------------------- ### PositionLabelTag.__init__ Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/proforma.html Initializes a PositionLabelTag. ```APIDOC ## PositionLabelTag.__init__ ### Description Initializes a PositionLabelTag. ### Parameters #### Path Parameters - **value** (any) - Optional - The value for the tag. - **extra** (list) - Optional - Additional tags. - **group_id** (any) - Required - The group identifier. ``` -------------------------------- ### IndexedReaderMixin - Get by Index Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/auxiliary/file_helpers.html Retrieves an item from the reader by its positional index. Requires an offset index to be built. ```python def get_by_index(self, i): try: key = self.default_index.from_index(i, False) except AttributeError: raise PyteomicsError('Positional access requires building an offset index.') return self.get_by_id(key) ``` -------------------------------- ### Counter Most Common Example Source: https://pyteomics.readthedocs.io/en/latest/api/auxiliary.html Finds the N most common elements and their counts in a Counter. If N is None, all elements are listed. ```python >>> Counter('abracadabra').most_common(3) [('a', 5), ('b', 2), ('r', 2)] ``` -------------------------------- ### Unimod Database Initialization Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/mass/mass.html Initializes the Unimod database by parsing an XML file from a given source. Handles both file paths and URLs. Requires lxml for XML parsing. ```python from pyteomics import mass from pyteomics.mass import Unimod unimod_db = Unimod() print(len(unimod_db.mods)) ``` -------------------------------- ### Initialize ChainBase with sources and keyword arguments Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/auxiliary/file_helpers.html Initializes the ChainBase class with a variable number of sources and keyword arguments. These are stored for later use in creating sequences. ```python def __init__(self, *sources, **kwargs): self.sources = sources self.kwargs = kwargs self._iterator = None ``` -------------------------------- ### Instantiate Indexed MGF Parser Source: https://pyteomics.readthedocs.io/en/latest/data.html Demonstrates how to instantiate an indexed MGF parser using either the class name or the `read()` function. Note that indexed parsers require files to be opened in binary mode. ```python from pyteomics import mgf f = mgf.IndexedMGF('tests/test.mgf') f f.close() f = mgf.read('tests/test.mgf', use_index=True) f ``` -------------------------------- ### process_marker Function Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/proforma.html Processes a tag marker, which starts with '#'. It can identify PositionLabelTag or LocalizationMarker based on the tag's content. ```APIDOC def process_marker(tokens: Sequence[str]) -> Union[PositionLabelTag, LocalizationMarker]: '''Process a marker, which is a tag whose value starts with #. Parameters ---------- tokens: list or str The tag tokens to parse Returns ------- PositionLabelTag or LocalizationMarker ''' if tokens[1:3] == 'XL': return PositionLabelTag(None, group_id=''.join(tokens)) else: group_id = None value = None for i, c in enumerate(tokens): if c == '(': group_id = ''.join(tokens[:i]) if tokens[-1] != ')': raise Exception( "Localization marker with score missing closing parenthesis") value = float(''.join(tokens[i + 1:-1])) return LocalizationMarker(value, group_id=group_id) else: group_id = ''.join(tokens) ``` -------------------------------- ### Initialize Composition Object Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/mass/mass.html Demonstrates various ways to initialize a Composition object, including from formula, sequence, parsed sequence, split sequence, or a dictionary. Handles potential ambiguities and provides error handling for invalid inputs. ```python def __init__(self, *args, **kwargs): """ A Composition object stores a chemical composition of a substance. Basically it is a dict object, in which keys are the names of chemical elements and values contain integer numbers of corresponding atoms in a substance. The main improvement over dict is that Composition objects allow addition and subtraction. A Composition object can be initialized with one of the following arguments: formula, sequence, parsed_sequence or split_sequence. If none of these are specified, the constructor will look at the first positional argument and try to build the object from it. Without positional arguments, a Composition will be constructed directly from keyword arguments. If there's an ambiguity, i.e. the argument is both a valid sequence and a formula (such as 'HCN'), it will be treated as a sequence. You need to provide the 'formula' keyword to override this. .. warning:: Be careful when supplying a list with a parsed sequence or a split sequence as a keyword argument. It must be obtained with enabled `show_unmodified_termini` option. When supplying it as a positional argument, the option doesn't matter, because the positional argument is always converted to a sequence prior to any processing. Parameters ---------- formula : str, optional A string with a chemical formula. sequence : str, optional A polypeptide sequence string in modX notation. parsed_sequence : list of str, optional A polypeptide sequence parsed into a list of amino acids. split_sequence : list of tuples of str, optional A polypeptyde sequence parsed into a list of tuples (as returned be :py:func:`pyteomics.parser.parse` with ``split=True``). aa_comp : dict, optional A dict with the elemental composition of the amino acids (the default value is std_aa_comp). ion_comp : dict, optional A dict with the relative elemental compositions of peptide ion fragments (default is :py:data:`std_ion_comp`). ion_type : str, optional If specified, then the polypeptide is considered to be in the form of the corresponding ion. """ defaultdict.__init__(self, int) aa_comp = kwargs.get('aa_comp', std_aa_comp) kw_given = self._kw_sources.intersection(kwargs) if len(kw_given) > 1: raise PyteomicsError( 'Only one of {} can be specified!\n' 'Given: {}'.format(', '.join(self._kw_sources), ', '.join(kw_given))) elif kw_given: kwa = kw_given.pop() if kwa == 'formula': self._from_formula(kwargs['formula']) else: getattr(self, '_from_' + kwa)(kwargs[kwa], aa_comp) # can't build from kwargs elif args: if isinstance(args[0], dict): self._from_composition(args[0]) elif isinstance(args[0], str): try: self._from_sequence(args[0], aa_comp) except PyteomicsError: try: self._from_formula(args[0]) except PyteomicsError: raise PyteomicsError( 'Could not create a Composition object from ' 'string: "{}": not a valid sequence or ' 'formula'.format(args[0])) else: try: self._from_sequence(parser.tostring(args[0], True), aa_comp) except Exception: raise PyteomicsError( 'Could not create a Composition object from `{}`. A Composition object must be ' 'specified by sequence, parsed or split sequence, formula or dict.'.format(args[0])) else: self._from_composition(kwargs) ion_comp = kwargs.get('ion_comp', std_ion_comp) if 'ion_type' in kwargs: ion_type = kwargs['ion_type'] _warn_about_ion_type(ion_type, ion_comp) self += ion_comp[ion_type] # Charge is not supported in kwargs charge = self['H+'] if 'charge' in kwargs: if charge: raise PyteomicsError('Charge is specified both by the number of protons and `charge` in kwargs') else: warnings.warn( 'charge and charge carrier should be specified when calling mass(). ' 'Support for charge in Composition.__init__ will be removed in a future version.', FutureWarning) ``` -------------------------------- ### IndexedMGF Item From Offsets Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/mgf.html Reads a single spectrum from the MGF file using provided start and end offsets. ```python def _item_from_offsets(self, offsets): start, end = offsets lines = self._read_lines_from_offsets(start, end) return self._read_spectrum_lines(lines) ``` -------------------------------- ### Backend Implementations Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/usi.html Concrete implementations for various PROXI-compliant servers, each with its own URL template for constructing requests. ```APIDOC ## PeptideAtlasBackend ### Description Backend for querying the PeptideAtlas PROXI service. ### Initialization ```python PeptideAtlasBackend(**kwargs) ``` ## MassIVEBackend ### Description Backend for querying the MassIVE PROXI service. ### Initialization ```python MassIVEBackend(**kwargs) ``` ## PRIDEBackend ### Description Backend for querying the PRIDE PROXI service. ### Initialization ```python PRIDEBackend(**kwargs) ``` ## JPOSTBackend ### Description Backend for querying the jPOST PROXI service. ### Initialization ```python JPOSTBackend(**kwargs) ``` ## ProteomeExchangeBackend ### Description Backend for querying the ProteomeExchange PROXI service. ### Initialization ```python ProteomeExchangeBackend(**kwargs) ``` ``` -------------------------------- ### Get Entry by Integer Index Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/auxiliary/file_helpers.html Retrieves an entry (key or key-value pair) from the index using its integer position. ```python def from_index(self, index, include_value=False): '''Get an entry by its integer index in the ordered sequence of this mapping. Parameters ---------- index: int The index to retrieve. include_value: bool Whether to return both the key and the value or just the key. Defaults to :const:`False`. Returns ------- object: If ``include_value`` is :const:`True`, a tuple of (key, value) at ``index`` else just the key at ``index`` ''' items = self.index_sequence if include_value: return items[index] else: return items[index][0] ``` -------------------------------- ### Get State for IndexedTextReader Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/auxiliary/file_helpers.html Prepares the object's state for pickling, including the offset index and configuration attributes. ```python def __getstate__(self): state = super(IndexedTextReader, self).__getstate__() state['offset_index'] = self._offset_index for key in self._kw_keys: state[key] = getattr(self, key) return state ``` -------------------------------- ### Initialize MS1Base Parser Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/ms1.html Instantiate an MS1Base parser. Configure source, header usage, array conversion, data types, and encoding. Requires NumPy if array conversion is enabled. ```python parser = MS1Base(source='path/to/file.ms1', use_header=True, convert_arrays=1, dtype='f8', encoding='utf-8') ``` -------------------------------- ### Get Scan by Time Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/auxiliary/file_helpers.html Retrieves a scan by its acquisition time. Supports exact matches and nearest neighbor searches. ```python mid = (hi + lo) // 2 sid = scan_ids[mid] scan = self._reader.get_by_id(sid) scan_time = self._reader._get_time(scan) err = abs(scan_time - time) if err < best_error: best_error = err best_match = scan best_time = scan_time best_id = sid if scan_time == time: return sid, scan, scan_time elif (hi - lo) == 1: return best_id, best_match, best_time elif scan_time > time: hi = mid else: lo = mid ``` -------------------------------- ### Initialize MzML Parser Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/mzml.html Instantiate the MzML parser with various options for reading mzML files. Supports iterative parsing, indexing, data type conversion, and binary data decoding. ```python def read(source, read_schema=False, iterative=True, use_index=False, dtype=None, huge_tree=False, decode_binary=True, cv=None): """Parse `source` and iterate through spectra. Parameters ---------- source : str or file A path to a target mzML file or the file object itself. read_schema : bool, optional If :py:const:`True`, attempt to extract information from the XML schema mentioned in the mzML header. Otherwise, use default parameters. Not recommended without Internet connection or if you don't like to get the related warnings. iterative : bool, optional Defines whether iterative parsing should be used. It helps reduce memory usage at almost the same parsing speed. Default is :py:const:`True`. use_index : bool, optional Defines whether an index of byte offsets needs to be created for spectrum elements. Default is :py:const:`False`. dtype : type or dict, optional dtype to convert arrays to, one for both m/z and intensity arrays or one for each key. If :py:class:`dict`, keys should be 'm/z array' and 'intensity array'. decode_binary : bool, optional Defines whether binary data should be decoded and included in the output (under "m/z array", "intensity array", etc.). Default is :py:const:`True`. huge_tree : bool, optional This option is passed to the `lxml` parser and defines whether security checks for XML tree depth and node size should be disabled. Default is :py:const:`False`. Enable this option for trusted files to avoid XMLSyntaxError exceptions (e.g. `XMLSyntaxError: xmlSAX2Characters: huge text node`). cv : psims.controlled_vocabulary.controlled_vocabulary.ControlledVocabulary, optional An instance of PSI-MS CV. If provided, the parser will use it for type checking. Otherwise, a CV will be loaded from the Internet or from cache, if it is configured. .. seealso :: See `psims documentation `_ about cache configuration. Returns ------- out : iterator An iterator over the dicts with spectrum properties. """ return MzML(source, read_schema=read_schema, iterative=iterative, use_index=use_index, dtype=dtype, huge_tree=huge_tree, decode_binary=decode_binary) ``` -------------------------------- ### IndexedReaderMixin - Get by ID Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/auxiliary/file_helpers.html Retrieves an item from the reader using its unique identifier. Requires an offset index to be built. ```python def get_by_id(self, elem_id): index = self.default_index if index is None: raise PyteomicsError('Access by ID requires building an offset index.') offsets = index[elem_id] return self._item_from_offsets(offsets) ``` -------------------------------- ### FASTA Parser Initialization Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/fasta.html Initialize a FASTA parser for sequential reading. Supports iteration and 'with' syntax. Can handle custom parsers for description fields and file encoding. ```python from pyteomics import fasta # Example usage with a file path with fasta.FASTA('my_sequences.fasta') as f: for description, sequence in f: print(description, sequence) # Example with a file-like object import io fasta_string = ">seq1 description1\nSEQUENCE1\n>seq2 description2\nSEQUENCE2" with fasta.FASTA(io.StringIO(fasta_string)) as f: for description, sequence in f: print(description, sequence) ``` -------------------------------- ### Counter Update Example Source: https://pyteomics.readthedocs.io/en/latest/api/auxiliary.html Adds counts to a Counter using an iterable or another Counter. Handles multiple additions correctly. ```python >>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.update(d) # add elements from another counter >>> c['h'] # four 'h' in which, witch, and watch 4 ``` -------------------------------- ### write Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/fasta.html Creates a FASTA file from an iterable of sequence entries. Supports string or dictionary descriptions, with a special key for raw header content. ```APIDOC ## write ### Description Create a FASTA file with `entries`. ### Parameters * `entries` (iterable of (str/dict, str) tuples) - An iterable of 2-tuples in the form (description, sequence). If description is a dictionary, it must have a special key, whose value will be written as protein description. The special key is defined by the variable :py:const:`RAW_HEADER_KEY`. * `output` (file-like or str, optional) - A file open for writing or a path to write to. If the file exists, it will be opened for writing. Default is :py:const:`None`, which means write to standard output. .. note:: The default mode for output files specified by name has been changed from `a` to `w` in *pyteomics 4.6*. See `file_mode` to override the mode. * `file_mode` (str, keyword only, optional) - If `output` is a file name, defines the mode the file will be opened in. Otherwise will be ignored. Default is `'w'`. .. note :: The default changed from `'a'` in *pyteomics 4.6*. ### Returns * `output_file` (file object) - The file where the FASTA is written. ``` -------------------------------- ### Counter Subtract Example Source: https://pyteomics.readthedocs.io/en/latest/api/auxiliary.html Subtracts counts from a Counter using an iterable or another Counter. Counts can become zero or negative. ```python >>> c = Counter('which') >>> c.subtract('witch') # subtract elements from another iterable >>> c.subtract(Counter('watch')) # subtract elements from another counter >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch 0 >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch -1 ``` -------------------------------- ### Initialize Unimod Database Object Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/mass/unimod.html Initializes the Unimod object, either by loading from a specified database path or downloading a fresh copy from the default URL if the path is None or the database does not exist. ```python def __init__(self, path=None): """ Initialize the object from a database file. Parameters ---------- path : str or None, optional If :py:class:`str`, should point to a database. Use a dialect-specific prefix, like ``'sqlite://'``. If :py:const:`None` (default), a relational XML file will be downloaded from default location. """ if path is None: self.path = None self.session = load(_unimod_xml_download_url) else: self.path = path try: self.session = session(path) if self.session.query(Modification).first() is None: raise Exception() except Exception: # Database may not yet exist at that location self.session = load(_unimod_xml_download_url, path) self.session.query(Modification).first() ``` -------------------------------- ### prebuild_byte_offset_file Source: https://pyteomics.readthedocs.io/en/latest/api/mzmlb.html Construct a new XML reader, build its byte offset index and write it to file. ```APIDOC ## prebuild_byte_offset_file ### Description Construct a new XML reader, build its byte offset index and write it to file. ### Method `classmethod prebuild_byte_offset_file(_path_) ### Parameters #### Path Parameter * **path** (_str_) – The path to the file to parse ``` -------------------------------- ### process_marker Function Source: https://pyteomics.readthedocs.io/en/latest/_modules/pyteomics/proforma.html Processes a marker, which is a tag whose value starts with '#'. It distinguishes between PositionLabelTag and LocalizationMarker based on the token content. ```python def process_marker(tokens: Sequence[str]) -> Union[PositionLabelTag, LocalizationMarker]: '''Process a marker, which is a tag whose value starts with #. Parameters ---------- tokens: list or str The tag tokens to parse Returns ------- PositionLabelTag or LocalizationMarker ''' if tokens[1:3] == 'XL': return PositionLabelTag(None, group_id=''.join(tokens)) else: group_id = None value = None for i, c in enumerate(tokens): if c == '(': group_id = ''.join(tokens[:i]) if tokens[-1] != ')': raise Exception( "Localization marker with score missing closing parenthesis") value = float(''.join(tokens[i + 1:-1])) return LocalizationMarker(value, group_id=group_id) else: group_id = ''.join(tokens) ```