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 forlinear_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.
TargetDecoy Approach¶
qvalues()
 estimate qvalues for a set of PSMs.
filter()
 filter PSMs to specified FDR level using TDA or given PEPs.
filter.chain()
 a chained version offilter()
.
fdr()
 estimate FDR in a set of PSMs using TDA or given PEPs.
Project infrastructure¶
PyteomicsError
 a pyteomicsspecific exception.
Helpers¶
Charge
 a subclass ofint
for charge states.
ChargeList
 a subclass oflist
for lists of charges.
print_tree()
 display the structure of a complex nesteddict
.
memoize()
 makes a memoization function decorator.
cvquery()
 traverse an arbitrarily nested dictionary looking for keys which arecvstr
instances, or objects with an attribute calledaccession
.

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,) – 1D arrays of floats. If y is omitted, x must be a 2D 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: 4tuple 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: 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: 4tuple 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:
The second formula is:
Note
This function is less versatile than
qvalues()
. To obtain FDR, you can callqvalues()
and take the last qvalue. This function can be used (with correction = 0 or 1) whennumpy
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 arraylike, 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 apandas.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 arraylike, 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 qvalues do not exceed the “real” qvalues 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:  psms (iterable, optional) – An iterable of PSMs, e.g. as returned by

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 / arraylike / 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 evalue 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 isFalse
.  is_decoy (callable / arraylike / 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 offdr()
for math; basically, if remove_decoy isTrue
, 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 (seefdr()
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 qvalues do not exceed the “real” qvalues with 95% probability.
See this paper for further explanation.
 pep (callable / arraylike / 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 arraylike, 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 qvalues. 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 isTrue
.Note
The name for the parameter comes from the fact that it is internally passed to
qvalues()
.  q_label (str, optional) – Field name for qvalue 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
orpandas.DataFrame

pyteomics.auxiliary.target_decoy.
qvalues
(*args, **kwargs)¶ Read args and return a NumPy array with scores and qvalues. qvalues are calculated either using TDA or based on provided values of PEP.
Requires
numpy
(and optionallypandas
).Parameters:  args (positional) – Iterables to read PSMs from. All positional arguments are chained. The rest of the arguments must be named.
 key (callable / arraylike / 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 arraylike, 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 isFalse
.  is_decoy (callable / arraylike / 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 arraylike, 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 / arraylike / 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 arraylike, 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 qvalues. 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 offdr()
for math; basically, if remove_decoy isTrue
, 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 (seefdr()
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 qvalues do not exceed the “real” qvalues with 95% probability.
See this paper for further explanation.
 q_label (str, optional) – Field name for qvalue 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 qvalues. Default isFalse
.  **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 isTrue
)
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.
BinaryArrayConversionMixin
(*args, **kwargs)[source]¶ Bases:
pyteomics.auxiliary.utils.ArrayConversionMixin
,pyteomics.auxiliary.utils.BinaryDataArrayTransformer

__init__
(*args, **kwargs)¶ Initialize self. See help(type(self)) for accurate signature.

class
binary_array_record
¶ 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

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'>)¶ Decode a base64encoded, compressed bytestring into a numerical array.
Parameters: Returns: Return type: np.ndarray


class
pyteomics.auxiliary.utils.
BinaryDataArrayTransformer
[source]¶ Bases:
object
A base class that provides methods for reading base64encoded binary arrays.

__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

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



pyteomics.auxiliary.utils.
add_metaclass
(metaclass)[source]¶ Class decorator for creating a class with a metaclass.

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.

clear
() → None. Remove all items from D.¶

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 setlike object providing a view on D's items¶

keys
() → a setlike 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¶ 2tuple; 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.
Charge
[source]¶ Bases:
int
A subclass of
int
. Can be constructed from strings in “N+” or “N” format, and the string representation of aCharge
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 builtin 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+”).

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.

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 nonoverlapping 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 alphanumeric string, False otherwise.
A string is alphanumeric if all characters in the string are alphanumeric 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+0000U+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 titlecased string, False otherwise.
In a titlecased string, upper and titlecase 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 leftjustified 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 3tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3tuple 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 rightjustified 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 3tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3tuple 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.

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


pyteomics.auxiliary.structures.
clear_unit_cv_table
()[source]¶ Clear the modulelevel unit name and controlled vocabulary accession table.

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 thesequence_maker()
function.
sources
¶ Sources for creating new sequences from, such as paths or filelike objects
Type: Iterable

kwargs
¶ Additional arguments used to instantiate each sequence
Type: Mapping

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 toprocesses
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 inargs
andkwargs
 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.
 target (


class
pyteomics.auxiliary.file_helpers.
FileReader
(source, **kwargs)[source]¶ Bases:
pyteomics.auxiliary.file_helpers.IteratorContextManager
Abstract class implementing context manager protocol for file readers.

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

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
andIndexSavingTextReader
.
__init__
(*args, **kwargs)¶ Initialize self. See help(type(self)) for accurate signature.


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
andIndexedXML
.
__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.

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

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: Returns: If
include_value
isTrue
, a tuple of (key, value) atindex
else just the key atindex
.Return type:

from_slice
(spec, include_value=False)[source]¶ Get a slice along index in the ordered sequence of this mapping.
Parameters: Returns: If
include_value
isTrue
, a tuple of (key, value) atindex
else just the key atindex
for eachindex
inspec
Return type:

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 atuple
to avoid repeatedly copying the sequence over many method calls.Returns: Return type: tuple

items
() → a setlike object providing a view on D's items¶

keys
() → a setlike 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 toprocesses
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 inargs
andkwargs
 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.
 target (
