API reference¶
Generated from the docstrings in the source, so it cannot fall out of step with the code.
pymzlib.pride¶
pride ¶
PRIDE Archive access, backed by mzLib's PrideArchiveClient.
The PRIDE Archive (https://www.ebi.ac.uk/pride/archive/) is EBI's public proteomics data repository. This module lets a Python user list what is in a project and pull files down, using the same paging, URL-resolution, and safe-download logic that mzLib uses in C#.
>>> import pymzlib
>>> files = pymzlib.pride.list_files("PXD000001")
>>> len(files)
8
>>> files[0].file_name
'PRIDE_Exp_Complete_Ac_22134.pride.mztab.gz'
>>> raw = [f for f in files if f.category == "RAW"]
>>> pymzlib.pride.download("PXD000001", "downloads", category="RAW")
ProjectNotFoundError ¶
Bases: PyMzLibError
No project with that accession exists, or it has no files.
PRIDE answers an unknown accession with an empty result rather than a 404, so earlier versions of pyMzLib returned an empty list. That was a mistake: an empty list is indistinguishable from "this project genuinely has nothing matching", so a typo'd accession produced a script that reported "0 files, done" and moved on. A wrong answer that looks like a right answer is worse than an error.
Source code in pkg/python/src/pymzlib/pride.py
PrideFile
dataclass
¶
One file belonging to a PRIDE Archive project.
Attributes:
| Name | Type | Description |
|---|---|---|
file_name |
str
|
The file's name, e.g. |
file_size_bytes |
int
|
Size in bytes as reported by PRIDE. |
checksum |
str
|
The repository's checksum, or |
category |
str
|
The file category, e.g. |
https_url |
str | None
|
A direct HTTPS download URL, or |
locations |
list[dict[str, str]]
|
Every published location as |
submission_date |
/ publication_date / updated_date
|
Repository timestamps. |
Source code in pkg/python/src/pymzlib/pride.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | |
size_mb
property
¶
The file size in megabytes, for the common case of eyeballing a manifest.
extension
property
¶
The file's lowercase extension including the dot, e.g. ".raw". Empty if none.
downloadable
property
¶
Whether this file can be fetched by :func:download (i.e. has an HTTPS location).
as_dict ¶
Return every attribute, including the computed ones, as a plain dict.
Use this rather than vars(f) when building a table. size_mb, extension and
downloadable are properties, so vars() and dataclasses.asdict() both skip
them — which silently produced a DataFrame missing the three attributes the
documentation pushes hardest, including the downloadable flag used to filter out
files that cannot be fetched.
Example
import pandas as pd # doctest: +SKIP df = pd.DataFrame([f.as_dict() for f in files]) # doctest: +SKIP
Source code in pkg/python/src/pymzlib/pride.py
list_files ¶
Return the file manifest of a PRIDE Archive project.
This is what PRIDE's REST API publishes, which is not always everything in the
project. For PXD000001 the API returns 8 files while the FTP tree holds 13, and
the five it omits include the two largest: ...60min_01-20141210.mzML (450 MB) and the
matching .mzXML (472 MB), exactly the modern open-format conversions most people want.
The omission is PRIDE's, not mzLib's. If completeness matters, cross-check the FTP
directory at https://ftp.pride.ebi.ac.uk/pride/data/archive/<year>/<month>/<accession>/.
Paging is handled for you: however many pages the project spans, you get one list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accession
|
str
|
The project accession, e.g. |
required |
page_size
|
int
|
How many files to request per underlying API call. Only affects how the manifest is fetched, never what you get back. |
100
|
timeout
|
float | None
|
Seconds to allow for the whole fetch. |
300
|
Returns:
| Type | Description |
|---|---|
list[PrideFile]
|
Every file in the project, in repository order. An unknown accession yields an empty |
list[PrideFile]
|
list rather than an error — that is PRIDE's own behavior, preserved here. |
Raises:
| Type | Description |
|---|---|
UsageError
|
the accession is blank or the page size is not positive. |
BridgeError
|
PRIDE returned an error status or was unreachable. |
Source code in pkg/python/src/pymzlib/pride.py
download ¶
download(accession: str, destination: str | Path, category: str | None = None, extensions: Sequence[str] | None = None, overwrite: bool = True, timeout: float | None = None) -> list[Path]
Download a project's files, optionally filtered, and return where they landed.
Files are streamed to a temporary name and moved into place only once complete, so an interrupted download never leaves a truncated file behind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accession
|
str
|
The project accession, e.g. |
required |
destination
|
str | Path
|
Directory to write into. Created if it does not exist. |
required |
category
|
str | None
|
Keep only files of this category, e.g. |
None
|
extensions
|
Sequence[str] | None
|
Keep only files with these extensions, e.g. |
None
|
overwrite
|
bool
|
When |
True
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Type | Description |
|---|---|
list[Path]
|
The paths written, in manifest order. |
Raises:
| Type | Description |
|---|---|
UsageError
|
the accession or destination is blank. |
BridgeError
|
a request failed, or a selected file has no HTTPS location. |
Source code in pkg/python/src/pymzlib/pride.py
download_files ¶
download_files(files: Iterable[PrideFile], destination: str | Path, overwrite: bool = True, timeout: float | None = None) -> list[Path]
Download exactly the files you selected, and nothing else.
This is the counterpart to :func:list_files, and usually the one you want. Filter the
manifest however you like — in Python, with the full expressiveness of Python — and hand the
result straight back:
>>> files = list_files("PXD000001") # doctest: +SKIP
>>> small = [f for f in files if f.size_mb < 5 and f.downloadable]
>>> download_files(small, "downloads") # doctest: +SKIP
:func:download's category and extensions filters can only express what they were
built to express; "under 5 MB", "the three newest", or "everything except the MGF" cannot be
said in that vocabulary at all. They can all be said in a list comprehension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
files
|
Iterable[PrideFile]
|
The :class: |
required |
destination
|
str | Path
|
Directory to write into. Created if it does not exist. |
required |
overwrite
|
bool
|
When |
True
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Type | Description |
|---|---|
list[Path]
|
The paths written, in the order the repository lists them. |
Raises:
| Type | Description |
|---|---|
UsageError
|
the selection is empty, spans several projects, or includes a file with no HTTPS location. |
Source code in pkg/python/src/pymzlib/pride.py
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 | |
total_size_bytes ¶
Sum the sizes of some files.
This is the size PRIDE reports, which is not the number of bytes you will transfer.
For compressed files PRIDE frequently reports the decompressed size: in PXD000001 the
reported size of PRIDE_Exp_Complete_Ac_22134.pride.mgf.gz is 16,448,103 bytes, exactly
what gzip -l gives as its uncompressed length, while the actual download is 5,984,662
bytes, 2.75x smaller.
It is also a sum over an incomplete manifest. For PXD000001 this returns 0.51 GB; the
project on disk is 1.44 GB, because PRIDE's API omits five files including the two largest
(see :func:list_files). The two errors run in opposite directions and do not cancel.
files = list_files("PXD000001") # doctest: +SKIP total_size_bytes(f for f in files if f.category == "RAW") / 1e9 # doctest: +SKIP 0.51
Source code in pkg/python/src/pymzlib/pride.py
pymzlib.peptidoform¶
peptidoform ¶
Peptidoform-level questions: digest an annotated protein and fragment its peptides.
The question this answers is the one a mass spectrometrist actually asks — what fragments would I see for this protein's peptides? — in one call:
>>> import pymzlib
>>> digest = pymzlib.peptidoform.fragments("P02768") # doctest: +SKIP
>>> len(digest.peptides) # doctest: +SKIP
303
The defaults are opinions, not placeholders. Tryptic with the proline rule, two missed cleavages, ETD, both termini, UniProt's annotated modifications applied. They are the choices this lab makes when it does not have a reason to choose otherwise, so the common question needs no parameters — and every one of them is reachable, because the point is to open the doors, not to hide them.
Fragment
dataclass
¶
One backbone fragment ion.
Attributes:
| Name | Type | Description |
|---|---|---|
product_type |
str
|
The ion series, e.g. |
fragment_number |
int
|
Position in the series — |
neutral_mass |
float
|
Monoisotopic neutral mass in daltons. Not an m/z: no proton has been added and no charge assumed. Fragments deliberately expose no |
neutral_loss |
float
|
Neutral loss in daltons, |
residue_position |
int
|
One-based residue position in the peptide. |
Source code in pkg/python/src/pymzlib/peptidoform.py
Peptide
dataclass
¶
One digested peptide, with its modifications and fragment ions.
Attributes:
| Name | Type | Description |
|---|---|---|
base_sequence |
str
|
The bare amino-acid sequence. |
full_sequence |
str
|
The sequence with modifications written inline, as mzLib renders them. |
monoisotopic_mass |
float
|
The neutral monoisotopic mass, modifications included. |
one_based_start |
/ one_based_end
|
Position within the parent protein. |
missed_cleavages |
int
|
How many cleavage sites the peptide spans. |
fixed_charges |
int
|
Charges the peptide carries before any protonation, from modifications
that leave a permanently charged residue. :meth: |
modifications |
list[dict[str, Any]]
|
Each applied modification. |
fragments |
list[Fragment]
|
The fragment ions for the requested dissociation type. |
Source code in pkg/python/src/pymzlib/peptidoform.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | |
mz ¶
Return the m/z of the intact peptide at a given total charge.
Two conventions are handled explicitly here, because getting either wrong is invisible in the answer.
The proton mass (1.007276), not the hydrogen atom (1.007825). The difference is 0.55 mDa — 1.1 ppm at m/z 500, which on an Orbitrap is a match versus a miss. Libraries differ on this and rarely say which they used.
Fixed charges are not double-counted. Some modifications leave the residue permanently
charged: trimethylation of a lysine ε-amine gives a quaternary ammonium, and UniProt
records the delta as 43.054227 — C₃H₇ minus an electron — rather than the neutral
43.054775. So :attr:monoisotopic_mass already carries that charge, and only
charge - fixed_charges protons are added. Adding a full complement would put a 2+
trimethylated peptide half a Thomson high, on the most important histone modification
there is.
A peptide with a fixed charge is therefore observable at that charge with no protonation
at all, which is why charge may not be below :attr:fixed_charges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
charge
|
int
|
The total charge state, at least :attr: |
required |
Source code in pkg/python/src/pymzlib/peptidoform.py
ModificationCensus
dataclass
¶
What UniProt annotates, and what could actually be used.
A modification is only usable for mass spectrometry if it has a defined target and a defined mass. A glycosylation site annotated as "N-linked (GlcNAc...) asparagine" has neither a fixed composition nor a fixed mass, so there is nothing to add to a peptide, and a peptide carrying an ambiguous-mass PTM is not identifiable by mass anyway. Such annotations are therefore excluded.
That exclusion is correct. What this class exists for is that you should not have to guess it happened: for serum albumin, 14 sites are applied out of 38 annotated, and without this the 14 arrives with no indication that a rule was ever applied.
Attributes:
| Name | Type | Description |
|---|---|---|
sites |
int
|
Distinct residue positions carrying at least one modification. A histone lists several alternatives at one residue — K9me1, K9me2, K9me3, K9ac are four modifications at one site — so this is always the smaller number and is not a modification count. |
applied |
int
|
Modifications actually placed on the protein. |
annotated |
int
|
Modification-like features UniProt lists. |
by_type |
list[dict[str, Any]]
|
One entry per feature type, with |
unresolved |
list[str]
|
Modification names UniProt annotated that could not be resolved to a mass — usually because the name is absent from UniProt's own ptmlist. These vanish silently otherwise: on histone H3.1, seven N6-lactoyllysine sites were dropped while the type summary still reported "modified residue … loaded". |
Source code in pkg/python/src/pymzlib/peptidoform.py
excluded
property
¶
Annotated features that could not be used because they have no defined mass.
explain ¶
A one-paragraph, human-readable account of what was used and what was not.
Source code in pkg/python/src/pymzlib/peptidoform.py
Digest
dataclass
¶
The result of digesting a protein and fragmenting its peptides.
Source code in pkg/python/src/pymzlib/peptidoform.py
truncated
property
¶
Whether any peptide hit the isoform cap, meaning the result is incomplete.
A short answer and a truncated answer look identical from the outside. Check this before treating a Peptidoform list as exhaustive.
modified_peptides
property
¶
Only the peptides carrying at least one modification.
fragments ¶
fragments(accession: str, protease: str = 'trypsin|P', dissociation: str = 'ETD', modifications: bool = True, missed_cleavages: int = 2, min_length: int = 7, max_length: int | None = None, max_modifications: int = 2, max_isoforms: int = 1024, terminus: str = 'Both', timeout: float | None = 300) -> Digest
Fetch a UniProt entry, digest it, and fragment every peptide.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accession
|
str
|
A UniProtKB accession, e.g. |
required |
protease
|
str
|
Read this if you are coming from MaxQuant or Mascot. mzLib's |
'trypsin|P'
|
dissociation
|
str
|
|
'ETD'
|
modifications
|
bool
|
Apply UniProt's annotated modifications.
Still true of the modifications themselves: pass |
True
|
missed_cleavages
|
int
|
Maximum missed cleavage sites per peptide. |
2
|
min_length
|
int
|
Shortest peptide to keep. The default of 7 silently discards shorter
peptides — roughly a third of a histone digest — so pass |
7
|
max_length
|
int | None
|
Longest peptide to keep. |
None
|
max_modifications
|
int
|
Maximum modifications considered per peptide. Modification isoforms are enumerated combinatorially: histone H3.1 yields 49 bare tryptic peptides, 2,563 at two modifications and 7,040 at three. |
2
|
max_isoforms
|
int
|
Maximum modification isoforms per peptide position. mzLib's default of 1024
truncates silently when it binds — on H3.1 at four modifications it discards
about 30% of the Peptidoforms (13,700 down to 9,536). :attr: |
1024
|
terminus
|
str
|
|
'Both'
|
timeout
|
float | None
|
Seconds to allow. Large proteins with many modification isoforms take longer. |
300
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
Digest
|
class: |
Digest
|
modification count — it reports what was annotated as well as what was applied. |
Raises:
| Type | Description |
|---|---|
UsageError
|
the accession, protease, dissociation type or terminus is not recognised. |
ServiceUnavailableError
|
UniProt was unreachable. |
Example
d = fragments("P02768") # doctest: +SKIP print(d.modification_census.explain()) # doctest: +SKIP 14 of 38 annotated modification sites were applied. Excluded: 24 × glycosylation site …
Source code in pkg/python/src/pymzlib/peptidoform.py
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | |
pymzlib.flashlfq¶
flashlfq ¶
Label-free quantification with FlashLFQ: quantify a search's peptides across mzML runs.
The question this answers is the one a quant workflow actually asks — given these identifications and these runs, how much of each peptide and protein is in each run? — in one call:
>>> import pymzlib
>>> result = pymzlib.flashlfq.quantify( # doctest: +SKIP
... psms="AllPSMs.psmtsv",
... spectra=["run_3.mzML", "run_4.mzML"],
... match_between_runs=True,
... )
>>> result.peptide_count, result.protein_count # doctest: +SKIP
(354, 943)
The whole pipeline is mzLib's: the result file is read by mzLib's Readers, turned into FlashLFQ
identifications by mzLib's own converter, and quantified by FlashLfqEngine. MetaMorpheus is not
involved — mzLib does it alone.
Names follow mzLib and FlashLFQ deliberately, so a value here means the same thing it does in the
FlashLFQ source, the MetaMorpheus output columns, and the FlashLFQ paper: match_between_runs,
ppm_tolerance, mbr_ppm_tolerance, sequence, base_sequence, protein_groups,
detection_types, ProteinGroup, FlashLfqResults.
.. warning::
Do not quantify an MSFragger psm.tsv with this. mzLib accepts one — it is one of only
three formats implementing the record view FlashLFQ consumes — but the numbers that come back
are wrong, and wrong silently.
MSFragger writes retention time in seconds; MetaMorpheus writes minutes. mzLib's
result-file readers pass the column through without converting it, and FlashLFQ then treats the
value as minutes and searches a ±2-minute window around it. A peptide truly eluting at 60
minutes is written as 3600 and then looked for at 3600 minutes - far past the end of any
real gradient - so it is simply not found: quantification collapses toward zero rather than
failing. This is an mzLib defect, not a pyMzLib one, and it affects any mzLib
caller — it is reported upstream. Until it is fixed, quantify MetaMorpheus output only.
pymzlib.readers.identify() will still report an MSFragger file as quantifiable: that
reports mzLib's interface, which the file genuinely implements. It is not an endorsement of the
numbers.
Three more limits worth knowing before you trust a number, in the "surface it, don't hide it" spirit of the rest of pyMzLib:
- mzML only, for now. Convert
.raw/.dto mzML first; a non-mzML path is rejected up front. - A protein intensity can be
None. FlashLFQ's median-polish protein quant marks a protein NaN when its peptide matrix is degenerate (too few peptides per run, or identical intensities across runs — a real artifact documented in mzLib's own tests). NaN is not valid JSON, so it arrives here asNone— "could not be quantified" — rather than a silently wrong number. A peptide intensity, by contrast, is0.0when missing, neverNone. - For match-between-runs, read the peaks, not the peptides. The peptide roll-up
(:attr:
FlashLfqResults.peptides, mirroringQuantifiedPeptides.tsv) reports far fewer MBR transfers than actually happened — a whole run's transfers can be absent. :attr:FlashLfqResults.peaks(and :meth:FlashLfqResults.mbr_peaks) is the complete surface; :attr:FlashLfqResults.mbr_peak_countis the number to trust.
SpectraFileInfo
dataclass
¶
One quantified run, mirroring mzLib's MassSpectrometry.SpectraFileInfo.
Attributes:
| Name | Type | Description |
|---|---|---|
file_name |
str
|
The run's base name (no directory, no extension) — the key used everywhere else here to look up this run's intensity. |
full_path |
str
|
The mzML path as provided. |
condition |
str
|
The sample-group label, or |
biological_replicate |
/ technical_replicate / fraction
|
The experimental-design coordinates. |
peak_count |
int
|
Chromatographic peaks quantified in this run. |
mbr_peak_count |
int
|
Of those, how many were transferred by match-between-runs — peaks quantified
in this run for a peptide that was never identified in it. Zero unless
|
Source code in pkg/python/src/pymzlib/flashlfq.py
Peptide
dataclass
¶
A quantified peptide, mirroring FlashLFQ's Peptide.
Attributes:
| Name | Type | Description |
|---|---|---|
sequence |
str
|
The full (modified) sequence, as FlashLFQ renders it — the identity FlashLFQ quantifies. Two different modification states of one base sequence are two peptides. |
base_sequence |
str
|
The bare amino-acid sequence. |
protein_groups |
str
|
The protein group(s) this peptide belongs to, |
intensities |
dict[str, Any]
|
Run base name → intensity in that run. Missing is |
detection_types |
dict[str, str]
|
Run base name → how it was quantified there. Values FlashLFQ emits:
|
Source code in pkg/python/src/pymzlib/flashlfq.py
intensity ¶
This peptide's intensity in the named run.
0.0 — not None — means "not quantified here." (Only protein intensities are
ever None.) Treat 0.0 as missing, not as a measured absence: log-transforming it
will mislead. And note a peptide that FlashLFQ transferred into this run by
match-between-runs may still read 0.0 here — see :attr:FlashLfqResults.peaks. Returns
0.0 for a run that was never provided.
Source code in pkg/python/src/pymzlib/flashlfq.py
detection_type ¶
How this peptide was quantified in the named run ("NotDetected" if it was not).
ProteinGroup
dataclass
¶
A quantified protein group, mirroring FlashLFQ's ProteinGroup.
Attributes:
| Name | Type | Description |
|---|---|---|
protein_group |
str
|
The protein group name (accession, or |
gene_name |
str
|
The gene name, when the result file carried one. |
organism |
str
|
The organism, when the result file carried one. |
intensities |
dict[str, Any]
|
Run base name → protein intensity in that run. May be |
Source code in pkg/python/src/pymzlib/flashlfq.py
intensity ¶
This protein's intensity in the named run.
None means FlashLFQ could not resolve a number (a degenerate peptide matrix); 0.0
means simply not measured in this run.
Source code in pkg/python/src/pymzlib/flashlfq.py
Peak
dataclass
¶
One quantified chromatographic peak, mirroring FlashLFQ's ChromatographicPeak.
This is the surface to use for match-between-runs. Unlike the peptide roll-up
(:attr:Peptide.intensities, which mirrors QuantifiedPeptides.tsv and drops most MBR
transfers), the peaks fully represent every quantified peak, transferred or not. To build an
MBR-inclusive peptide × run matrix, pivot these on (sequence, file_name).
Attributes:
| Name | Type | Description |
|---|---|---|
file_name |
str
|
The run this peak was measured in (base name). |
sequence |
str
|
The full (modified) sequence of the peptide the peak was assigned to. |
base_sequence |
str
|
The bare amino-acid sequence. |
intensity |
Any
|
The peak's intensity ( |
detection_type |
str
|
|
retention_time |
Any
|
Apex retention time in minutes, or |
num_identifications |
int
|
How many peptides could explain this peak. |
protein_groups |
str
|
The protein group(s) the assigned identification(s) belong to, |
Source code in pkg/python/src/pymzlib/flashlfq.py
FlashLfqResults
dataclass
¶
The result of a quantification run, mirroring mzLib's FlashLfqResults.
Attributes:
| Name | Type | Description |
|---|---|---|
psm_file |
str
|
The absolute path of the PSM result file that was quantified. |
identification_count |
int
|
How many identifications were read from it. |
parameters |
dict[str, Any]
|
The FlashLFQ parameters actually used, echoed back with their mzLib names. |
spectra_files |
list[SpectraFileInfo]
|
One :class: |
peptides |
list[Peptide]
|
One :class: |
proteins |
list[ProteinGroup]
|
One :class: |
peaks |
list[Peak]
|
Every quantified :class: |
output_directory |
Any
|
Where the FlashLFQ TSVs were written, or |
Source code in pkg/python/src/pymzlib/flashlfq.py
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | |
mbr_peak_count
property
¶
Total match-between-runs peaks (transfers) across every run.
This counts transferred peaks, not distinct peptides: one peptide rescued in two runs is
two peaks here. For "how many peptides did MBR rescue," use :attr:mbr_rescued_peptide_count.
Either way, do not count MBR from the peptide roll-up (:attr:Peptide.detection_types) — it
under-counts. Zero unless match_between_runs was on.
mbr_peaks
property
¶
Exactly the peaks transferred by match-between-runs (detection_type == "MBR").
mbr_rescued_peptide_count
property
¶
Distinct peptides quantified in at least one run only by match-between-runs.
Exactly: the number of distinct sequence values among peaks whose
detection_type is "MBR". Stated in code terms because the prose version,
"peptides quantified in at least one run only by match-between-runs", is subtly
different and on real data the two diverge: peptides having both an MBR peak and
a zero-intensity MSMS peak in the same run were identified there, so they are not
rescues under the strict reading. On the K562 pair this returns 140 where the strict
count is 135. Do not read mbr_rescued_peptide_count == mbr_peak_count as
reassurance that nothing was double-counted; on that data both are 140, and they
coincide only because every MBR peak happened to carry a distinct sequence.
Distinct modified sequences among
:attr:mbr_peaks. This equals :attr:mbr_peak_count only when no peptide was rescued in
more than one run.
quantify ¶
quantify(psms: str, spectra: Sequence[SpectraInput], *, normalize: bool = False, ppm_tolerance: float = 10.0, isotope_ppm_tolerance: float = 5.0, integrate: bool = False, match_between_runs: bool = False, mbr_ppm_tolerance: float = 10.0, mbr_q_value_threshold: float = 0.05, use_shared_peptides_for_protein_quant: bool = False, bayesian_protein_quant: bool = False, use_pep_q_value: bool = False, max_threads: int = -1, output_directory: str | None = None, timeout: float | None = None) -> FlashLfqResults
Quantify a search's peptides across mzML runs with FlashLFQ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psms
|
str
|
Path to a PSM result file. Use a MetaMorpheus |
required |
spectra
|
Sequence[SpectraInput]
|
The mzML runs. Each entry is either a path ( |
required |
normalize
|
bool
|
Normalize intensities across runs (FlashLFQ |
False
|
ppm_tolerance
|
float
|
Mass tolerance for peak-finding, in ppm ( |
10.0
|
isotope_ppm_tolerance
|
float
|
Mass tolerance for isotope-envelope matching, in ppm. |
5.0
|
integrate
|
bool
|
Integrate peak intensities rather than taking the apex. FlashLFQ recommends leaving this off. |
False
|
match_between_runs
|
bool
|
Quantify a peptide in a run where it was not identified, by transferring
the identification from a run where it was ( |
False
|
mbr_ppm_tolerance
|
float
|
Mass tolerance for MBR transfers, in ppm. |
10.0
|
mbr_q_value_threshold
|
float
|
The q-value cutoff below which an MBR transfer is accepted. |
0.05
|
use_shared_peptides_for_protein_quant
|
bool
|
Let peptides shared between protein groups contribute
to protein quant ( |
False
|
bayesian_protein_quant
|
bool
|
Run FlashLFQ's Bayesian protein-fold-change engine. |
False
|
use_pep_q_value
|
bool
|
Filter identifications on PEP q-value rather than q-value. |
False
|
max_threads
|
int
|
Worker threads; This is not only a performance knob - it changes results. With |
-1
|
output_directory
|
str | None
|
If given, FlashLFQ also writes |
None
|
timeout
|
float | None
|
Seconds to allow. Large experiments legitimately take a while; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
FlashLfqResults
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
an argument is malformed, a run is not mzML, an mzML is missing, or the PSM file names a run with no mzML provided. |
BridgeError
|
FlashLFQ itself failed. |
Source code in pkg/python/src/pymzlib/flashlfq.py
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 | |
pymzlib.readers¶
readers ¶
Read proteomics result files: what a file is, what you can do with it, and its records.
mzLib recognises 29 file types written by a dozen different search and deconvolution tools - MetaMorpheus, MSFragger, TopPIC, TopFD, MsPathFinderT, Crux, Casanovo, FlashDeconv, Dinosaur, FlashLFQ - and dispatches each to a parser it maintains. This module asks it what a path is::
>>> import pymzlib
>>> info = pymzlib.readers.identify("psm.tsv") # doctest: +SKIP
>>> info.file_type, info.views # doctest: +SKIP
('MsFraggerPsm', ['quantifiable'])
Read :attr:FileInfo.views before assuming anything. It is tempting to describe mzLib as
reading 29 formats into one uniform shape, and it does not. The formats fall into disjoint families
and several belong to no family at all:
"quantifiable"- a cross-format record view (sequence, retention time, charge, mass, protein groups), and the input :func:pymzlib.flashlfq.quantifyaccepts. Exactly three file types have it: MetaMorpheus.psmtsvand.osmtsv, and MSFraggerpsm.tsv. This view reports what mzLib's interface offers, not that the numbers are comparable - see the warning below, and do not quantify the MSFragger one."ms1_features"- deconvolved MS1 features (TopFD_ms1.feature, Dinosaur)."spectra"- the file is spectra, not results (.raw,.mzML,.mgf,.d, msalign)."spectral_match"- records are identifications but share no file-level interface (MsPathFinderT, Casanovo).[]- an empty list is a real and common answer. TopPIC, Crux, MSFragger's peptide/protein tables and the FlashDeconv formats each parse into their own record type with nothing in common. mzLib reads them; there is simply no uniform view to project them onto.
Call :func:formats for the whole table. It is enumerated from mzLib rather than transcribed, so it
cannot drift from what mzLib actually dispatches.
Three things this module deliberately does not tell you, in the "surface it, don't hide it" spirit of the rest of pyMzLib:
- Which tool wrote the file. mzLib has a
Softwareproperty that looks like the answer and is not: readers carry their software constant on a constructor that mzLib's own file factory does not use, so the value is unset for everything the factory returns - and it is not reliably set on the other constructor either. Rather than reconstruct a plausible answer, there is nosoftwarefield. :attr:FileInfo.file_typealready names the tool. -
Whether the numbers inside mean the same thing across formats. They do not, and this is the trap most likely to produce a wrong result. mzLib's result-file readers pass through whatever the tool wrote, with no unit conversion: MetaMorpheus retention times are in minutes, MSFragger's and TopPIC's are in seconds, and TopFD changed from seconds to minutes between v1.6.2 and v1.7.0 within the same file type. Likewise
is_decoyis hardcodedFalsefor MSFragger, which means "mzLib cannot tell" rather than "target" - MSFragger'spsm.tsvcarries no target/decoy column at all - sois_decoyarrives asNonefor that format rather than a fabricatedFalse.monoisotopic_massis the theoretical peptide mass in both formats, never the observed precursor mass. Identifying a file is safe; comparing raw fields across formats is not. -
Anything about confidence. There is no q-value, PEP or score in this view, because
IQuantifiableRecordcarries only what FlashLFQ needs. Nothing you get back is FDR-filtered, even though every one of these files records confidence somewhere. Filter before you report.
.. warning::
That units mismatch is not hypothetical. Passing an MSFragger psm.tsv to
:func:pymzlib.flashlfq.quantify returns near-zero intensities, because FlashLFQ reads the
seconds as minutes and searches for each peptide roughly sixty times too late in the gradient -
typically past the end of the run, so the peptide is never found.
identify() will still call the file quantifiable - that is mzLib's interface, honestly
reported - but quantify MetaMorpheus output only until the upstream fix lands.
Format
dataclass
¶
One file type mzLib can recognise.
Attributes:
| Name | Type | Description |
|---|---|---|
file_type |
str
|
mzLib's |
extension |
Any
|
The extension or filename suffix mzLib dispatches on, e.g. |
reader |
Any
|
The name of the mzLib class that parses it, for cross-referencing the mzLib source. |
views |
list[str]
|
The uniform views this format supports - see the module docstring. Often empty. |
Source code in pkg/python/src/pymzlib/readers.py
is_quantifiable
property
¶
Whether this format offers the cross-format record view (and so feeds FlashLFQ).
FileInfo
dataclass
¶
What a particular file is, and what can be done with it.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path that was identified. |
file_type |
str
|
mzLib's |
extension |
Any
|
The extension mzLib dispatched on. |
reader |
Any
|
The mzLib class that would parse it. |
views |
list[str]
|
The uniform views this file supports - see the module docstring. Often empty, which means mzLib can read the file but offers no cross-format projection of it. |
Source code in pkg/python/src/pymzlib/readers.py
is_quantifiable
property
¶
Whether this file offers the cross-format record view.
When True, the path can be passed straight to :func:pymzlib.flashlfq.quantify as
psms. When False, mzLib can still read the file - it simply has no uniform view,
so quantification would fail on it.
WrittenTable
dataclass
¶
Where :func:read_results wrote a table, when asked to write one instead of returning it.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path written. |
format |
str
|
Always |
row_count |
int
|
Rows written, excluding the header. |
Source code in pkg/python/src/pymzlib/readers.py
ResultRecords
dataclass
¶
The uniform record view of a result file.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path that was read. |
file_type |
str
|
mzLib's |
record_count |
int
|
Records in the whole file, regardless of |
returned_count |
int
|
Records actually carried back in :attr: |
offset |
int
|
The offset that was applied. |
truncated |
bool
|
Whether records were left behind, by either |
retention_time_unit |
str
|
The unit :attr: |
rows_not_read |
Any
|
Data rows in the file that did not become records - mzLib drops a malformed
row silently, so a non-zero value here means the file is partly unreadable and the
table is incomplete. |
caveats |
list[str]
|
What the uniform view cannot be trusted to mean for this format. Empty for some formats, not for others; each entry cites the mzLib source it came from. Worth printing before comparing anything across formats - this is where you learn that MSFragger retention times are seconds while MetaMorpheus's are minutes. |
column_names |
list[str]
|
The field names, in order. |
columns |
Any
|
Field name -> list of values, one entry per record - the shape |
output |
Any
|
Where the table was written, or |
Source code in pkg/python/src/pymzlib/readers.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
retention_time_in_minutes
property
¶
retention_time converted to minutes, whatever unit the format wrote.
The conversion you would otherwise write by hand, using
:attr:retention_time_unit. Raises if the unit is "unknown" rather than guessing -
a silently unconverted axis is the specific mistake this module exists to prevent.
records
property
¶
The same data row-wise: one dict per record.
A convenience for looping. If you are building a table, prefer :attr:columns - it is
already the shape a DataFrame wants, and this rebuilds it. Empty when out was given.
formats ¶
Every file type mzLib can recognise.
Enumerated from mzLib itself rather than from a list maintained here, so it reflects the installed version and cannot go stale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
One |
list[Format]
|
class: |
Example
quantifiable = [f.file_type for f in formats() if f.is_quantifiable] # doctest: +SKIP quantifiable # doctest: +SKIP ['psmtsv', 'osmtsv', 'MsFraggerPsm']
Source code in pkg/python/src/pymzlib/readers.py
identify ¶
Identify a result file without parsing its contents.
Cheap by design: mzLib resolves the type and stops, so identifying a million-row file costs no
more than identifying an empty one. It is not, however, pure - mzLib disambiguates a bare
.tsv by reading its first line, a .mztab by its first five, and a Bruker .d by which
analysis file the directory holds. An unreadable file will therefore raise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to a result or spectra file. A Bruker |
required |
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
FileInfo
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank, does not exist, or is not a file type mzLib recognises.
mzLib has no "unknown" result - a file is dispatchable or it is an error - so use
:func: |
Example
info = identify("AllPSMs.psmtsv") # doctest: +SKIP info.file_type, info.is_quantifiable # doctest: +SKIP ('psmtsv', True)
Source code in pkg/python/src/pymzlib/readers.py
read_results ¶
read_results(path: str, *, limit: int | None = None, offset: int = 0, out: str | None = None, timeout: float | None = None) -> ResultRecords
Read a result file into the uniform record view.
Only the three file types offering the "quantifiable" view can be read this way - check
:func:identify first, or catch the error. A file without the view is rejected with a message
naming the views it does have.
There is no default row limit. A result file can carry a million rows, and truncating by
default would mean the ordinary call returns a table that looks complete and is not. For a large
file use out rather than paging: see the note on offset below.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to a MetaMorpheus |
required |
limit
|
int | None
|
Maximum records to return. |
None
|
offset
|
int
|
Records to skip. This is a window, not a cursor. mzLib materializes the whole
file on every call - its readers look lazy and are not - so paging re-reads and
re-parses the file once per page. For a large file, one call with |
0
|
out
|
str | None
|
Write the records to this path as a tab-separated table and return only a summary, instead of carrying them back in the envelope. The intended path for large files, not an escape hatch. Tab-separated because these fields contain commas. |
None
|
timeout
|
float | None
|
Seconds to allow. A large file legitimately takes a while; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ResultRecords
|
class: |
ResultRecords
|
formats. |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank, missing, not a recognised format, or has no quantifiable view. |
Example
r = read_results("AllPSMs.psmtsv") # doctest: +SKIP r.record_count, r.truncated # doctest: +SKIP (8, False) import pandas as pd # doctest: +SKIP pd.DataFrame(r.columns) # doctest: +SKIP
Source code in pkg/python/src/pymzlib/readers.py
Errors and diagnostics¶
Everything pyMzLib raises inherits from PyMzLibError, so a single except catches all of it.
_bridge ¶
Locating and invoking the bundled mzLib bridge executable.
This module is the only place in pyMzLib that knows the bridge exists. Everything above it sees ordinary Python functions and objects. That boundary is deliberate: the transport (today, a self-contained .NET executable invoked per call) can be replaced by an in-process binding or a long-lived local server without any public API changing.
Nothing here imports a third-party package. pyMzLib declares no runtime dependencies, so it cannot participate in a dependency conflict inside anyone's environment.
PyMzLibError ¶
UsageError ¶
Bases: PyMzLibError, ValueError
A call was malformed — a missing or invalid argument. Raised before any work happens.
BridgeError ¶
Bases: PyMzLibError
mzLib reported a failure.
Attributes:
| Name | Type | Description |
|---|---|---|
error_type |
The .NET exception type name, e.g. |
Source code in pkg/python/src/pymzlib/_bridge.py
ServiceUnavailableError ¶
Bases: BridgeError
An external service is unavailable — down, rate-limited, timing out, or unreachable.
This is deliberately a distinct type, because the difference between "the repository is having a bad morning" and "something is broken" is the difference between retrying later and filing a bug. Catch it to back off and retry::
try:
files = pymzlib.pride.list_files("PXD000001")
except pymzlib.ServiceUnavailableError:
... # EBI's problem; try again later
except pymzlib.BridgeError:
... # ours
The classification happens in the bridge rather than here, so every consumer of the wire format gets it and not only Python. HTTP 408, 429, and 5xx count as unavailable; 404 and 400 do not, because a wrong URL or a malformed request is our problem and excusing it as an outage would hide a real bug.
Source code in pkg/python/src/pymzlib/_bridge.py
BridgeTimeoutError ¶
Bases: PyMzLibError
The bridge process did not finish within the timeout.
Deliberately not a :class:ServiceUnavailableError, and the distinction is the whole
point. A subprocess timeout has several possible causes and only one of them is a slow
service: the bridge may be wedged, the executable may be corrupt, antivirus may be holding
it, or the caller may simply have passed a timeout that was too short. Reporting all of that
as "the repository is down" is how a real bug gets skipped by every test suite and never
seen again.
If the caller wants a slow network to be treated as an outage, they can catch this explicitly — but the library will not guess on their behalf.
Source code in pkg/python/src/pymzlib/_bridge.py
BridgeNotFoundError ¶
Bases: PyMzLibError
The bridge executable could not be located.
In a released wheel this should be impossible: the executable ships inside the package.
It normally means pyMzLib is being run from a source checkout where the bridge has not
been built yet (see pkg/build/publish-bridge.ps1).
Source code in pkg/python/src/pymzlib/_bridge.py
bridge_path ¶
Return the path of the bridge executable that will be used.
Resolution order: the PYMZLIB_BRIDGE environment variable, then the copy staged
inside this package for the current platform.
Raises:
| Type | Description |
|---|---|
BridgeNotFoundError
|
if neither exists. |
Source code in pkg/python/src/pymzlib/_bridge.py
bridge_version ¶
Return the bridge's own version information, and check protocol compatibility.
Raises:
| Type | Description |
|---|---|
PyMzLibError
|
if the bridge speaks a different wire format than this package. |