Pyteomics documentation v4.3a1

auxiliary - common functions and objects

Contents

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:
x, y : array_like of float

1-D arrays of floats. If y is omitted, x must be a 2-D array of shape (N, 2).

Returns:
out : 4-tuple of float

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

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:
x, y : array_like of float

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 : 4-tuple of float

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

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 : float

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

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:
positional args : iterables

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 : 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:
positional args : iterables

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 : numpy.ndarray

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)
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.

Attributes:
compression_type_map : dict

Maps compressor type name to decompression function

Methods

binary_array_record Hold all of the information about a base64 encoded array needed to decode the array.
decode_data_array(self, source[, …]) Decode a base64-encoded, compressed bytestring into a numerical array.
__init__(self, /, *args, **kwargs)

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.

Attributes:
compression

Alias for field number 1

data

Alias for field number 0

dtype

Alias for field number 2

key

Alias for field number 4

source

Alias for field number 3

Methods

count(self, value, /) Return number of occurrences of value.
decode(self) Decode data into a numerical array
index(self, value[, start, stop]) Return first index of value.
__init__(self, /, *args, **kwargs)

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

compression

Alias for field number 1

count(self, value, /)

Return number of occurrences of value.

data

Alias for field number 0

decode(self)[source]

Decode data into a numerical array

Returns:
np.ndarray
dtype

Alias for field number 2

index(self, value, start=0, stop=9223372036854775807, /)

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(self, 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:
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.

Attributes:
default_factory

Factory for default value called by __missing__().

Methods

clear()
copy(self)
elements(self) Iterator over elements repeating each as many times as its count.
fromkeys(iterable[, v]) Create a new dictionary with keys from iterable and values set to value.
get(self, key[, default]) Return the value for key if key is in the dictionary, else default.
items()
keys()
most_common(self[, n]) List the n most common elements and their counts from the most common to the least.
pop() If key is not found, d is returned if given, otherwise KeyError is raised
popitem() 2-tuple; but raise KeyError if D is empty.
setdefault(self, key[, default]) Insert key with a value of default if key is not in the dictionary.
subtract(\*args, \*\*kwds) Like dict.update() but subtracts counts instead of replacing them.
update(\*args, \*\*kwds) Like dict.update() but add counts instead of replacing them.
values()
__init__(self, *args, **kwargs)[source]

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

clear()
copy(self)[source]
default_factory

Factory for default value called by __missing__().

elements(self)

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(self, key, default=None, /)

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

items()
keys()
most_common(self, 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()

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

popitem()

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

setdefault(self, key, default=None, /)

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(*args, **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(*args, **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()
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.

Methods

__call__(self, data[, accession]) If accession is None, calls index() on data, otherwise calls query() with data and accession.
index(self, data) 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(self, data, accession) Search data for a key with the accession number accession.
__init__(self, /, *args, **kwargs)

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

index(self, 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(self, 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.

Attributes:
denominator

the denominator of a rational number in lowest terms

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

Methods

bit_length(self, /) Number of bits necessary to represent self in binary.
conjugate() Returns self, the complex conjugate of any int.
from_bytes(bytes, byteorder, \*[, signed]) Return the integer represented by the given array of bytes.
to_bytes(self, /, length, byteorder, \*[, …]) Return an array of bytes representing an integer.
__init__(self, /, *args, **kwargs)

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

bit_length(self, /)

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(bytes, byteorder, *, signed=False)

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(self, /, length, byteorder, *, signed=False)

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+”).

Methods

append(self, object, /) Append object to the end of the list.
clear(self, /) Remove all items from list.
copy(self, /) Return a shallow copy of the list.
count(self, value, /) Return number of occurrences of value.
extend(self, iterable, /) Extend list by appending elements from the iterable.
index(self, value[, start, stop]) Return first index of value.
insert(self, index, object, /) Insert object before index.
pop(self[, index]) Remove and return item at index (default last).
remove(self, value, /) Remove first occurrence of value.
reverse(self, /) Reverse IN PLACE.
sort(self, /, \*[, key, reverse]) Stable sort IN PLACE.
__init__(self, *args, **kwargs)[source]

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

append(self, object, /)

Append object to the end of the list.

clear(self, /)

Remove all items from list.

copy(self, /)

Return a shallow copy of the list.

count(self, value, /)

Return number of occurrences of value.

extend(self, iterable, /)

Extend list by appending elements from the iterable.

index(self, value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

insert(self, index, object, /)

Insert object before index.

pop(self, index=-1, /)

Remove and return item at index (default last).

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

remove(self, value, /)

Remove first occurrence of value.

Raises ValueError if the value is not present.

reverse(self, /)

Reverse IN PLACE.

sort(self, /, *, key=None, reverse=False)

Stable sort IN PLACE.

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

Bases: Exception

Exception raised for errors in Pyteomics library.

Attributes:
message : str

Error message.

__init__(self, 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

Attributes:
accession
unit_accession

Methods

capitalize(self, /) Return a capitalized version of the string.
casefold(self, /) Return a version of the string suitable for caseless comparisons.
center(self, width[, fillchar]) Return a centered string of length width.
count() Return the number of non-overlapping occurrences of substring sub in string S[start:end].
encode(self, /[, encoding, errors]) Encode the string using the codec registered for encoding.
endswith() Return True if S ends with the specified suffix, False otherwise.
expandtabs(self, /[, tabsize]) Return a copy where all tab characters are expanded using spaces.
find() Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
format() Return a formatted version of S, using substitutions from args and kwargs.
format_map() Return a formatted version of S, using substitutions from mapping.
index() Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
isalnum(self, /) Return True if the string is an alpha-numeric string, False otherwise.
isalpha(self, /) Return True if the string is an alphabetic string, False otherwise.
isascii(self, /) Return True if all characters in the string are ASCII, False otherwise.
isdecimal(self, /) Return True if the string is a decimal string, False otherwise.
isdigit(self, /) Return True if the string is a digit string, False otherwise.
isidentifier(self, /) Return True if the string is a valid Python identifier, False otherwise.
islower(self, /) Return True if the string is a lowercase string, False otherwise.
isnumeric(self, /) Return True if the string is a numeric string, False otherwise.
isprintable(self, /) Return True if the string is printable, False otherwise.
isspace(self, /) Return True if the string is a whitespace string, False otherwise.
istitle(self, /) Return True if the string is a title-cased string, False otherwise.
isupper(self, /) Return True if the string is an uppercase string, False otherwise.
join(self, iterable, /) Concatenate any number of strings.
ljust(self, width[, fillchar]) Return a left-justified string of length width.
lower(self, /) Return a copy of the string converted to lowercase.
lstrip(self[, chars]) Return a copy of the string with leading whitespace removed.
maketrans(x[, y, z]) Return a translation table usable for str.translate().
partition(self, sep, /) Partition the string into three parts using the given separator.
replace(self, old, new[, count]) Return a copy with all occurrences of substring old replaced by new.
rfind() Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
rindex() Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
rjust(self, width[, fillchar]) Return a right-justified string of length width.
rpartition(self, sep, /) Partition the string into three parts using the given separator.
rsplit(self, /[, sep, maxsplit]) Return a list of the words in the string, using sep as the delimiter string.
rstrip(self[, chars]) Return a copy of the string with trailing whitespace removed.
split(self, /[, sep, maxsplit]) Return a list of the words in the string, using sep as the delimiter string.
splitlines(self, /[, keepends]) Return a list of the lines in the string, breaking at line boundaries.
startswith() Return True if S starts with the specified prefix, False otherwise.
strip(self[, chars]) Return a copy of the string with leading and trailing whitespace remove.
swapcase(self, /) Convert uppercase characters to lowercase and lowercase characters to uppercase.
title(self, /) Return a version of the string where each word is titlecased.
translate(self, table, /) Replace each character in the string using the given translation table.
upper(self, /) Return a copy of the string converted to uppercase.
zfill(self, width, /) Pad a numeric string with zeros on the left, to fill a field of the given width.
__init__(self, /, *args, **kwargs)

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

capitalize(self, /)

Return a capitalized version of the string.

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

casefold(self, /)

Return a version of the string suitable for caseless comparisons.

center(self, width, fillchar=' ', /)

Return a centered string of length width.

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

count()

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(self, /, encoding='utf-8', errors='strict')

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

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(self, /, tabsize=8)

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

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

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

format_map()

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

index()

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, iterable, /)

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(self, width, fillchar=' ', /)

Return a left-justified string of length width.

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

lower(self, /)

Return a copy of the string converted to lowercase.

lstrip(self, chars=None, /)

Return a copy of the string with leading whitespace removed.

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

static maketrans(x, y=None, z=None, /)

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(self, sep, /)

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(self, old, new, count=-1, /)

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

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

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(self, width, fillchar=' ', /)

Return a right-justified string of length width.

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

rpartition(self, sep, /)

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(self, /, sep=None, maxsplit=-1)

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(self, chars=None, /)

Return a copy of the string with trailing whitespace removed.

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

split(self, /, sep=None, maxsplit=-1)

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(self, /, keepends=False)

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

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(self, chars=None, /)

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

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

swapcase(self, /)

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title(self, /)

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(self, table, /)

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(self, /)

Return a copy of the string converted to uppercase.

zfill(self, width, /)

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

Attributes:
imag

the imaginary part of a complex number

real

the real part of a complex number

unit_info

Methods

as_integer_ratio(self, /) Return integer ratio.
conjugate(self, /) Return self, the complex conjugate of any float.
fromhex(string, /) Create a floating-point number from a hexadecimal string.
hex(self, /) Return a hexadecimal representation of a floating-point number.
is_integer(self, /) Return True if the float is an integer.
__init__(self, /, *args, **kwargs)

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

as_integer_ratio(self, /)

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(self, /)

Return self, the complex conjugate of any float.

fromhex(string, /)

Create a floating-point number from a hexadecimal string.

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

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(self, /)

Return True if the float is an integer.

real

the real part of a complex number

class pyteomics.auxiliary.structures.unitint[source]

Bases: int

Attributes:
denominator

the denominator of a rational number in lowest terms

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

Methods

bit_length(self, /) Number of bits necessary to represent self in binary.
conjugate() Returns self, the complex conjugate of any int.
from_bytes(bytes, byteorder, \*[, signed]) Return the integer represented by the given array of bytes.
to_bytes(self, /, length, byteorder, \*[, …]) Return an array of bytes representing an integer.
__init__(self, /, *args, **kwargs)

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

bit_length(self, /)

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(bytes, byteorder, *, signed=False)

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(self, /, length, byteorder, *, signed=False)

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

Attributes:
unit_info

Methods

capitalize(self, /) Return a capitalized version of the string.
casefold(self, /) Return a version of the string suitable for caseless comparisons.
center(self, width[, fillchar]) Return a centered string of length width.
count() Return the number of non-overlapping occurrences of substring sub in string S[start:end].
encode(self, /[, encoding, errors]) Encode the string using the codec registered for encoding.
endswith() Return True if S ends with the specified suffix, False otherwise.
expandtabs(self, /[, tabsize]) Return a copy where all tab characters are expanded using spaces.
find() Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
format() Return a formatted version of S, using substitutions from args and kwargs.
format_map() Return a formatted version of S, using substitutions from mapping.
index() Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
isalnum(self, /) Return True if the string is an alpha-numeric string, False otherwise.
isalpha(self, /) Return True if the string is an alphabetic string, False otherwise.
isascii(self, /) Return True if all characters in the string are ASCII, False otherwise.
isdecimal(self, /) Return True if the string is a decimal string, False otherwise.
isdigit(self, /) Return True if the string is a digit string, False otherwise.
isidentifier(self, /) Return True if the string is a valid Python identifier, False otherwise.
islower(self, /) Return True if the string is a lowercase string, False otherwise.
isnumeric(self, /) Return True if the string is a numeric string, False otherwise.
isprintable(self, /) Return True if the string is printable, False otherwise.
isspace(self, /) Return True if the string is a whitespace string, False otherwise.
istitle(self, /) Return True if the string is a title-cased string, False otherwise.
isupper(self, /) Return True if the string is an uppercase string, False otherwise.
join(self, iterable, /) Concatenate any number of strings.
ljust(self, width[, fillchar]) Return a left-justified string of length width.
lower(self, /) Return a copy of the string converted to lowercase.
lstrip(self[, chars]) Return a copy of the string with leading whitespace removed.
maketrans(x[, y, z]) Return a translation table usable for str.translate().
partition(self, sep, /) Partition the string into three parts using the given separator.
replace(self, old, new[, count]) Return a copy with all occurrences of substring old replaced by new.
rfind() Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
rindex() Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
rjust(self, width[, fillchar]) Return a right-justified string of length width.
rpartition(self, sep, /) Partition the string into three parts using the given separator.
rsplit(self, /[, sep, maxsplit]) Return a list of the words in the string, using sep as the delimiter string.
rstrip(self[, chars]) Return a copy of the string with trailing whitespace removed.
split(self, /[, sep, maxsplit]) Return a list of the words in the string, using sep as the delimiter string.
splitlines(self, /[, keepends]) Return a list of the lines in the string, breaking at line boundaries.
startswith() Return True if S starts with the specified prefix, False otherwise.
strip(self[, chars]) Return a copy of the string with leading and trailing whitespace remove.
swapcase(self, /) Convert uppercase characters to lowercase and lowercase characters to uppercase.
title(self, /) Return a version of the string where each word is titlecased.
translate(self, table, /) Replace each character in the string using the given translation table.
upper(self, /) Return a copy of the string converted to uppercase.
zfill(self, width, /) Pad a numeric string with zeros on the left, to fill a field of the given width.
__init__(self, /, *args, **kwargs)

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

capitalize(self, /)

Return a capitalized version of the string.

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

casefold(self, /)

Return a version of the string suitable for caseless comparisons.

center(self, width, fillchar=' ', /)

Return a centered string of length width.

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

count()

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(self, /, encoding='utf-8', errors='strict')

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

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(self, /, tabsize=8)

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

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

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

format_map()

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

index()

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, /)

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(self, iterable, /)

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(self, width, fillchar=' ', /)

Return a left-justified string of length width.

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

lower(self, /)

Return a copy of the string converted to lowercase.

lstrip(self, chars=None, /)

Return a copy of the string with leading whitespace removed.

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

static maketrans(x, y=None, z=None, /)

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(self, sep, /)

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(self, old, new, count=-1, /)

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

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

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(self, width, fillchar=' ', /)

Return a right-justified string of length width.

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

rpartition(self, sep, /)

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(self, /, sep=None, maxsplit=-1)

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(self, chars=None, /)

Return a copy of the string with trailing whitespace removed.

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

split(self, /, sep=None, maxsplit=-1)

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(self, /, keepends=False)

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

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(self, chars=None, /)

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

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

swapcase(self, /)

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title(self, /)

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(self, table, /)

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(self, /)

Return a copy of the string converted to uppercase.

zfill(self, width, /)

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.

Attributes:
sources : Iterable

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

kwargs : Mapping

Additional arguments used to instantiate each sequence

Methods

map(self[, target, processes, …]) Execute the target function over entries of this object across up to processes processes.
from_iterable  
next  
sequence_maker  
__init__(self, *sources, **kwargs)[source]

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

map(self, 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.

Methods

reset(self) Resets the iterator to its initial state.
next  
__init__(self, source, **kwargs)[source]

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

reset(self)[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.

Attributes:
authkey
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

name
pid

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

sentinel

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

Methods

close(self) Close the Process object.
is_alive(self) Return whether process is alive
join(self[, timeout]) Wait until child process terminates
kill(self) Terminate process; sends SIGKILL signal or uses TerminateProcess()
run(self) Method to be run in sub-process; can be overridden in sub-class
start(self) Start child process
terminate(self) Terminate process; sends SIGTERM signal or uses TerminateProcess()
is_done  
__init__(self, reader_spec, target_spec, qin, qout, args_spec, kwargs_spec)[source]

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

close(self)

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

Return whether process is alive

join(self, timeout=None)

Wait until child process terminates

kill(self)

Terminate process; sends SIGKILL signal or uses TerminateProcess()

pid

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

run(self)[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(self)

Start child process

terminate(self)

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.

Methods

prebuild_byte_offset_file(path) Construct a new XML reader, build its byte offset index and write it to file
write_byte_offsets(self) Write the byte offsets in _offset_index to the file at _byte_offset_filename
__init__(self, *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(self)[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

Attributes:
default_index
delimiter
index
label

Methods

prebuild_byte_offset_file(path) Construct a new XML reader, build its byte offset index and write it to file
reset(self) Resets the iterator to its initial state.
write_byte_offsets(self) Write the byte offsets in _offset_index to the file at _byte_offset_filename
build_byte_index  
get_by_id  
get_by_ids  
get_by_index  
get_by_index_slice  
get_by_indexes  
get_by_key_slice  
next  
__init__(self, 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(self)

Resets the iterator to its initial state.

write_byte_offsets(self)

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.

Attributes:
default_index
index

Methods

get_by_id  
get_by_ids  
get_by_index  
get_by_index_slice  
get_by_indexes  
get_by_key_slice  
__init__(self, *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.

Attributes:
default_index
delimiter
index
label

Methods

reset(self) Resets the iterator to its initial state.
build_byte_index  
get_by_id  
get_by_ids  
get_by_index  
get_by_index_slice  
get_by_indexes  
get_by_key_slice  
next  
__init__(self, source, **kwargs)[source]

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

reset(self)

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

Attributes:
index_sequence

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

Methods

clear()
copy()
from_index(self, index[, include_value]) Get an entry by its integer index in the ordered sequence of this mapping.
from_slice(self, spec[, include_value]) Get a slice along index in the ordered sequence of this mapping.
fromkeys(iterable[, value]) Create a new ordered dictionary with keys from iterable and values set to value.
get(self, key[, default]) Return the value for key if key is in the dictionary, else default.
items()
keys()
move_to_end(self, /, key[, last]) Move an existing element to the end (or beginning if last is false).
pop(self, \*args, \*\*kwargs) value.
popitem(self, /[, last]) Remove and return a (key, value) pair from the dictionary.
setdefault(self, /, key[, default]) Insert key with a value of default if key is not in the dictionary.
update() 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()
between  
find  
load  
save  
sort  
__init__(self, *args, **kwargs)[source]

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

clear()
copy()
from_index(self, 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:
object:

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

from_slice(self, 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:
list:

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

fromkeys(iterable, value=None)

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

get(self, key, default=None, /)

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:
tuple
items()
keys()
move_to_end(self, /, key, last=True)

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

Raise KeyError if the element does not exist.

pop(self, *args, **kwargs)[source]

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

popitem(self, /, last=True)

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(self, /, key, default=None)

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

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()
class pyteomics.auxiliary.file_helpers.TableJoiner(*sources, **kwargs)[source]

Bases: pyteomics.auxiliary.file_helpers.ChainBase

Methods

map(self[, target, processes, …]) Execute the target function over entries of this object across up to processes processes.
concatenate  
from_iterable  
next  
sequence_maker  
__init__(self, *sources, **kwargs)

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

map(self, 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

Attributes:
default_index
index
time

Methods

get_by_id  
get_by_ids  
get_by_index  
get_by_index_slice  
get_by_indexes  
get_by_key_slice  
__init__(self, *args, **kwargs)[source]

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

Contents