Pyteomics documentation v4.4.0

auxiliary - common functions and objects

«  xml - utilities for XML parsing   ::   Contents   ::   version - Pyteomics version information  »

auxiliary - common functions and objects

Math

linear_regression_vertical() - a wrapper for NumPy linear regression, minimizes the sum of squares of y errors.

linear_regression() - alias for linear_regression_vertical().

linear_regression_perpendicular() - a wrapper for NumPy linear regression, minimizes the sum of squares of (perpendicular) distances between the points and the line.

Target-Decoy Approach

qvalues() - estimate q-values for a set of PSMs.

filter() - filter PSMs to specified FDR level using TDA or given PEPs.

filter.chain() - a chained version of filter().

fdr() - estimate FDR in a set of PSMs using TDA or given PEPs.

Project infrastructure

PyteomicsError - a pyteomics-specific exception.

Helpers

Charge - a subclass of int for charge states.

ChargeList - a subclass of list for lists of charges.

print_tree() - display the structure of a complex nested dict.

memoize() - makes a memoization function decorator.

cvquery() - traverse an arbitrarily nested dictionary looking for keys which are cvstr instances, or objects with an attribute called accession.


pyteomics.auxiliary.math.linear_regression(x, y=None, a=None, b=None)[source]

Alias of linear_regression_vertical().

pyteomics.auxiliary.math.linear_regression_perpendicular(x, y=None)[source]

Calculate coefficients of a linear regression y = a * x + b. The fit minimizes perpendicular distances between the points and the line.

Requires numpy.

Parameters:y (x,) – 1-D arrays of floats. If y is omitted, x must be a 2-D array of shape (N, 2).
Returns:out – The structure is (a, b, r, stderr), where a – slope coefficient, b – free term, r – Peason correlation coefficient, stderr – standard deviation.
Return type:4-tuple of float
pyteomics.auxiliary.math.linear_regression_vertical(x, y=None, a=None, b=None)[source]

Calculate coefficients of a linear regression y = a * x + b. The fit minimizes vertical distances between the points and the line.

Requires numpy.

Parameters:
  • y (x,) – 1-D arrays of floats. If y is omitted, x must be a 2-D array of shape (N, 2).
  • a (float, optional) – If specified then the slope coefficient is fixed and equals a.
  • b (float, optional) – If specified then the free term is fixed and equals b.
Returns:

out – The structure is (a, b, r, stderr), where a – slope coefficient, b – free term, r – Peason correlation coefficient, stderr – standard deviation.

Return type:

4-tuple of float

pyteomics.auxiliary.target_decoy.fdr(psms=None, formula=1, is_decoy=None, ratio=1, correction=0, pep=None, decoy_prefix='DECOY_', decoy_suffix=None)

Estimate FDR of a data set using TDA or given PEP values. Two formulas can be used. The first one (default) is:

FDR = \frac{N_{decoy}}{N_{target} * ratio}

The second formula is:

FDR = \frac{N_{decoy} * (1 + \frac{1}{ratio})}{N_{total}}

Note

This function is less versatile than qvalues(). To obtain FDR, you can call qvalues() and take the last q-value. This function can be used (with correction = 0 or 1) when numpy is not available.

Parameters:
  • psms (iterable, optional) – An iterable of PSMs, e.g. as returned by read(). Not needed if is_decoy is an iterable.
  • formula (int, optional) – Can be either 1 or 2, defines which formula should be used for FDR estimation. Default is 1.
  • is_decoy (callable, iterable, or str) – If callable, should accept exactly one argument (PSM) and return a truthy value if the PSM is considered decoy. Default is is_decoy(). If array-like, should contain float values for all given PSMs. If string, it is used as a field name (PSMs must be in a record array or a pandas.DataFrame).
  • pep (callable, iterable, or str, optional) –

    If callable, a function used to determine the posterior error probability (PEP). Should accept exactly one argument (PSM) and return a float. If array-like, should contain float values for all given PSMs. If string, it is used as a field name (PSMs must be in a record array or a pandas.DataFrame).

    Note

    If this parameter is given, then PEP values will be used to calculate FDR. Otherwise, decoy PSMs will be used instead. This option conflicts with: is_decoy, formula, ratio, correction.

  • ratio (float, optional) – The size ratio between the decoy and target databases. Default is 1. In theory, the “size” of the database is the number of theoretical peptides eligible for assignment to spectra that are produced by in silico cleavage of that database.
  • correction (int or float, optional) –

    Possible values are 0, 1 and 2, or floating point numbers between 0 and 1.

    0 (default): no correction;

    1: enable “+1” correction. This accounts for the probability that a false positive scores better than the first excluded decoy PSM;

    2: this also corrects that probability for finite size of the sample, so the correction will be slightly less than “+1”.

    If a floating point number is given, then instead of the expectation value for the number of false PSMs, the confidence value is used. The value of correction is then interpreted as desired confidence level. E.g., if correction=0.95, then the calculated q-values do not exceed the “real” q-values with 95% probability.

    See this paper for further explanation.

    Note

    Requires numpy, if correction is a float or 2.

    Note

    Correction is only needed if the PSM set at hand was obtained using TDA filtering based on decoy counting (as done by using filter() without correction).

Returns:

out – The estimation of FDR, (roughly) between 0 and 1.

Return type:

float

pyteomics.auxiliary.target_decoy.filter(*args, **kwargs)

Read args and yield only the PSMs that form a set with estimated false discovery rate (FDR) not exceeding fdr.

Requires numpy and, optionally, pandas.

Parameters:
  • args (positional) – Iterables to read PSMs from. All positional arguments are chained. The rest of the arguments must be named.
  • fdr (float, keyword only, 0 <= fdr <= 1) – Desired FDR level.
  • key (callable / array-like / iterable / str, keyword only) –

    A function used for sorting of PSMs. Should accept exactly one argument (PSM) and return a number (the smaller the better). The default is a function that tries to extract e-value from the PSM.

    Warning

    The default function may not work with your files, because format flavours are diverse.

  • reverse (bool, keyword only, optional) – If True, then PSMs are sorted in descending order, i.e. the value of the key function is higher for better PSMs. Default is False.
  • is_decoy (callable / array-like / iterable / str, keyword only) – A function used to determine if the PSM is decoy or not. Should accept exactly one argument (PSM) and return a truthy value if the PSM should be considered decoy.
  • remove_decoy (bool, keyword only, optional) –

    Defines whether decoy matches should be removed from the output. Default is True.

    Note

    If set to False, then by default the decoy PSMs will be taken into account when estimating FDR. Refer to the documentation of fdr() for math; basically, if remove_decoy is True, then formula 1 is used to control output FDR, otherwise it’s formula 2. This can be changed by overriding the formula argument.

  • formula (int, keyword only, optional) – Can be either 1 or 2, defines which formula should be used for FDR estimation. Default is 1 if remove_decoy is True, else 2 (see fdr() for definitions).
  • ratio (float, keyword only, optional) – The size ratio between the decoy and target databases. Default is 1. In theory, the “size” of the database is the number of theoretical peptides eligible for assignment to spectra that are produced by in silico cleavage of that database.
  • correction (int or float, keyword only, optional) –

    Possible values are 0, 1 and 2, or floating point numbers between 0 and 1.

    0 (default): no correction;

    1: enable “+1” correction. This accounts for the probability that a false positive scores better than the first excluded decoy PSM;

    2: this also corrects that probability for finite size of the sample, so the correction will be slightly less than “+1”.

    If a floating point number is given, then instead of the expectation value for the number of false PSMs, the confidence value is used. The value of correction is then interpreted as desired confidence level. E.g., if correction=0.95, then the calculated q-values do not exceed the “real” q-values with 95% probability.

    See this paper for further explanation.

  • pep (callable / array-like / iterable / str, keyword only, optional) –

    If callable, a function used to determine the posterior error probability (PEP). Should accept exactly one argument (PSM) and return a float. If array-like, should contain float values for all given PSMs. If string, it is used as a field name (PSMs must be in a record array or a DataFrame).

    Note

    If this parameter is given, then PEP values will be used to calculate q-values. Otherwise, decoy PSMs will be used instead. This option conflicts with: is_decoy, remove_decoy, formula, ratio, correction. key can still be provided. Without key, PSMs will be sorted by PEP.

  • full_output (bool, keyword only, optional) –

    If True, then an array of PSM objects is returned. Otherwise, an iterator / context manager object is returned, and the files are parsed twice. This saves some RAM, but is ~2x slower. Default is True.

    Note

    The name for the parameter comes from the fact that it is internally passed to qvalues().

  • q_label (str, optional) – Field name for q-value in the output. Default is 'q'.
  • score_label (str, optional) – Field name for score in the output. Default is 'score'.
  • decoy_label (str, optional) – Field name for the decoy flag in the output. Default is 'is decoy'.
  • pep_label (str, optional) – Field name for PEP in the output. Default is 'PEP'.
  • **kwargs (passed to the chain() function.) –
Returns:

out

Return type:

iterator or numpy.ndarray or pandas.DataFrame

pyteomics.auxiliary.target_decoy.qvalues(*args, **kwargs)

Read args and return a NumPy array with scores and q-values. q-values are calculated either using TDA or based on provided values of PEP.

Requires numpy (and optionally pandas).

Parameters:
  • args (positional) – Iterables to read PSMs from. All positional arguments are chained. The rest of the arguments must be named.
  • key (callable / array-like / iterable / str, keyword only) –

    If callable, a function used for sorting of PSMs. Should accept exactly one argument (PSM) and return a number (the smaller the better). If array-like, should contain scores for all given PSMs. If string, it is used as a field name (PSMs must be in a record array or a DataFrame).

    Warning

    The default function may not work with your files, because format flavours are diverse.

  • reverse (bool, keyword only, optional) – If True, then PSMs are sorted in descending order, i.e. the value of the key function is higher for better PSMs. Default is False.
  • is_decoy (callable / array-like / iterable / str, keyword only) – If callable, a function used to determine if the PSM is decoy or not. Should accept exactly one argument (PSM) and return a truthy value if the PSM should be considered decoy. If array-like, should contain boolean values for all given PSMs. If string, it is used as a field name (PSMs must be in a record array or a DataFrame).
  • pep (callable / array-like / iterable / str, keyword only, optional) –

    If callable, a function used to determine the posterior error probability (PEP). Should accept exactly one argument (PSM) and return a float. If array-like, should contain float values for all given PSMs. If string, it is used as a field name (PSMs must be in a record array or a DataFrame).

    Note

    If this parameter is given, then PEP values will be used to calculate q-values. Otherwise, decoy PSMs will be used instead. This option conflicts with: is_decoy, remove_decoy, formula, ratio, correction. key can still be provided. Without key, PSMs will be sorted by PEP.

  • remove_decoy (bool, keyword only, optional) –

    Defines whether decoy matches should be removed from the output. Default is False.

    Note

    If set to False, then by default the decoy PSMs will be taken into account when estimating FDR. Refer to the documentation of fdr() for math; basically, if remove_decoy is True, then formula 1 is used to control output FDR, otherwise it’s formula 2. This can be changed by overriding the formula argument.

  • formula (int, keyword only, optional) – Can be either 1 or 2, defines which formula should be used for FDR estimation. Default is 1 if remove_decoy is True, else 2 (see fdr() for definitions).
  • ratio (float, keyword only, optional) – The size ratio between the decoy and target databases. Default is 1. In theory, the “size” of the database is the number of theoretical peptides eligible for assignment to spectra that are produced by in silico cleavage of that database.
  • correction (int or float, keyword only, optional) –

    Possible values are 0, 1 and 2, or floating point numbers between 0 and 1.

    0 (default): no correction;

    1: enable “+1” correction. This accounts for the probability that a false positive scores better than the first excluded decoy PSM;

    2: this also corrects that probability for finite size of the sample, so the correction will be slightly less than “+1”.

    If a floating point number is given, then instead of the expectation value for the number of false PSMs, the confidence value is used. The value of correction is then interpreted as desired confidence level. E.g., if correction=0.95, then the calculated q-values do not exceed the “real” q-values with 95% probability.

    See this paper for further explanation.

  • q_label (str, optional) – Field name for q-value in the output. Default is 'q'.
  • score_label (str, optional) – Field name for score in the output. Default is 'score'.
  • decoy_label (str, optional) – Field name for the decoy flag in the output. Default is 'is decoy'.
  • pep_label (str, optional) – Field name for PEP in the output. Default is 'PEP'.
  • full_output (bool, keyword only, optional) – If True, then the returned array has PSM objects along with scores and q-values. Default is False.
  • **kwargs (passed to the chain() function.) –
Returns:

out – A sorted array of records with the following fields:

  • ’score’: np.float64
  • ’is decoy’: np.bool_
  • ’q’: np.float64
  • ’psm’: np.object_ (if full_output is True)

Return type:

numpy.ndarray

pyteomics.auxiliary.target_decoy.sigma_T(psms, is_decoy, ratio=1)[source]

Calculates the standard error for the number of false positive target PSMs.

The formula is:

.. math ::
sigma(T) = sqrt{frac{(d + 1) cdot {p}}{(1 - p)^{2}}} = sqrt{frac{d+1}{r^{2}} cdot (r+1)}

This estimation is accurate for low FDRs. See the article for more details.

pyteomics.auxiliary.target_decoy.sigma_fdr(psms=None, formula=1, is_decoy=None, ratio=1)[source]

Calculates the standard error of FDR using the formula for negative binomial distribution. See sigma_T() for math. This estimation is accurate for low FDRs. See also the article for more details.

class pyteomics.auxiliary.utils.BinaryDataArrayTransformer[source]

Bases: object

A base class that provides methods for reading base64-encoded binary arrays.

compression_type_map

Maps compressor type name to decompression function

Type:dict
__init__

Initialize self. See help(type(self)) for accurate signature.

class binary_array_record[source]

Bases: pyteomics.auxiliary.utils.binary_array_record

Hold all of the information about a base64 encoded array needed to decode the array.

__init__

Initialize self. See help(type(self)) for accurate signature.

compression

Alias for field number 1

count()

Return number of occurrences of value.

data

Alias for field number 0

decode()[source]

Decode data into a numerical array

Returns:
Return type:np.ndarray
dtype

Alias for field number 2

index()

Return first index of value.

Raises ValueError if the value is not present.

key

Alias for field number 4

source

Alias for field number 3

decode_data_array(source, compression_type=None, dtype=<class 'numpy.float64'>)[source]

Decode a base64-encoded, compressed bytestring into a numerical array.

Parameters:
  • source (bytes) – A base64 string encoding a potentially compressed numerical array.
  • compression_type (str, optional) – The name of the compression method used before encoding the array into base64.
  • dtype (type, optional) – The data type to use to decode the binary array from the decompressed bytes.
Returns:

Return type:

np.ndarray

pyteomics.auxiliary.utils.memoize(maxsize=1000)[source]

Make a memoization decorator. A negative value of maxsize means no size limit.

pyteomics.auxiliary.utils.print_tree(d, indent_str=' -> ', indent_count=1)[source]

Read a nested dict (with strings as keys) and print its structure.

class pyteomics.auxiliary.structures.BasicComposition(*args, **kwargs)[source]

Bases: collections.defaultdict, collections.Counter

A generic dictionary for compositions. Keys should be strings, values should be integers. Allows simple arithmetics.

__init__(*args, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

clear() → None. Remove all items from D.
copy() → a shallow copy of D.[source]
default_factory

Factory for default value called by __missing__().

elements()

Iterator over elements repeating each as many times as its count.

>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']

# Knuth’s example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors … product *= factor # and multiply them >>> product 1836

Note, if an element’s count has been set to zero or is a negative number, elements() will ignore it.

classmethod fromkeys(iterable, v=None)

Create a new dictionary with keys from iterable and values set to value.

get()

Return the value for key if key is in the dictionary, else default.

items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
most_common(n=None)

List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts.

>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
pop(k[, d]) → v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised

popitem() → (k, v), remove and return some (key, value) pair as a

2-tuple; but raise KeyError if D is empty.

setdefault()

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

subtract(**kwds)

Like dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts.

Source can be an iterable, a dictionary, or another Counter instance.

>>> 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
update(**kwds)

Like dict.update() but add counts instead of replacing them.

Source can be an iterable, a dictionary, or another Counter instance.

>>> 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
values() → an object providing a view on D's values
class pyteomics.auxiliary.structures.CVQueryEngine[source]

Bases: object

Traverse an arbitrarily nested dictionary looking for keys which are cvstr instances, or objects with an attribute called accession.

__init__

Initialize self. See help(type(self)) for accurate signature.

index(data)[source]

Construct a flat dict whose keys are the accession numbers for all qualified keys in data and whose values are the mapped values from data.

query(data, accession)[source]

Search data for a key with the accession number accession. Returns None if not found.

class pyteomics.auxiliary.structures.Charge[source]

Bases: int

A subclass of int. Can be constructed from strings in “N+” or “N-” format, and the string representation of a Charge is also in that format.

__init__

Initialize self. See help(type(self)) for accurate signature.

bit_length()

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate()

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes()

Return the integer represented by the given array of bytes.

bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
signed
Indicates whether two’s complement is used to represent the integer.
imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes()

Return an array of bytes representing an integer.

length
Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes.
byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
signed
Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
class pyteomics.auxiliary.structures.ChargeList(*args, **kwargs)[source]

Bases: list

Just a list of :py:class:`Charge`s. When printed, looks like an enumeration of the list contents. Can also be constructed from such strings (e.g. “2+, 3+ and 4+”).

__init__(*args, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

append()

Append object to the end of the list.

clear()

Remove all items from list.

copy()

Return a shallow copy of the list.

count()

Return number of occurrences of value.

extend()

Extend list by appending elements from the iterable.

index()

Return first index of value.

Raises ValueError if the value is not present.

insert()

Insert object before index.

pop()

Remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

remove()

Remove first occurrence of value.

Raises ValueError if the value is not present.

reverse()

Reverse IN PLACE.

sort()

Stable sort IN PLACE.

class pyteomics.auxiliary.structures.Ion(*args, **kwargs)[source]

Bases: str

Represents an Ion, right now just a subclass of String.

__init__(*args, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center()

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) → int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode()

Encode the string using the codec registered for encoding.

encoding
The encoding in which to encode the string.
errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
endswith(suffix[, start[, end]]) → bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs()

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) → int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) → str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{‘ and ‘}’).

format_map(mapping) → str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{‘ and ‘}’).

index(sub[, start[, end]]) → int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Use keyword.iskeyword() to test for reserved identifiers such as “def” and “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join()

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust()

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip()

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition()

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

replace()

Return a copy with all occurrences of substring old replaced by new.

count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) → int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) → int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust()

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition()

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit()

Return a list of the words in the string, using sep as the delimiter string.

sep
The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.
maxsplit
Maximum number of splits to do. -1 (the default value) means no limit.

Splits are done starting at the end of the string and working to the front.

rstrip()

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split()

Return a list of the words in the string, using sep as the delimiter string.

sep
The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.
maxsplit
Maximum number of splits to do. -1 (the default value) means no limit.
splitlines()

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) → bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip()

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate()

Replace each character in the string using the given translation table.

table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill()

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

exception pyteomics.auxiliary.structures.PyteomicsError(msg, *values)[source]

Bases: Exception

Exception raised for errors in Pyteomics library.

message

Error message.

Type:str
__init__(msg, *values)[source]

Initialize self. See help(type(self)) for accurate signature.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

pyteomics.auxiliary.structures.clear_unit_cv_table()[source]

Clear the module-level unit name and controlled vocabulary accession table.

class pyteomics.auxiliary.structures.cvstr[source]

Bases: str

A helper class to associate a controlled vocabullary accession number with an otherwise plain str object

__init__

Initialize self. See help(type(self)) for accurate signature.

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center()

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) → int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode()

Encode the string using the codec registered for encoding.

encoding
The encoding in which to encode the string.
errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
endswith(suffix[, start[, end]]) → bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs()

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) → int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) → str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{‘ and ‘}’).

format_map(mapping) → str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{‘ and ‘}’).

index(sub[, start[, end]]) → int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Use keyword.iskeyword() to test for reserved identifiers such as “def” and “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join()

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust()

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip()

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition()

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

replace()

Return a copy with all occurrences of substring old replaced by new.

count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) → int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) → int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust()

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition()

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit()

Return a list of the words in the string, using sep as the delimiter string.

sep
The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.
maxsplit
Maximum number of splits to do. -1 (the default value) means no limit.

Splits are done starting at the end of the string and working to the front.

rstrip()

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split()

Return a list of the words in the string, using sep as the delimiter string.

sep
The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.
maxsplit
Maximum number of splits to do. -1 (the default value) means no limit.
splitlines()

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) → bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip()

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate()

Replace each character in the string using the given translation table.

table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill()

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

class pyteomics.auxiliary.structures.unitfloat[source]

Bases: float

__init__

Initialize self. See help(type(self)) for accurate signature.

as_integer_ratio()

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original float and with a positive denominator.

Raise OverflowError on infinities and a ValueError on NaNs.

>>> (10.0).as_integer_ratio()
(10, 1)
>>> (0.0).as_integer_ratio()
(0, 1)
>>> (-.25).as_integer_ratio()
(-1, 4)
conjugate()

Return self, the complex conjugate of any float.

fromhex()

Create a floating-point number from a hexadecimal string.

>>> float.fromhex('0x1.ffffp10')
2047.984375
>>> float.fromhex('-0x1p-1074')
-5e-324
hex()

Return a hexadecimal representation of a floating-point number.

>>> (-0.1).hex()
'-0x1.999999999999ap-4'
>>> 3.14159.hex()
'0x1.921f9f01b866ep+1'
imag

the imaginary part of a complex number

is_integer()

Return True if the float is an integer.

real

the real part of a complex number

class pyteomics.auxiliary.structures.unitint[source]

Bases: int

__init__

Initialize self. See help(type(self)) for accurate signature.

bit_length()

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate()

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes()

Return the integer represented by the given array of bytes.

bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
signed
Indicates whether two’s complement is used to represent the integer.
imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes()

Return an array of bytes representing an integer.

length
Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes.
byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
signed
Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
class pyteomics.auxiliary.structures.unitstr[source]

Bases: str

__init__

Initialize self. See help(type(self)) for accurate signature.

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center()

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) → int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode()

Encode the string using the codec registered for encoding.

encoding
The encoding in which to encode the string.
errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
endswith(suffix[, start[, end]]) → bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs()

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) → int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) → str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{‘ and ‘}’).

format_map(mapping) → str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{‘ and ‘}’).

index(sub[, start[, end]]) → int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Use keyword.iskeyword() to test for reserved identifiers such as “def” and “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join()

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust()

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip()

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition()

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

replace()

Return a copy with all occurrences of substring old replaced by new.

count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) → int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) → int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust()

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition()

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit()

Return a list of the words in the string, using sep as the delimiter string.

sep
The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.
maxsplit
Maximum number of splits to do. -1 (the default value) means no limit.

Splits are done starting at the end of the string and working to the front.

rstrip()

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split()

Return a list of the words in the string, using sep as the delimiter string.

sep
The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.
maxsplit
Maximum number of splits to do. -1 (the default value) means no limit.
splitlines()

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) → bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip()

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate()

Replace each character in the string using the given translation table.

table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill()

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

class pyteomics.auxiliary.file_helpers.ChainBase(*sources, **kwargs)[source]

Bases: object

Chain sequence_maker() for several sources into a single iterable. Positional arguments should be sources like file names or file objects. Keyword arguments are passed to the sequence_maker() function.

sources

Sources for creating new sequences from, such as paths or file-like objects

Type:Iterable
kwargs

Additional arguments used to instantiate each sequence

Type:Mapping
__init__(*sources, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

map(target=None, processes=-1, queue_timeout=4, args=None, kwargs=None, **_kwargs)[source]

Execute the target function over entries of this object across up to processes processes.

Results will be returned out of order.

Parameters:
  • target (Callable, optional) – The function to execute over each entry. It will be given a single object yielded by the wrapped iterator as well as all of the values in args and kwargs
  • processes (int, optional) – The number of worker processes to use. If negative, the number of processes will match the number of available CPUs.
  • queue_timeout (float, optional) – The number of seconds to block, waiting for a result before checking to see if all workers are done.
  • args (Sequence, optional) – Additional positional arguments to be passed to the target function
  • kwargs (Mapping, optional) – Additional keyword arguments to be passed to the target function
  • **_kwargs – Additional keyword arguments to be passed to the target function
Yields:

object – The work item returned by the target function.

class pyteomics.auxiliary.file_helpers.FileReader(source, **kwargs)[source]

Bases: pyteomics.auxiliary.file_helpers.IteratorContextManager

Abstract class implementing context manager protocol for file readers.

__init__(source, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

reset()[source]

Resets the iterator to its initial state.

class pyteomics.auxiliary.file_helpers.FileReadingProcess(reader_spec, target_spec, qin, qout, args_spec, kwargs_spec)[source]

Bases: multiprocessing.context.Process

Process that does a share of distributed work on entries read from file. Reconstructs a reader object, parses an entries from given indexes, optionally does additional processing, sends results back.

The reader class must support the __getitem__() dict-like lookup.

__init__(reader_spec, target_spec, qin, qout, args_spec, kwargs_spec)[source]

Initialize self. See help(type(self)) for accurate signature.

close()

Close the Process object.

This method releases resources held by the Process object. It is an error to call this method if the child process is still running.

daemon

Return whether process is a daemon

exitcode

Return exit code of process or None if it has yet to stop

ident

Return identifier (PID) of process or None if it has yet to start

is_alive()

Return whether process is alive

join(timeout=None)

Wait until child process terminates

kill()

Terminate process; sends SIGKILL signal or uses TerminateProcess()

pid

Return identifier (PID) of process or None if it has yet to start

run()[source]

Method to be run in sub-process; can be overridden in sub-class

sentinel

Return a file descriptor (Unix) or handle (Windows) suitable for waiting for process termination.

start()

Start child process

terminate()

Terminate process; sends SIGTERM signal or uses TerminateProcess()

class pyteomics.auxiliary.file_helpers.IndexSavingMixin(*args, **kwargs)[source]

Bases: pyteomics.auxiliary.file_helpers.NoOpBaseReader

Common interface for IndexSavingXML and IndexSavingTextReader.

__init__(*args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

classmethod prebuild_byte_offset_file(path)[source]

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
write_byte_offsets()[source]

Write the byte offsets in _offset_index to the file at _byte_offset_filename

class pyteomics.auxiliary.file_helpers.IndexSavingTextReader(source, **kwargs)[source]

Bases: pyteomics.auxiliary.file_helpers.IndexSavingMixin, pyteomics.auxiliary.file_helpers.IndexedTextReader

__init__(source, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

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
reset()

Resets the iterator to its initial state.

write_byte_offsets()

Write the byte offsets in _offset_index to the file at _byte_offset_filename

class pyteomics.auxiliary.file_helpers.IndexedReaderMixin(*args, **kwargs)[source]

Bases: pyteomics.auxiliary.file_helpers.NoOpBaseReader

Common interface for IndexedTextReader and IndexedXML.

__init__(*args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

class pyteomics.auxiliary.file_helpers.IndexedTextReader(source, **kwargs)[source]

Bases: pyteomics.auxiliary.file_helpers.IndexedReaderMixin, pyteomics.auxiliary.file_helpers.FileReader

Abstract class for text file readers that keep an index of records for random access. This requires reading the file in binary mode.

__init__(source, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

reset()

Resets the iterator to its initial state.

class pyteomics.auxiliary.file_helpers.OffsetIndex(*args, **kwargs)[source]

Bases: collections.OrderedDict, pyteomics.auxiliary.file_helpers.WritableIndex

An augmented OrderedDict that formally wraps getting items by index

__init__(*args, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

clear() → None. Remove all items from od.
copy() → a shallow copy of od
from_index(index, include_value=False)[source]

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 False.
Returns:

If include_value is True, a tuple of (key, value) at index else just the key at index.

Return type:

object

from_slice(spec, include_value=False)[source]

Get a slice along index in the ordered sequence of this mapping.

Parameters:
  • spec (slice) – The slice over the range of indices to retrieve
  • include_value (bool) – Whether to return both the key and the value or just the key. Defaults to False
Returns:

If include_value is True, a tuple of (key, value) at index else just the key at index for each index in spec

Return type:

list

fromkeys()

Create a new ordered dictionary with keys from iterable and values set to value.

get()

Return the value for key if key is in the dictionary, else default.

index_sequence

Keeps a cached copy of the items() sequence stored as a tuple to avoid repeatedly copying the sequence over many method calls.

Returns:
Return type:tuple
items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
move_to_end()

Move an existing element to the end (or beginning if last is false).

Raise KeyError if the element does not exist.

pop(k[, d]) → v, remove specified key and return the corresponding[source]

value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem()

Remove and return a (key, value) pair from the dictionary.

Pairs are returned in LIFO order if last is true or FIFO order if false.

setdefault()

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) → None. Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() → an object providing a view on D's values
class pyteomics.auxiliary.file_helpers.TableJoiner(*sources, **kwargs)[source]

Bases: pyteomics.auxiliary.file_helpers.ChainBase

__init__(*sources, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

map(target=None, processes=-1, queue_timeout=4, args=None, kwargs=None, **_kwargs)

Execute the target function over entries of this object across up to processes processes.

Results will be returned out of order.

Parameters:
  • target (Callable, optional) – The function to execute over each entry. It will be given a single object yielded by the wrapped iterator as well as all of the values in args and kwargs
  • processes (int, optional) – The number of worker processes to use. If negative, the number of processes will match the number of available CPUs.
  • queue_timeout (float, optional) – The number of seconds to block, waiting for a result before checking to see if all workers are done.
  • args (Sequence, optional) – Additional positional arguments to be passed to the target function
  • kwargs (Mapping, optional) – Additional keyword arguments to be passed to the target function
  • **_kwargs – Additional keyword arguments to be passed to the target function
Yields:

object – The work item returned by the target function.

class pyteomics.auxiliary.file_helpers.TimeOrderedIndexedReaderMixin(*args, **kwargs)[source]

Bases: pyteomics.auxiliary.file_helpers.IndexedReaderMixin

__init__(*args, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

«  xml - utilities for XML parsing   ::   Contents   ::   version - Pyteomics version information  »