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"]
>>> [f.file_name for f in raw]
['TMT_Erwinia_1uLSike_Top10HCD_isol2_45stepped_60min_01.raw']
>>> # Not run in CI: downloads 220 MB from EBI.
>>> pymzlib.pride.download("PXD000001", "downloads", category="RAW") # doctest: +SKIP
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 |
category_accession |
str
|
The category's PRIDE controlled-vocabulary accession, e.g.
|
locations |
list[dict[str, str]]
|
Every published location as |
submission_date |
datetime | None
|
When the project was submitted, as a timezone-aware timestamp. |
publication_date |
datetime | None
|
When the project was made public; as |
updated_date |
datetime | None
|
When the project record last changed; as |
project_accession |
str
|
The accession the file was listed under. |
Source code in pkg/python/src/pymzlib/pride.py
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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
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.
Examples:
>>> # Not run in CI: pandas is not a pyMzLib dependency.
>>> import pandas as pd
>>> df = pd.DataFrame([f.as_dict() for f in files])
Source code in pkg/python/src/pymzlib/pride.py
PrideFtpFile
dataclass
¶
One file found by walking a PRIDE project's FTP directory tree — the complete listing.
This is what :func:list_ftp_files returns, and the difference from :class:PrideFile is the
whole point: the FTP walk sees everything the project holds, including the files PRIDE's REST
manifest omits and files nested in subdirectories. The trade-off is the size: PRIDE's directory
index rounds it to about three significant figures, so it is approximate_size_bytes — a good
project-size estimate, not the exact number of bytes you will transfer.
Attributes:
| Name | Type | Description |
|---|---|---|
relative_path |
str
|
Path relative to the project's FTP root, e.g. |
file_name |
str
|
The bare file name — the last segment of |
url |
str
|
The HTTPS URL the file can be downloaded from. |
approximate_size_bytes |
int
|
PRIDE's rounded index size in bytes. For the exact transfer size of
one file, issue an HTTP HEAD against |
project_accession |
str
|
The accession this file was listed under. |
Source code in pkg/python/src/pymzlib/pride.py
approximate_size_mb
property
¶
The approximate size in megabytes, for eyeballing a project's footprint.
extension
property
¶
The file's lowercase extension including the dot, e.g. ".raw". Empty if none.
as_dict ¶
Return every attribute, including the computed ones, as a plain dict for a DataFrame.
Source code in pkg/python/src/pymzlib/pride.py
PrideProjectSearchResult
dataclass
¶
One hit from :func:search.
This is not a project's full metadata, and the two are not interchangeable. PRIDE serves
search from a separate Elasticsearch projection in which every controlled-vocabulary field has
been flattened to a display string: the same project reports its instruments as
["Q Exactive"] here and as structured terms with accessions from the metadata endpoint,
contacts collapse from ten-field objects to a display name, and publications to a single
pre-formatted citation string. That is a property of PRIDE's wire, not a simplification chosen
here — the accessions are simply not sent. Follow :attr:accession when you need the
vocabulary.
A zero or an empty list means "not reported", never a measured zero. PRIDE omits nothing as
null, so absence arrives as 0, "" or [], and several fields are genuinely sparse —
sampled across 1,600 hits, :attr:project_tags was populated on 2.6%, :attr:sdrf on 2.4%,
:attr:other_omics_links on 18%, and the bot/hub/organic trio on under half. Do not read a
download_count of 0 as "nobody downloaded it".
Attributes:
| Name | Type | Description |
|---|---|---|
accession |
str
|
The project accession — the key to everything else in this module. Usually a
|
title |
str
|
The project title. |
project_description |
str
|
The submitter's free-text description. |
sample_processing_protocol |
str
|
How the sample was prepared, as free text. |
data_processing_protocol |
str
|
How the data were searched and processed, as free text. |
doi |
str
|
The dataset DOI, or |
submission_type |
str
|
|
sdrf |
str
|
The project's SDRF metadata as a single space-joined bag of term values, flattened
by the search index. Not a file, filename or URL — nothing can be fetched with it
and the row/column structure is gone. For a real SDRF see :mod: |
submission_date |
date | None
|
A calendar :class: |
publication_date |
date | None
|
As |
updated_date |
date | None
|
As |
project_tags |
list[str]
|
PRIDE's coarse classification tags. |
keywords |
list[str]
|
The submitter's free-text keywords. May contain empty and whitespace-only strings — PRIDE ships them on roughly 9% of hits. They are passed through rather than filtered, because dropping them here would make this module disagree with mzLib and with the Rust and R bindings about what a project's keywords are. Filter before joining. |
submitters |
list[str]
|
Display names, flattened from the structured contact objects the metadata endpoint returns. |
lab_pis |
list[str]
|
Display names of the lab heads, flattened the same way. |
affiliations |
list[str]
|
Display strings. |
instruments |
list[str]
|
Display names only; the controlled-vocabulary accessions are not sent. |
softwares |
list[str]
|
Display names. |
quantification_methods |
list[str]
|
Display names, e.g. |
sample_attributes |
list[str]
|
Sample characteristics by display value (e.g. |
organisms |
list[str]
|
Display names, e.g. |
organism_parts |
list[str]
|
Display names. |
diseases |
list[str]
|
Display names. |
references |
list[str]
|
Publications, each a single pre-formatted citation string. A PubMed ID or DOI cannot be read out of one without parsing the string PRIDE assembled. |
experiment_types |
list[str]
|
e.g. |
project_file_names |
list[str]
|
File names only — a search convenience, not the manifest. It
carries no sizes, categories or download locations. Use :func: |
other_omics_links |
list[str]
|
Links to related datasets in other omics repositories. |
highlights |
dict[str, list[str]]
|
Why this project matched, keyed by the field each match was found in, with the
matched terms wrapped in |
yearly_downloads |
list[dict[str, Any]]
|
|
download_count |
int
|
Total downloads. |
avg_downloads_per_file |
float
|
Mean downloads per file. |
percentile |
int
|
Download-popularity percentile within PRIDE. |
bot_count |
int
|
Downloads attributed to crawlers. |
hub_count |
int
|
Downloads attributed to institutional or aggregating hubs. |
organic_count |
int
|
Downloads attributed to ordinary human traffic. |
Source code in pkg/python/src/pymzlib/pride.py
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 | |
matched_fields
property
¶
Which PRIDE fields the query hit, from :attr:highlights. Empty if PRIDE reported none.
as_dict ¶
Every attribute, including the computed ones, as a plain dict.
Use this rather than vars() when building a table: matched_fields is a property, so
dataclasses.asdict() silently omits it. Same reasoning as :meth:PrideFile.as_dict.
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, use :func:list_ftp_files,
which walks the project's FTP directory and returns everything it actually holds.
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
list_ftp_files ¶
Return the complete file list of a PRIDE project, read from its FTP directory tree.
This is the authoritative counterpart to :func:list_files. Where list_files returns
PRIDE's REST manifest — which is knowingly incomplete, omitting for PXD000001 five of the
project's 13 files, including the two largest — this walks the FTP directory (subdirectories
included) and returns everything the project actually holds. Reach for it whenever completeness
or a true project size matters; use :func:list_files when you want the rich metadata (category,
checksum, controlled-vocabulary locations) that the REST manifest carries and the directory
index does not.
This is a listing surface only. :func:download and :func:download_files operate on the
REST manifest, so a file that appears only here — the whole point of this function — is not
accepted by them; fetch it directly from its :attr:PrideFtpFile.url with an ordinary HTTPS
client (e.g. urllib.request.urlretrieve(f.url, f.file_name)).
The sizes are approximate: PRIDE's directory index rounds them (see
:attr:PrideFtpFile.approximate_size_bytes), so :func:approximate_total_size_bytes is an
estimate — but an estimate over the whole project, unlike :func:total_size_bytes.
>>> # Not run in CI: no "pride ftp-files" recording to replay yet.
>>> ftp = pymzlib.pride.list_ftp_files("PXD000001") # doctest: +SKIP
>>> len(ftp) # doctest: +SKIP
13
>>> nested = [f.relative_path for f in ftp if "/" in f.relative_path] # doctest: +SKIP
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accession
|
str
|
The project accession, e.g. |
required |
timeout
|
float | None
|
Seconds to allow for the whole walk, which spans one request per directory. |
300
|
Returns:
| Type | Description |
|---|---|
list[PrideFtpFile]
|
Every file under the project's FTP root, subdirectories included, in the order the walk |
list[PrideFtpFile]
|
encounters them. Never empty — an empty result is raised as an error (see below). |
Raises:
| Type | Description |
|---|---|
UsageError
|
the accession is blank or malformed. |
ProjectNotFoundError
|
no project has that accession (or it lacks the publication date that
locates its FTP directory), or the directory listed no files. Same "no such project"
signal :func: |
ServiceUnavailableError / BridgeError
|
PRIDE was unreachable, or a directory fetch failed. |
Source code in pkg/python/src/pymzlib/pride.py
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 | |
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")
>>> small = [f for f in files if f.size_mb < 5 and f.downloadable]
>>> len(small)
3
>>> # Not run in CI: downloads from EBI.
>>> 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
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 | |
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. For
a size that covers the whole project, use :func:approximate_total_size_bytes over
:func:list_ftp_files.
files = list_files("PXD000001") round(total_size_bytes(files) / 1e9, 2) 0.51
Source code in pkg/python/src/pymzlib/pride.py
approximate_total_size_bytes ¶
Sum the approximate sizes of some FTP files.
This is the honest project-size number, and the counterpart to :func:total_size_bytes with the
trade-offs reversed. It sums over the complete FTP listing (:func:list_ftp_files), so no
files are missing — but each size is PRIDE's directory-index value, rounded to about three
significant figures, so the total is an estimate, not an exact byte count. For PXD000001 it
lands near the true 1.44 GB, where :func:total_size_bytes reports 0.51 GB over the incomplete
REST manifest. When you need the exact bytes for one file, HTTP HEAD its
:attr:PrideFtpFile.url and read Content-Length.
Not run in CI: no "pride ftp-files" recording to replay yet.¶
ftp = list_ftp_files("PXD000001") # doctest: +SKIP approximate_total_size_bytes(ftp) / 1e9 # doctest: +SKIP 1.44
Source code in pkg/python/src/pymzlib/pride.py
search ¶
search(keyword: str, page_size: int = 100, timeout: float | None = 300) -> list[PrideProjectSearchResult]
Find PRIDE projects by keyword.
The discovery entry point. Every other function here takes an accession you already have; this is the one that produces them, so you can go from a subject to a dataset without leaving Python.
Paging is handled for you: however many pages the result set spans, you get one list, with no accession repeated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keyword
|
str
|
What to search for, e.g. |
required |
page_size
|
int
|
How many projects to request per underlying API call. Only affects how the result set is fetched, never what you get back. |
100
|
timeout
|
float | None
|
Seconds to allow for the whole fetch. |
300
|
Returns:
| Type | Description |
|---|---|
list[PrideProjectSearchResult]
|
Every matching project. An empty list is a real answer — PRIDE reports no hits as an |
list[PrideProjectSearchResult]
|
empty result rather than an error, so unlike :func: |
list[PrideProjectSearchResult]
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the keyword is blank, over |
BridgeError
|
PRIDE returned an error status or was unreachable. |
Note
PRIDE pages a live index with no stable cursor, so a result set that changes during a multi-page fetch shifts its own paging. A project published mid-fetch is served on two pages and deduplicated, so it comes back once; a project removed mid-fetch can fall between two pages and be missed. A search whose hits fit on one page cannot be affected.
Examples:
>>> hits = search("plasmodium falciparum schizont")
>>> hits[0].accession, hits[0].organisms
('PXD070842', ['Homo sapiens (human)', 'Plasmodium falciparum (isolate 3d7)'])
>>> hits[0].matched_fields
['references', 'title']
>>> # Not run in CI: no recording of this project's file list to replay.
>>> files = list_files(hits[0].accession)
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")
>>> digest.accession, digest.sequence_length
('P02768', 609)
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.
:func:convert rewrites full sequences from one notation to another with mzLib's
SequenceConversionService: a MetaMorpheus full sequence [UniProt:N-acetylserine on S]SEQK
becomes [UNIMOD:1]SEQK in Unimod notation.
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
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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | |
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.
mzLib loads only modified residue and lipid moiety-binding region annotations; every
other feature type is dropped on feature type alone, before any mass lookup. So the census
sees the world at feature-type granularity — one entry per type in :attr:by_type, never per
modification name. On serum albumin the 24 excluded features all sit under the single type
glycosylation site; at UniProt's finer name level 22 of those 24 are specifically
N-linked (Glc) (glycation) lysine, which does have a defined mass — but the census never
surfaces that name, so "22" is a fact you confirm by reading the UniProt entry, not a number
this class reports. Read the exclusion as "wrong feature type", not "no defined mass".
The exclusion is still correct: glycation and glycosylation are labile, heterogeneous adducts, so assigning one an exact mass and a clean fragment ladder would describe a species you cannot observe. 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. See smith-chem-wisc/mzLib#1112.
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
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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | |
excluded
property
¶
Annotated features mzLib did not apply, dropped on feature type (not for want of mass).
explain ¶
A one-paragraph, human-readable account of what was used and what was not.
It names the excluded feature types and their counts — the only granularity the census
has. It never reports a modification-name-level breakdown (e.g. "22 of 24 are glycation"),
because :attr:by_type does not carry names; such a figure comes from reading the UniProt
entry, not from this census.
Source code in pkg/python/src/pymzlib/peptidoform.py
Digest
dataclass
¶
The result of digesting a protein and fragmenting its peptides.
Attributes:
| Name | Type | Description |
|---|---|---|
accession |
str
|
The accession UniProt returned. |
name |
str
|
UniProt entry name, e.g. |
full_name |
str
|
Recommended protein name, e.g. |
organism |
str
|
Scientific name of the source organism. |
sequence_length |
int
|
Length of the full precursor sequence, in residues. |
protease |
str
|
The protease used, as mzLib names it. |
dissociation |
str
|
The dissociation type used, which decides the fragment series. |
terminus |
str
|
Which fragment termini were generated: |
modifications_applied |
bool
|
|
max_modifications |
int
|
The |
max_isoforms |
int
|
The |
peptides_at_cap |
int
|
Peptide positions whose peptidoforms reached |
modification_census |
ModificationCensus
|
What UniProt annotates against what mzLib applied: distinct residue
positions carrying a modification ( |
peptides |
list[Peptide]
|
One :class: |
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.
ConvertedSequence
dataclass
¶
One input sequence and what mzLib made of it.
Attributes:
| Name | Type | Description |
|---|---|---|
input |
str
|
The sequence exactly as given. |
output |
str | None
|
The sequence in the target notation, or |
status |
str
|
mzLib's verdict. |
failure_reason |
str | None
|
mzLib's |
incompatible_items |
list[str]
|
The modifications (or other elements) mzLib could not write in the
target, as mzLib describes them ( |
warnings |
list[str]
|
mzLib's non-fatal messages for this input. |
errors |
list[str]
|
mzLib's error messages for this input. |
Source code in pkg/python/src/pymzlib/peptidoform.py
ok
property
¶
Whether mzLib converted it with nothing recorded against it (status == "converted").
SequenceConversions
dataclass
¶
Bases: _Table
What :func:convert returned: one row per input sequence, in input order.
columns maps input, output, status, failure_reason, incompatible_items,
warnings and errors to one value per input, ready for
pandas.DataFrame(result.columns). :attr:sequences is the same rows as
:class:ConvertedSequence objects.
Attributes:
| Name | Type | Description |
|---|---|---|
source_format |
str
|
The source notation, spelled as mzLib registered it ( |
target_format |
str
|
The target notation, spelled as mzLib registered it ( |
mode |
str
|
The |
source_formats |
list[str]
|
Every source notation mzLib has registered, sorted. |
target_formats |
list[str]
|
Every target notation mzLib has registered, sorted. |
record_count |
int
|
Rows, one per input sequence, duplicates included. |
converted_count |
int
|
Sequences with status |
warned_count |
int
|
Sequences with status |
failed_count |
int
|
Sequences with status |
column_names |
list[str]
|
The table's columns, in order. |
columns |
dict[str, list[Any]]
|
Column name to one value per input. |
caveats |
list[str]
|
What a status does and does not promise, per target. Read these once. |
Source code in pkg/python/src/pymzlib/peptidoform.py
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | |
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. Pass This once carried a caveat saying |
True
|
missed_cleavages
|
int
|
Maximum missed cleavage sites per peptide. |
2
|
min_length
|
int
|
Shortest peptide to keep, in residues. 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, in residues. |
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. |
Examples:
>>> d = fragments("P02768")
>>> print(d.modification_census.explain())
14 of 38 annotated modifications were applied, across 14 residue positions. Excluded ...
Source code in pkg/python/src/pymzlib/peptidoform.py
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 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 456 | |
convert ¶
convert(sequences: Iterable[str], *, source: str = 'mzLib', target: str = 'Unimod', mode: str = 'ReturnNull', threads: int = 1, timeout: float | None = 120) -> SequenceConversions
Convert full sequences from one notation to another with mzLib, one result per input.
Wraps mzLib's SequenceConversionService.Default (with ProForma registered). The main use is
MetaMorpheus or mzLib full sequences to Unimod accessions: [UniProt:N-acetylserine on S]SEQK
becomes [UNIMOD:1]SEQK. Nothing is converted in Python or in the bridge; every output and
every status is mzLib's.
Choose Unimod, not ProForma, for UniProt-sourced modifications. mzLib's ProForma target
does not resolve them and writes them back under their mzLib name, status "converted". See
the caveats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sequences
|
Iterable[str]
|
Full sequences, one result row each, in order, duplicates included. Sent to
mzLib exactly as given. A blank entry or one with a line break is refused, because it
would shift every later row. Split an ambiguous MetaMorpheus full sequence
( |
required |
source
|
str
|
The notation the sequences are in. One of mzLib's registered source formats
(:attr: |
'mzLib'
|
target
|
str
|
The notation to write. One of mzLib's registered target formats
(:attr: |
'Unimod'
|
mode
|
str
|
mzLib's |
'ReturnNull'
|
threads
|
int
|
Sequences converted at once. Default 1; |
1
|
timeout
|
float | None
|
Seconds to allow. |
120
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
SequenceConversions
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
no sequences; a blank one; |
Examples:
UniProt and MetaMorpheus modifications to Unimod accessions, and one mzLib cannot map:
>>> result = convert([
... "[UniProt:N-acetylserine on S]SEQK",
... "PEPK[UniProt:N6,N6-dimethyllysine on K]R",
... "PEPM[Common Variable:Oxidation on M]K",
... "PEPK[Made Up:Not a modification on K]R",
... ])
>>> result.outputs
['[UNIMOD:1]SEQK', 'PEPK[UNIMOD:36]R', 'PEPM[UNIMOD:35]K', None]
>>> failed = result.not_converted[0]
>>> failed.status, failed.incompatible_items
('failed', ['Made Up:Not a modification on K @3(K)'])
Source code in pkg/python/src/pymzlib/peptidoform.py
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 | |
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(
... psms="AllPSMs.psmtsv",
... spectra=["run_3.mzML", "run_4.mzML"],
... match_between_runs=True,
... )
>>> result.peptide_count, result.protein_count
(2, 2)
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.
.. note::
An MSFragger psm.tsv can now be quantified here. mzLib PR #1116 converts MSFragger's
retention time to minutes at the reader, so the value FlashLFQ consumes is in the unit it
expects; the former "MSFragger writes seconds, do not quantify it" warning no longer applies.
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 |
peptide_count |
int
|
Distinct modified sequences quantified: the number of peptides in
:attr: |
protein_count |
int
|
Protein groups quantified: the number of protein groups in :attr: |
Source code in pkg/python/src/pymzlib/flashlfq.py
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 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 | |
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 | PathLike[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 | PathLike[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 | PathLike[str]
|
Path to a PSM result file — 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
|
Also run FlashLFQ's Bayesian protein-fold-change engine. Its
results are written to |
False
|
use_pep_q_value
|
bool
|
Store each identification's PEP q-value as its q-value, instead of its q-value. It filters nothing here: FlashLFQ is given every identification either way. It changes the q-value FlashLFQ carries, which match-between-runs reads. |
False
|
max_threads
|
int
|
Worker threads; Before mzLib 1.0.592 this changed results, not only speed: with match-between-runs
on and more than one thread, the peptide roll-up dropped some MBR intensities
nondeterministically, so identical inputs gave different peptide and protein
numbers (smith-chem-wisc/mzLib#1111). mzLib#1155 fixed the cause, the PEP
training rows being assembled in thread-completion order, and this build includes
it. pyMzLib has not re-measured its own K562 reproduction on this build, so
|
-1
|
output_directory
|
str | PathLike[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
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 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 | |
median_polish ¶
median_polish(peptides: str | PathLike[str], *, design: Sequence[DesignInput] | None = None, use_shared_peptides: bool = False, output_directory: str | PathLike[str] | None = None, timeout: float | None = None) -> list[ProteinGroup]
Roll a QuantifiedPeptides.tsv up to protein intensities with FlashLFQ's median polish.
This is the second half of :func:quantify on its own: given a peptide table FlashLFQ already
wrote — its Intensity_<run> and Detection Type_<run> columns — it rebuilds the FlashLFQ
peptide/protein object graph and runs the exact same median-polish protein quant
(CalculateProteinResultsMedianPolish), without re-reading any mzML. Reach for it to
re-quantify proteins under a different experimental design, or with shared peptides toggled,
without paying for peak-finding again::
>>> import pymzlib
>>> proteins = pymzlib.flashlfq.median_polish(
... "QuantifiedPeptides.tsv",
... design=[
... {"file_name": "run_3", "condition": "control", "biological_replicate": 0},
... {"file_name": "run_4", "condition": "treated", "biological_replicate": 0},
... ],
... )
>>> proteins[0].intensity("control_1")
3005.6
The returned objects are ordinary :class:ProteinGroup\ s, so their intensity semantics are the
ones documented there and on :func:quantify: an intensity is None where median polish could
not resolve a number (a degenerate peptide matrix), 0.0 where the protein was simply not
measured in that sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
peptides
|
str | PathLike[str]
|
Path to a FlashLFQ |
required |
design
|
Sequence[DesignInput] | None
|
The experimental design, one mapping per run. Each needs a |
None
|
use_shared_peptides
|
bool
|
Let peptides shared between protein groups contribute to protein quant
(FlashLFQ's |
False
|
output_directory
|
str | PathLike[str] | None
|
If given, also write a FlashLFQ |
None
|
timeout
|
float | None
|
Seconds to allow; |
None
|
Returns:
| Type | Description |
|---|---|
list[ProteinGroup]
|
A list of :class: |
list[ProteinGroup]
|
attr: |
list[ProteinGroup]
|
is given, |
Raises:
| Type | Description |
|---|---|
UsageError
|
|
BridgeError
|
the reconstruction or quantification itself failed. |
Source code in pkg/python/src/pymzlib/flashlfq.py
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 | |
pymzlib.readers¶
readers ¶
Read mass-spectrometry data files and proteomics search results: what a file is, what you can do with it, and its records.
Spectra files are read here too, not just search output. :func:read_spectra reads
mzML, Thermo .raw, Bruker .d, timsTOF .d, MGF and msalign - scan headers always,
peaks on request::
>>> import pymzlib
>>> scans = pymzlib.readers.read_spectra("sliced_ethcd.mzML", limit=3)
>>> scans.scan_count, scans.columns["retention_time"][:2]
(6, [38.92571663975, 38.92606115255])
mzLib recognises 38 file types in all - the instrument and deconvolution formats above, plus the output of a dozen search tools: MetaMorpheus, MSFragger, TopPIC, TopFD, MsPathFinderT, Crux, Casanovo, FlashDeconv, Dinosaur, DIA-NN, FlashLFQ, Pytheas, and any mzIdentML writer - and dispatches each to a parser it maintains. This module asks it what a path is::
>>> # Not run in CI: no "readers identify" recording to replay yet.
>>> info = pymzlib.readers.identify("psm.tsv") # doctest: +SKIP
>>> info.file_type, info.views # doctest: +SKIP
('MsFraggerPsm', ['quantifiable'])
...and reads it, whatever it turns out to be::
>>> table = pymzlib.readers.read_records("ToppicPrsm_TopPICv1.6.2_prsm.tsv")
>>> table.record_type, len(table.column_names)
('ToppicPrsm', 36)
Every one of the 38 formats is readable - :func:read_records reads any of them. What differs
between formats is not whether you can read them but what the columns mean, and that is what
:attr:FileInfo.views tells you. It is tempting to describe mzLib as reading 38 formats into one
uniform shape; it does not. They fall into disjoint families, and several belong to no family at
all:
+---------------------+-------+------------------------+---------------------------------------+
| view | types | function | columns |
+=====================+=======+========================+=======================================+
| "quantifiable" | 4 | :func:read_results | uniform: sequence, RT, charge, mass, |
| | | | protein groups. What |
| | | | :func:pymzlib.flashlfq.quantify |
| | | | consumes. |
+---------------------+-------+------------------------+---------------------------------------+
| "ms1_features" | 2 | :func:read_features | uniform: m/z, charge, RT range, |
| | | | intensity, isotope count. |
+---------------------+-------+------------------------+---------------------------------------+
| "spectral_match"| 6 | :func:read_matches | uniform: scan, sequences, accession, |
| | | | decoy flag, modifications. |
+---------------------+-------+------------------------+---------------------------------------+
| "spectra" | 7 | :func:read_spectra | uniform: scan headers, and peaks on |
| | | | request. |
+---------------------+-------+------------------------+---------------------------------------+
| (any) | 38 | :func:read_records | this format's own fields, under |
| | | | mzLib's names. Not uniform. |
+---------------------+-------+------------------------+---------------------------------------+
views == [] is a real and common answer - nineteen types have it. TopPIC, Crux, MSFragger's
peptide and protein tables, the FlashDeconv formats and MetaMorpheus's protein-group and peptide
tables (and their RNA counterparts) each parse into their own record type with nothing in common. mzLib reads them and so does :func:read_records; there is simply no uniform
view to project them onto, and inventing one here would mean publishing a schema mzLib does not
have.
So: use a typed view when you need numbers that mean the same thing across files, and
:func:read_records when you need everything a format has. A .psmtsv read through
:func:read_results gives 10 comparable columns; the same file through :func:read_records gives
73, including the q-values and scores the uniform view does not carry.
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: MetaMorpheus retention times are in minutes and MSFragger's are too (mzLib PR #1116 converts them at the reader), but TopPIC's are still 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.
Two quantification tables have typed functions of their own (mzLib 1.0.592, #1347). They
belong to no uniform view - :func:read_records reads them too - but their per-sample values are
dictionaries that :func:read_records cannot project, so these return them as long tables,
one row per record per sample:
+-------------------------------------+------------------------------------------------------------+
| function | reads |
+=====================================+============================================================+
| :func:read_protein_groups | MetaMorpheus AllQuantifiedProteinGroups.tsv: one row |
| | per group per sample group - spectral count, intensity. |
+-------------------------------------+------------------------------------------------------------+
| :func:read_quantified_peptides | FlashLFQ QuantifiedPeptides.tsv (and MetaMorpheus's |
| | AllQuantifiedPeptides.tsv): one row per peptide per |
| | sample - intensity, detection type. |
+-------------------------------------+------------------------------------------------------------+
| :func:read_occupancy | the same protein-group table's PTM site occupancy: one row |
| | per group, sample group, basis and modified site. |
+-------------------------------------+------------------------------------------------------------+
Many files at once. Every read function has a _many twin - :func:read_spectra_many,
:func:read_records_many, :func:identify_many and so on - that takes a list of paths and
returns ONE long table, whose first two columns say which file each row came from
(source_index, source_path), plus one :class:FileReport per file in
:attr:ReadBatch.files. The list is read by one bridge process, threads files at a time, so
two hundred runs cost one .NET start-up rather than two hundred. The answer is identical at any
threads; the default is 1 because each file in flight is held whole in memory. There is
deliberately no Python-side thread or process pool anywhere in this module: parallelism is the
bridge's to express, once, where it can be counted.
Four ways a field can have no value, and each is named. A None in a table can mean four
different things, and conflating them is how a missing column turns into a measured zero:
absent_fields- the function defines the field, but this file's format has no column for it: MBR Score in a current FlashLFQ peaks table (mzLib #1345),q_valuein an MsPathFinderT targets file, apex intensity in a FLASHDeconv feature file. Every value in the column isNone, whatever default mzLib filled in.failed_fields- the field exists, but reading it threw for some rows (a UniProt-shaped accession parsed from a plain FASTA header).Nonein those rows.excluded_fields- the field has no column shape (a dictionary, a nested object), or none without loss (an SDRF row's header and cells), so it does not cross in this function at all; each entry names the function that does carry it.- a
Nonein one row, with the field in none of those lists - the value is genuinely missing for that row: the precursor of an MS1 scan, a blank intensity cell.
.. note::
That units mismatch was not hypothetical, and the fix shows where such things belong. Passing an
MSFragger psm.tsv to :func:pymzlib.flashlfq.quantify used to return near-zero intensities,
because FlashLFQ read the seconds as minutes and searched for each peptide about sixty times too
late in the gradient. It was fixed upstream in mzLib (#1116
<https://github.com/smith-chem-wisc/mzLib/pull/1116>_, converting at the reader) rather than
papered over here, so every mzLib consumer benefits and this library's caveat and
retention_time_unit changed with it. That is the standing rule: a value whose meaning or
availability is wrong is repaired in the core contract, and a binding discloses rather than
repairs.
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).
ReadError
dataclass
¶
Why one file of a _many read could not be read, under on_error="skip".
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
|
type |
str
|
What the failure would have been raised as on its own: |
message |
str
|
mzLib's own message. |
Source code in pkg/python/src/pymzlib/readers.py
SpectraSource
dataclass
¶
What a spectra file records about the run it came from (mzLib SourceFile, #1349).
The facts a batch or instrument confound is built from: which instrument, which unit of that
model, and when. Every field is None when the file does not record it - MGF and msalign
record none of them.
Attributes:
| Name | Type | Description |
|---|---|---|
instrument_model |
str | None
|
The instrument model's name, e.g. |
instrument_model_accession |
str | None
|
Its PSI-MS accession, e.g. |
instrument_serial_number |
str | None
|
The instrument's serial number, verbatim, e.g. |
acquisition_start_time |
str | None
|
When acquisition started, as ISO-8601 text, e.g.
|
acquisition_start_time_is_utc |
bool
|
|
Source code in pkg/python/src/pymzlib/readers.py
acquired_at
property
¶
:attr:acquisition_start_time as a :class:datetime.datetime, or None.
Timezone-aware (UTC) when :attr:acquisition_start_time_is_utc, and naive otherwise:
a local clock reading with no known offset must not be given one.
SkippedMatch
dataclass
¶
An mzIdentML identification item mzLib did not turn into a row, and why (mzLib #1313).
Attributes:
| Name | Type | Description |
|---|---|---|
spectrum_identification_item_id |
str
|
The item's |
spectrum_id |
str
|
The spectrum's nativeID, as written. |
reason |
str
|
Why it was skipped, e.g. |
Source code in pkg/python/src/pymzlib/readers.py
FileReport
dataclass
¶
The per-file facts of one input to a _many read: one entry of :attr:ReadBatch.files.
One per input, in input order; a file's rows in the batch table are those whose
source_index is its position. The fields are the ones a single-file read reports at its top
level, under the same names, so what you learn about one reads the same for many.
The fields every reader reports come first; the rest belong to particular readers and are
None elsewhere. For an input that failed under on_error="skip", :attr:error says why
and the facts that could not be established are None or empty.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path of the input. |
file_type |
str | None
|
mzLib's |
reader |
str | None
|
The mzLib class that parsed the file. |
record_count |
int | None
|
Records mzLib read from the whole file, in the reader's own unit - matches,
scans passing |
rows_not_read |
int | None
|
Data lines that did not become records, counted where one line is one
record (the psmtsv family and MSFragger); mzLib drops a malformed line silently.
|
retention_time_unit |
str | None
|
The unit of the reader's time columns for this file: |
caveats |
list[str]
|
What the reader cannot be trusted to mean for this file, each citing the mzLib source. |
column_names |
list[str]
|
This file's columns, without the |
absent_fields |
list[str]
|
Columns the reader defines but this file has no source for - its
format has no such column - so every value in them is |
failed_fields |
list[str]
|
|
excluded_fields |
list[dict[str, Any]]
|
Fields that have no column shape and so do not cross, each as
|
error |
ReadError | None
|
Why this input could not be read, under |
record_type |
str | None
|
:func: |
views |
list[str] | None
|
:func: |
scan_count |
int | None
|
:func: |
source |
SpectraSource | None
|
:func: |
skipped_count |
int | None
|
mzIdentML items mzLib did not represent (:func: |
skipped |
list[SkippedMatch] | None
|
The same items, each a :class: |
sample_labels |
list[str] | None
|
The quantification readers only - the file's sample labels, in header order. |
truncated_cell_count |
int | None
|
:func: |
Source code in pkg/python/src/pymzlib/readers.py
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 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 | |
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. |
error |
ReadError | None
|
Always |
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 a read wrote its 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 - for a |
Source code in pkg/python/src/pymzlib/readers.py
ResultRecords
dataclass
¶
Bases: _Table
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
|
Records skipped: 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, e.g., TopPIC retention times are seconds while MetaMorpheus's and MSFragger'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 |
reader |
Any
|
The mzLib class that parsed the file, e.g. |
absent_fields |
list[str]
|
Columns this view defines but this file's format has no column for, so
every value is |
failed_fields |
list[str]
|
|
excluded_fields |
list[dict[str, Any]]
|
Fields with no column shape. Always empty for this view. |
error |
ReadError | None
|
Always |
Source code in pkg/python/src/pymzlib/readers.py
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 | |
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.
NativeRecords
dataclass
¶
Bases: _Table
A result file read into its own fields, whatever format it is.
What :func:read_records returns. Unlike every other result type in this module, the columns
here are not uniform: they are the fields of this format's own mzLib record type, under
mzLib's own names in snake_case. A TopPIC file gives you TopPIC's thirty-six columns; a Crux
file gives you Crux's twenty-three. Always read :attr:column_names rather than assuming.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path that was read. |
file_type |
str
|
mzLib's |
reader |
Any
|
The mzLib class that parsed it. |
record_type |
str
|
The mzLib record class the columns came from, e.g. |
record_count |
int
|
Records in the whole file, regardless of |
returned_count |
int
|
Records carried back in :attr: |
offset |
int
|
Records skipped: the offset that was applied. |
truncated |
bool
|
Whether records were left behind, by either |
views |
list[str]
|
The uniform views this file also supports, if any - see the module docstring. |
excluded_fields |
list[dict[str, Any]]
|
Fields of the record type that could not become columns, each as
|
failed_fields |
list[str]
|
Fields that raised while being read, with the exception type. Several
mzLib properties are computed and assume a UniProt-style FASTA header - Crux's and
MsPathFinderT's |
absent_fields |
list[str]
|
Columns this file has no source for: the record type reads them from an
optional column the file does not have, so every value is mzLib's default, and is
|
column_names |
list[str]
|
The field names, in order - base-class fields first, then declared ones. |
columns |
Any
|
Field name -> list of values, one entry per record. |
output |
Any
|
Where the table was written, or |
rows_not_read |
Any
|
Data rows that did not become records, counted where one line is one
record (the psmtsv family and MSFragger), since mzLib drops a malformed line silently.
|
retention_time_unit |
Any
|
Always |
caveats |
list[str]
|
Always empty for this function. |
skipped_count |
int | None
|
mzIdentML only - identification items mzLib did not represent as records
(crosslinks, unresolvable modifications, substitutions), so |
skipped |
list[SkippedMatch] | None
|
The same items, each a :class: |
error |
ReadError | None
|
Always |
Source code in pkg/python/src/pymzlib/readers.py
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 | |
FeatureRecords
dataclass
¶
Bases: _Table
Deconvolved MS1 features, in the cross-format ms1_features view.
What :func:read_features returns. Columns are mz, charge, retention_time_start,
retention_time_end, intensity and number_of_isotopes - the same for every format
that offers the view, so they are comparable across files, subject to
:attr:retention_time_unit.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path that was read. |
file_type |
str
|
mzLib's |
record_count |
int
|
Features in the whole file. For |
returned_count |
int
|
Features carried back in :attr: |
offset |
int
|
Features skipped: the offset that was applied. |
truncated |
bool
|
Whether features were left behind, by either |
retention_time_unit |
str
|
|
caveats |
list[str]
|
What this view cannot be trusted to mean for this format, each citing the mzLib source it came from. |
column_names |
list[str]
|
The field names, in order. |
columns |
Any
|
Field name -> list of values. |
output |
Any
|
Where the table was written, or |
reader |
Any
|
The mzLib class that parsed the file, e.g. |
rows_not_read |
Any
|
Always |
absent_fields |
list[str]
|
Columns this file has no source for, so every value is |
failed_fields |
list[str]
|
|
excluded_fields |
list[dict[str, Any]]
|
Always empty for this view. |
error |
ReadError | None
|
Always |
Source code in pkg/python/src/pymzlib/readers.py
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 | |
retention_time_start_in_minutes
property
¶
retention_time_start in minutes, or a raised error if the unit is unknown.
Raises rather than guessing. For _ms1.feature the unit genuinely is unknown, and a
silently unconverted time axis is the specific mistake this module exists to prevent -
mzLib's own deconvolution code guesses here, and this will not.
retention_time_end_in_minutes
property
¶
retention_time_end in minutes, or a raised error if the unit is unknown.
MatchRecords
dataclass
¶
Bases: _Table
Identifications, in the cross-format spectral_match view.
What :func:read_matches returns. Columns are file_name_without_extension,
one_based_scan_number, base_sequence, full_sequence, accession, is_decoy,
modifications, modification_count, q_value, rank and pass_threshold - and,
with scores=True, match_index, score_name and score_value.
Nothing here is FDR-filtered. q_value is filled only by mzIdentML and by an
MsPathFinderT file that carries a QValue column; :attr:absent_fields names it for every
other file. Filter before you report.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path that was read. |
file_type |
str
|
mzLib's |
record_count |
int
|
Matches in the whole file. |
returned_count |
int
|
Matches carried back in :attr: |
row_count |
int
|
Rows in :attr: |
offset |
int
|
Matches skipped: the offset that was applied. |
truncated |
bool
|
Whether matches were left behind, by either |
caveats |
list[str]
|
What this view cannot be trusted to mean for this format - that MsPathFinderT
infers decoys from an |
column_names |
list[str]
|
The field names, in order. |
columns |
Any
|
Field name -> list of values. |
output |
Any
|
Where the table was written, or |
reader |
Any
|
The mzLib class that parsed the file, e.g. |
scores_included |
bool
|
Whether |
skipped_count |
int | None
|
mzIdentML only - identification items mzLib did not turn into rows
(crosslinks, unresolvable modifications, substitutions); |
skipped |
list[SkippedMatch] | None
|
The same items, each a :class: |
rows_not_read |
Any
|
Always |
retention_time_unit |
Any
|
Always |
absent_fields |
list[str]
|
Columns this file's format has no source for, so every value is |
failed_fields |
list[str]
|
|
excluded_fields |
list[dict[str, Any]]
|
Always empty for this view. |
error |
ReadError | None
|
Always |
Source code in pkg/python/src/pymzlib/readers.py
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 | |
ScanRecords
dataclass
¶
Bases: _Table
Scan headers - and optionally peaks - from a spectra file.
What :func:read_spectra returns. Retention times here are in minutes for every format:
mzLib's spectra readers convert at the boundary, unlike its result-file readers, which pass the
tool's own unit through untouched.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path that was read. |
file_type |
str
|
mzLib's |
reader |
Any
|
The mzLib class that parsed it, e.g. |
scan_count |
int
|
Scans in the whole file, before any |
ms_order |
Any
|
The MS level filtered to, or |
record_count |
int
|
Scans that passed the |
returned_count |
int
|
Scans carried back in :attr: |
offset |
int
|
Scans skipped: the offset that was applied, counted after |
truncated |
bool
|
Whether scans were left behind, by either |
peaks_included |
bool
|
Whether |
retention_time_unit |
str
|
Always |
caveats |
list[str]
|
What this view cannot be trusted to mean for this format - that msalign holds deconvolved neutral masses rather than m/z, that MGF scan numbers come from a title line, that Bruker needs Windows-x64 native libraries. |
column_names |
list[str]
|
The field names, in order. |
columns |
Any
|
Field name -> list of values. When :attr: |
output |
Any
|
Where the table was written, or |
source |
SpectraSource | None
|
What the file records about the run - instrument model and serial number, and
when acquisition started (mzLib #1349) - as a :class: |
rows_not_read |
Any
|
Always |
absent_fields |
list[str]
|
Always empty for this view: a scan field a file does not record is |
failed_fields |
list[str]
|
|
excluded_fields |
list[dict[str, Any]]
|
Always empty for this view. |
error |
ReadError | None
|
Always |
Source code in pkg/python/src/pymzlib/readers.py
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 | |
total_ion_current
property
¶
The total_ion_current column, for the commonest plot there is.
ProteinGroupRecords
dataclass
¶
Bases: _Table
A MetaMorpheus protein-group table in long form: one row per group per sample group.
What :func:read_protein_groups returns. Columns: protein_group_name, gene,
organism, decoy_contaminant_target, is_decoy, is_contaminant,
is_entrapment, q_value, then sample_label, spectral_count and intensity.
Unfiltered. Decoys, contaminants and groups above 1% FDR are all rows, as MetaMorpheus
writes them. Filter on q_value and decoy_contaminant_target before counting.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path that was read. |
file_type |
str
|
|
reader |
Any
|
|
sample_labels |
list[str]
|
The file's sample-group labels, in header order, verbatim - e.g.
|
record_count |
int
|
Protein groups in the whole file - groups, not rows. |
returned_count |
int
|
Groups carried back in :attr: |
row_count |
int
|
Rows in :attr: |
offset |
int
|
Groups skipped. |
truncated |
bool
|
Whether groups were left behind, by either |
rows_not_read |
Any
|
Always |
retention_time_unit |
Any
|
Always |
caveats |
list[str]
|
What this table cannot be trusted to mean, each citing the mzLib source. |
column_names |
list[str]
|
The field names, in order. |
columns |
Any
|
Field name -> list of values. |
output |
Any
|
Where the table was written, or |
absent_fields |
list[str]
|
Columns this file has no column for, so every value is |
failed_fields |
list[str]
|
|
excluded_fields |
list[dict[str, Any]]
|
|
error |
ReadError | None
|
Always |
Source code in pkg/python/src/pymzlib/readers.py
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 | |
QuantifiedPeptideRecords
dataclass
¶
Bases: _Table
A FlashLFQ peptide table in long form: one row per peptide per sample.
What :func:read_quantified_peptides returns. Columns: sequence (the full, modified
sequence), base_sequence, peak_order, protein_groups, gene_names,
organism, then sample_label, intensity, detection_type and retention_time.
An intensity of 0 is not a measurement. FlashLFQ writes a literal 0 for a peptide it did
not quantify in a sample; detection_type ("MSMS", "MBR", "NotDetected", ...)
is what tells the two apart.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path that was read. |
file_type |
str
|
|
reader |
Any
|
|
sample_labels |
list[str]
|
The file's sample labels, in header order, verbatim. |
record_count |
int
|
Peptides in the whole file - peptides, not rows. |
returned_count |
int
|
Peptides carried back in :attr: |
row_count |
int
|
Rows in :attr: |
offset |
int
|
Peptides skipped. |
truncated |
bool
|
Whether peptides were left behind, by either |
rows_not_read |
Any
|
Always |
retention_time_unit |
Any
|
|
caveats |
list[str]
|
What this table cannot be trusted to mean, each citing the mzLib source. |
column_names |
list[str]
|
The field names, in order. |
columns |
Any
|
Field name -> list of values. |
output |
Any
|
Where the table was written, or |
absent_fields |
list[str]
|
Columns this file has no column for, so every value is |
failed_fields |
list[str]
|
|
excluded_fields |
list[dict[str, Any]]
|
Always empty for this table. |
error |
ReadError | None
|
Always |
Source code in pkg/python/src/pymzlib/readers.py
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 | |
OccupancyRecords
dataclass
¶
Bases: _Table
PTM site occupancy from a MetaMorpheus protein-group table: one row per modified site.
What :func:read_occupancy returns. Each row is one site in one occupancy cell - one group,
one sample group, one basis. Columns: protein_group_name, sample_label, basis
("count" or "intensity"), entity_index, position, is_n_terminus,
modification, fraction, numerator, denominator and cell_is_truncated.
Which number to trust depends on the basis. A "count" cell prints its fraction to two
decimals, so use numerator / denominator (PSMs modified / PSMs covering the site); an
"intensity" cell prints its numerator and denominator to four significant digits, so use
fraction.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path that was read. |
file_type |
str
|
|
reader |
Any
|
|
sample_labels |
list[str]
|
The file's sample-group labels, in header order. |
truncated_cell_count |
int
|
Occupancy cells the writer cut short or replaced with |
record_count |
int
|
Protein groups in the whole file - groups, not rows. |
returned_count |
int
|
Groups carried back - groups, not rows. Zero when |
row_count |
int
|
Site rows in :attr: |
offset |
int
|
Groups skipped. |
truncated |
bool
|
Whether groups were left behind by |
rows_not_read |
Any
|
Always |
retention_time_unit |
Any
|
Always |
caveats |
list[str]
|
What this table cannot be trusted to mean. |
column_names |
list[str]
|
The field names, in order. |
columns |
Any
|
Field name -> list of values. |
output |
Any
|
Where the table was written, or |
absent_fields |
list[str]
|
Every site column, when the file has no occupancy columns at all (then there are no rows). |
failed_fields |
list[str]
|
|
excluded_fields |
list[dict[str, Any]]
|
Always empty for this table. |
error |
ReadError | None
|
Always |
Source code in pkg/python/src/pymzlib/readers.py
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 | |
ReadBatch
dataclass
¶
Bases: _Table
Many files read into ONE long table: what every _many read function returns.
The table's first two columns say where each row came from: source_index, the file's
0-based position in the list you passed, and source_path, its absolute path. The rest are
the single-file function's columns. Rows are grouped by file in input order, each file's rows
in the file's own order - whatever threads was, so the same list always gives the
same table. The per-file facts are in :attr:files, one :class:FileReport per input.
Attributes:
| Name | Type | Description |
|---|---|---|
verb |
str
|
The bridge command that produced it, e.g. |
file_count |
int
|
Files in the list you passed. |
read_count |
int
|
Files read. |
failed_count |
int
|
Files that could not be read - always 0 unless |
on_error |
str
|
|
record_count |
int
|
Records read, summed over the files read, in the reader's own unit (scans, matches, groups, ...). Not always the row count: a long reader gives several rows per record. |
returned_count |
int
|
Records carried back in :attr: |
row_count |
int
|
Rows in :attr: |
column_names |
list[str]
|
|
columns |
Any
|
Column name -> list of values, one per row - the shape |
output |
Any
|
Where the table was written, or |
files |
list[FileReport]
|
One :class: |
ms_order |
Any
|
:func: |
peaks_included |
bool
|
:func: |
scores_included |
bool
|
:func: |
Source code in pkg/python/src/pymzlib/readers.py
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 | |
failed_files
property
¶
The inputs that could not be read, under on_error="skip". Empty otherwise.
in_minutes ¶
A time column in minutes, converting each file's rows by that file's own unit.
The multi-file form of :attr:ResultRecords.retention_time_in_minutes: every file's
:attr:FileReport.retention_time_unit is applied to that file's rows, so a batch that mixes
formats comes back on one axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
str
|
The time column, e.g. |
required |
Returns:
| Type | Description |
|---|---|
list[Any]
|
The column's values in minutes, one per row. |
Raises:
| Type | Description |
|---|---|
UsageError
|
the table went to |
Source code in pkg/python/src/pymzlib/readers.py
IdentifyBatch
dataclass
¶
What :func:identify_many returns: one :class:FileInfo per path, in the order given.
Attributes:
| Name | Type | Description |
|---|---|---|
file_count |
int
|
Paths given. |
read_count |
int
|
Paths identified. |
failed_count |
int
|
Paths that could not be identified - always 0 unless |
on_error |
str
|
|
files |
list[FileInfo]
|
One :class: |
Source code in pkg/python/src/pymzlib/readers.py
failed_files
property
¶
The paths that could not be identified, under on_error="skip".
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: |
Examples:
>>> quantifiable = [f.file_type for f in formats() if f.is_quantifiable]
>>> quantifiable
['psmtsv', 'osmtsv', 'MsFraggerPsm', 'DiaNnReport']
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 | PathLike[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: |
Examples:
>>> info = identify("PXD078927_msgf_1_1_0.mzid")
>>> info.file_type, info.views
('MzIdentML', ['spectral_match'])
Source code in pkg/python/src/pymzlib/readers.py
identify_many ¶
identify_many(paths: PathList, *, threads: int = 1, on_error: str = 'fail', timeout: float | None = 60) -> IdentifyBatch
Identify many files in one call, without parsing their contents.
:func:identify for a list: one bridge process, the answers in the order given. The cheap way
to sort a directory of unknown files before reading any of them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
PathList
|
The files to identify, as a list of |
required |
threads
|
int
|
Files identified at once: |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow for the whole list. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
IdentifyBatch
|
class: |
IdentifyBatch
|
path, in order. |
Raises:
| Type | Description |
|---|---|
UsageError
|
|
BridgeError
|
with |
Examples:
>>> # Not run in CI: the replay bridge answers single-path calls only.
>>> batch = identify_many(["run.mzML", "AllPSMs.psmtsv", "notes.txt"],
... on_error="skip")
>>> [f.file_type for f in batch.files]
['MzML', 'psmtsv', '']
>>> batch.failed_files[0].error.kind
'usage'
Source code in pkg/python/src/pymzlib/readers.py
read_results ¶
read_results(path: str | PathLike[str], *, limit: int | None = None, offset: int = 0, out: str | PathLike[str] | None = None, timeout: float | None = None) -> ResultRecords
Read a result file into the uniform record view.
Only the four 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. :func:read_results_many reads a list of them into one table.
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 | PathLike[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 | PathLike[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.
The path must end in |
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. |
Examples:
>>> r = read_results("FraggerPsm_FragPipev21.1_psm.tsv", limit=2)
>>> r.record_count, r.returned_count, r.absent_fields
(5, 2, ['is_decoy'])
pandas is not a dependency of pyMzLib, so these lines are not executed:
Source code in pkg/python/src/pymzlib/readers.py
read_results_many ¶
read_results_many(paths: PathList, *, out: str | PathLike[str] | None = None, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> ReadBatch
Read many result files into one long table of the uniform record view.
:func:read_results for a list, which may mix the four quantifiable formats: the columns are
the same for all of them. Their units need not be - use :meth:ReadBatch.in_minutes for
retention_time - and each file's caveats are in its :class:FileReport.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
PathList
|
The files to read, as a list (or any iterable) of |
required |
out
|
str | PathLike[str] | None
|
Write the table to this path as tab-separated text and return only a summary
(:attr: |
None
|
threads
|
int
|
Files to read at once: |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow for the whole batch. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ReadBatch
|
class: |
ReadBatch
|
|
Raises:
| Type | Description |
|---|---|
UsageError
|
|
BridgeError
|
with |
Examples:
>>> # Not run in CI: the replay bridge answers single-path calls only.
>>> batch = read_results_many(["a/AllPSMs.psmtsv", "b/psm.tsv"], threads=2)
>>> [(f.file_type, f.record_count) for f in batch.files]
[('psmtsv', 8), ('MsFraggerPsm', 6)]
Source code in pkg/python/src/pymzlib/readers.py
read_records ¶
read_records(path: str | PathLike[str], *, limit: int | None = None, offset: int = 0, out: str | PathLike[str] | None = None, timeout: float | None = None) -> NativeRecords
Read any file mzLib recognises, into that format's own fields.
This is the exhaustive verb: if :func:identify succeeds on a path, this reads it. All
thirty-eight file types, including the nineteen that belong to no cross-format view at all -
TopPIC, Crux, MSFragger's peptide and protein tables, the FlashDeconv formats, MetaMorpheus's
protein-group and peptide tables and their RNA counterparts - which no other
function here can touch.
The columns are not uniform, by design. They are this format's own mzLib record fields,
under mzLib's own names in snake_case: a TopPIC file gives thirty-six columns, a Crux file
twenty-three, an experiment annotation five. Read :attr:NativeRecords.column_names, and use
:func:read_results, :func:read_features or :func:read_matches when you need columns that
mean the same thing across formats.
Nothing is silently dropped. A field that could not become a column is named in
:attr:NativeRecords.excluded_fields, one that raised while being read in
:attr:NativeRecords.failed_fields, and one this file's format has no column for in
:attr:NativeRecords.absent_fields - so a missing value never has to be guessed at.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to any file mzLib recognises. A Bruker |
required |
limit
|
int | None
|
Maximum records to return. |
None
|
offset
|
int
|
Records to skip. A window, not a cursor - see :func: |
0
|
out
|
str | PathLike[str] | None
|
Write a tab-separated table here and return only a summary.
The path must end in |
None
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
NativeRecords
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank, missing, or not a file type mzLib recognises. |
Examples:
>>> r = read_records("ToppicPrsm_TopPICv1.6.2_prsm.tsv")
>>> r.record_type, len(r.column_names), r.record_count
('ToppicPrsm', 36, 4)
pandas is not a dependency of pyMzLib, so this line is not executed:
Source code in pkg/python/src/pymzlib/readers.py
read_records_many ¶
read_records_many(paths: PathList, *, out: str | PathLike[str] | None = None, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> ReadBatch
Read many files of ONE record type into one long table of their own fields.
:func:read_records for a list. Because the columns are the record type's own, every file
must have the same record type - all mzIdentML, all FlashLFQ peaks tables, all TopPIC PrSMs.
A mixed list is refused with a UsageError before anything is parsed, whatever on_error
says, with the groups named so you can split it.
Each file's record_type, absent_fields and mzIdentML skipped list are in its
:class:FileReport.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
PathList
|
The files to read, as a list (or any iterable) of |
required |
out
|
str | PathLike[str] | None
|
Write the table to this path as tab-separated text and return only a summary
(:attr: |
None
|
threads
|
int
|
Files to read at once: |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow for the whole batch. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ReadBatch
|
class: |
ReadBatch
|
|
Raises:
| Type | Description |
|---|---|
UsageError
|
|
BridgeError
|
with |
Examples:
>>> # Not run in CI: the replay bridge answers single-path calls only.
>>> batch = read_records_many(sorted(Path("runs").glob("*.mzid.gz")), threads=4)
>>> batch.files[0].record_type, batch.record_count
('MzIdentMLRecord', 48213)
Source code in pkg/python/src/pymzlib/readers.py
read_features ¶
read_features(path: str | PathLike[str], *, limit: int | None = None, offset: int = 0, out: str | PathLike[str] | None = None, timeout: float | None = None) -> FeatureRecords
Read deconvolved MS1 features, in the cross-format ms1_features view.
Two file types offer it: TopFD/FLASHDeconv _ms1.feature and Dinosaur .feature.tsv. A
file without the view is rejected with a message naming the views it does have.
One row is not one line of the file for _ms1.feature. mzLib expands each deconvolved
feature into one single-charge feature per charge in its recorded range, so a hundred-feature
file can read as a thousand rows. Dinosaur is one-for-one. Both facts are in
:attr:FeatureRecords.caveats, and :func:read_records gives the file's own rows either way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to a |
required |
limit
|
int | None
|
Maximum features to return. |
None
|
offset
|
int
|
Features to skip. |
0
|
out
|
str | PathLike[str] | None
|
Write a tab-separated table here and return only a summary.
The path must end in |
None
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
FeatureRecords
|
class: |
FeatureRecords
|
comparing times - it is |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank, missing, unrecognised, or has no |
Examples:
>>> f = read_features("Ms1Feature_TopFDv1.6.2_ms1.feature", limit=5)
>>> f.record_count, f.returned_count, f.retention_time_unit
(25, 5, 'unknown')
>>> f.absent_fields
['number_of_isotopes']
Source code in pkg/python/src/pymzlib/readers.py
read_features_many ¶
read_features_many(paths: PathList, *, out: str | PathLike[str] | None = None, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> ReadBatch
Read many feature files into one long table of the ms1_features view.
:func:read_features for a list. Units differ per file - _ms1.feature times are genuinely
of unknown unit - so :meth:ReadBatch.in_minutes raises rather than put two units on one axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
PathList
|
The files to read, as a list (or any iterable) of |
required |
out
|
str | PathLike[str] | None
|
Write the table to this path as tab-separated text and return only a summary
(:attr: |
None
|
threads
|
int
|
Files to read at once: |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow for the whole batch. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ReadBatch
|
class: |
ReadBatch
|
and |
Raises:
| Type | Description |
|---|---|
UsageError
|
|
BridgeError
|
with |
Examples:
>>> # Not run in CI: the replay bridge answers single-path calls only.
>>> batch = read_features_many(["a.feature.tsv", "b.feature.tsv"])
>>> batch.file_count, batch.read_count
(2, 2)
Source code in pkg/python/src/pymzlib/readers.py
read_matches ¶
read_matches(path: str | PathLike[str], *, limit: int | None = None, offset: int = 0, scores: bool = False, out: str | PathLike[str] | None = None, timeout: float | None = None) -> MatchRecords
Read identifications, in the cross-format spectral_match view.
Six file types offer it: MsPathFinderT's targets, decoys and combined results, Casanovo's
.mztab, and mzIdentML (.mzid, and .mzid.gz read without unpacking it, mzLib #1313).
These are the identification formats that share no file-level interface, so
:func:read_results cannot reach them.
Nothing here is FDR-filtered. q_value is the only confidence column, filled by
mzIdentML (the PSM-level q-value, mzLib #1306) and by an MsPathFinderT _IcTda.tsv; for
every other file it is named in :attr:MatchRecords.absent_fields and None. mzIdentML
also lists every candidate, not only accepted ones: filter on rank == 1 and
pass_threshold before counting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to an MsPathFinderT |
required |
limit
|
int | None
|
Maximum matches to return. |
None
|
offset
|
int
|
Matches to skip. |
0
|
scores
|
bool
|
Add each search engine's own scores as long rows: one row per match and
score, with |
False
|
out
|
str | PathLike[str] | None
|
Write a tab-separated table here and return only a summary.
The path must end in |
None
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
MatchRecords
|
class: |
MatchRecords
|
it is inferred from a name prefix for MsPathFinderT and absent for Casanovo and mzIdentML. |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank, missing, unrecognised, or has no |
Examples:
>>> m = read_matches("MsPathFinderT_WithMods_IcTda.tsv")
>>> m.record_count, m.columns["modifications"][:3]
(5, ['37:Oxidation on M', '', '1:Acetylation on X;27:Acetylation on K'])
>>> s = read_matches("PXD078927_msgf_1_1_0.mzid", limit=1, scores=True)
>>> s.columns["score_name"][:3], s.columns["q_value"][0]
(['MS-GF:RawScore', 'MS-GF:DeNovoScore', 'MS-GF:SpecEValue'], 0)
Source code in pkg/python/src/pymzlib/readers.py
read_matches_many ¶
read_matches_many(paths: PathList, *, scores: bool = False, out: str | PathLike[str] | None = None, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> ReadBatch
Read many identification files into one long table of the spectral_match view.
:func:read_matches for a list - a directory of mzIdentML submissions, say. Each file's
skipped items and absent_fields are in its :class:FileReport.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
PathList
|
The files to read, as a list (or any iterable) of |
required |
out
|
str | PathLike[str] | None
|
Write the table to this path as tab-separated text and return only a summary
(:attr: |
None
|
threads
|
int
|
Files to read at once: |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow for the whole batch. |
None
|
scores
|
bool
|
As for :func: |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ReadBatch
|
class: |
ReadBatch
|
|
Raises:
| Type | Description |
|---|---|
UsageError
|
|
BridgeError
|
with |
Examples:
>>> # Not run in CI: the replay bridge answers single-path calls only.
>>> batch = read_matches_many(["a.mzid", "b.mzid.gz"], scores=True)
>>> sorted(set(batch.columns["score_name"]))[:2]
['MS-GF:DeNovoScore', 'MS-GF:EValue']
Source code in pkg/python/src/pymzlib/readers.py
read_spectra ¶
read_spectra(path: str | PathLike[str], *, limit: int | None = None, offset: int = 0, ms_order: int | None = None, peaks: bool = False, out: str | PathLike[str] | None = None, timeout: float | None = None) -> ScanRecords
Read the scans of a spectra file: headers always, peaks on request.
Seven file types offer the spectra view: .mzML, .mgf, _ms1.msalign,
_ms2.msalign, Thermo .raw, Bruker .d and timsTOF .d. Each read also reports
what the file records about the run - instrument model and serial number, and when acquisition
started (:attr:ScanRecords.source, mzLib #1349).
Peaks are opt-in and should stay that way unless you need them. A scan header is tens of
bytes; its peak list is thousands, and a mid-size mzML holds tens of thousands of scans. With
peaks=True the mz and intensity columns each become a list of arrays, one per scan -
so pair it with limit, ms_order or out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to a spectra file. A Bruker |
required |
limit
|
int | None
|
Maximum scans to return. |
None
|
offset
|
int
|
Scans to skip, applied after |
0
|
ms_order
|
int | None
|
Keep only scans at this MS level - |
None
|
peaks
|
bool
|
Include the |
False
|
out
|
str | PathLike[str] | None
|
Write a tab-separated table here and return only a summary. With |
None
|
timeout
|
float | None
|
Seconds to allow. Reading a large |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ScanRecords
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank, missing, unrecognised, has no |
Examples:
>>> s = read_spectra("sliced_ethcd.mzML", ms_order=2, limit=2)
>>> s.scan_count, s.record_count, s.returned_count
(6, 5, 2)
>>> s.columns["selected_ion_mz"]
[548.453918457031, 796.765197753906]
>>> s.source.instrument_model, s.source.acquisition_start_time
('Orbitrap Fusion', '2021-03-16T17:09:07Z')
Source code in pkg/python/src/pymzlib/readers.py
read_spectra_many ¶
read_spectra_many(paths: PathList, *, ms_order: int | None = None, peaks: bool = False, out: str | PathLike[str] | None = None, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> ReadBatch
Read the scans of many spectra files into one long table.
:func:read_spectra for a list - every run of an experiment, with each file's instrument,
serial number and acquisition start in its :attr:FileReport.source. Retention times are
minutes for every format, so the table is on one time axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
PathList
|
The files to read, as a list (or any iterable) of |
required |
out
|
str | PathLike[str] | None
|
Write the table to this path as tab-separated text and return only a summary
(:attr: |
None
|
threads
|
int
|
Files to read at once: |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow for the whole batch. |
None
|
ms_order
|
int | None
|
Keep only scans at this MS level, in every file. |
None
|
peaks
|
bool
|
Include the |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ReadBatch
|
class: |
ReadBatch
|
|
Raises:
| Type | Description |
|---|---|
UsageError
|
|
BridgeError
|
with |
Examples:
>>> # Not run in CI: the replay bridge answers single-path calls only.
>>> runs = read_spectra_many(["run1.raw", "run2.raw"], ms_order=1, threads=2)
>>> [f.source.instrument_serial_number for f in runs.files]
['FSN20410', 'FSN20410']
Source code in pkg/python/src/pymzlib/readers.py
read_protein_groups ¶
read_protein_groups(path: str | PathLike[str], *, limit: int | None = None, offset: int = 0, out: str | PathLike[str] | None = None, timeout: float | None = None) -> ProteinGroupRecords
Read a MetaMorpheus protein-group table as one row per group per sample group.
AllQuantifiedProteinGroups.tsv keeps each group's per-sample spectral counts and
intensities in columns named after the samples, which mzLib 1.0.592 reads into a dictionary
(mzLib #1347) that :func:read_records cannot project. This is that dictionary as a long
table - sample_label, spectral_count, intensity - beside the fields you filter on.
A wide matrix is one pivot away; the readers guide shows it.
The table is unfiltered, as MetaMorpheus writes it: decoys, contaminants and groups above
1% FDR are all rows. The group's other fields - coverage, masses, member counts - are in
:func:read_records, joined on protein_group_name; PTM site occupancy is
:func:read_occupancy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to a MetaMorpheus protein-group table (:func: |
required |
limit
|
int | None
|
Maximum groups to return; each group gives one row per sample group. |
None
|
offset
|
int
|
Groups to skip. |
0
|
out
|
str | PathLike[str] | None
|
Write a tab-separated table here and return only a summary.
The path must end in |
None
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ProteinGroupRecords
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank or missing, or is not a protein-group table; or the bridge in use predates this function. |
Examples:
>>> g = read_protein_groups("MetaMorpheus_1.1.11_AllQuantifiedProteinGroups.tsv", limit=1)
>>> g.record_count, g.returned_count, len(g.sample_labels), g.row_count
(6, 1, 18, 18)
>>> g.records[0]["sample_label"], g.records[0]["intensity"]
('QE-002106_GM1_a-calib', 1838317.1674502683)
Source code in pkg/python/src/pymzlib/readers.py
read_protein_groups_many ¶
read_protein_groups_many(paths: PathList, *, out: str | PathLike[str] | None = None, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> ReadBatch
Read many MetaMorpheus protein-group tables into one long table.
:func:read_protein_groups for a list - one search per condition, say. Each file's sample
labels are in its :attr:FileReport.sample_labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
PathList
|
The files to read, as a list (or any iterable) of |
required |
out
|
str | PathLike[str] | None
|
Write the table to this path as tab-separated text and return only a summary
(:attr: |
None
|
threads
|
int
|
Files to read at once: |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow for the whole batch. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ReadBatch
|
class: |
ReadBatch
|
|
Raises:
| Type | Description |
|---|---|
UsageError
|
|
BridgeError
|
with |
Examples:
>>> # Not run in CI: the replay bridge answers single-path calls only.
>>> batch = read_protein_groups_many(["search1/AllQuantifiedProteinGroups.tsv",
... "search2/AllQuantifiedProteinGroups.tsv"])
>>> batch.record_count, batch.row_count
(12, 216)
Source code in pkg/python/src/pymzlib/readers.py
read_quantified_peptides ¶
read_quantified_peptides(path: str | PathLike[str], *, limit: int | None = None, offset: int = 0, out: str | PathLike[str] | None = None, timeout: float | None = None) -> QuantifiedPeptideRecords
Read a FlashLFQ peptide table as one row per peptide per sample.
FlashLFQ's QuantifiedPeptides.tsv - and MetaMorpheus's AllQuantifiedPeptides.tsv,
which is the same format - keeps per-sample intensities and detection types in columns named
after the samples, which mzLib 1.0.592 reads into a dictionary (mzLib #1347). This is that
dictionary as a long table: sample_label, intensity, detection_type and, for
IsoTracker output, retention_time.
An intensity of 0 is not a measured zero. FlashLFQ writes 0 for a peptide it did not
quantify in a sample; filter on detection_type before taking a mean or a log.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to a FlashLFQ |
required |
limit
|
int | None
|
Maximum peptides to return; each gives one row per sample. |
None
|
offset
|
int
|
Peptides to skip. |
0
|
out
|
str | PathLike[str] | None
|
Write a tab-separated table here and return only a summary.
The path must end in |
None
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
QuantifiedPeptideRecords
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank or missing, or is not a peptide table; or the bridge in use predates this function. |
Examples:
>>> p = read_quantified_peptides("MetaMorpheus_1.1.11_AllQuantifiedPeptides.tsv", limit=1)
>>> p.returned_count, p.row_count, p.absent_fields
(1, 18, ['peak_order', 'retention_time'])
>>> p.records[0]["intensity"], p.records[0]["detection_type"]
(0, 'NotDetected')
Source code in pkg/python/src/pymzlib/readers.py
read_quantified_peptides_many ¶
read_quantified_peptides_many(paths: PathList, *, out: str | PathLike[str] | None = None, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> ReadBatch
Read many FlashLFQ peptide tables into one long table.
:func:read_quantified_peptides for a list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
PathList
|
The files to read, as a list (or any iterable) of |
required |
out
|
str | PathLike[str] | None
|
Write the table to this path as tab-separated text and return only a summary
(:attr: |
None
|
threads
|
int
|
Files to read at once: |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow for the whole batch. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ReadBatch
|
class: |
ReadBatch
|
|
Raises:
| Type | Description |
|---|---|
UsageError
|
|
BridgeError
|
with |
Examples:
>>> # Not run in CI: the replay bridge answers single-path calls only.
>>> batch = read_quantified_peptides_many(["a/QuantifiedPeptides.tsv",
... "b/QuantifiedPeptides.tsv"])
>>> batch.read_count
2
Source code in pkg/python/src/pymzlib/readers.py
read_occupancy ¶
read_occupancy(path: str | PathLike[str], *, limit: int | None = None, offset: int = 0, out: str | PathLike[str] | None = None, timeout: float | None = None) -> OccupancyRecords
Read the PTM site occupancy of a MetaMorpheus protein-group table, one row per site.
MetaMorpheus writes two occupancy cells per group per sample group - one from PSM counts
(CountOccupancy_) and one from intensities (IntensityOccupancy_) - each a list of
modified sites encoded as text. mzLib 1.0.592 parses them (ModificationOccupancyCell,
1347); this returns every site of every cell as a row, with basis saying which cell it¶
came from.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to any MetaMorpheus protein-group table :func: |
required |
limit
|
int | None
|
Maximum groups to return. A group with no modified sites gives no rows. |
None
|
offset
|
int
|
Groups to skip. |
0
|
out
|
str | PathLike[str] | None
|
Write a tab-separated table here and return only a summary.
The path must end in |
None
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
OccupancyRecords
|
class: |
OccupancyRecords
|
attr: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank or missing, or is not a protein-group table; or the bridge in use predates this function. |
Examples:
>>> o = read_occupancy("MetaMorpheus_1.1.11_AllQuantifiedProteinGroups.tsv")
>>> o.record_count, o.returned_count, o.row_count, o.truncated_cell_count
(6, 6, 95, 0)
>>> row = o.records[0]
>>> row["basis"], row["position"], row["modification"], row["numerator"], row["denominator"]
('count', 329, 'Deamidation on N', 1, 2)
Source code in pkg/python/src/pymzlib/readers.py
read_occupancy_many ¶
read_occupancy_many(paths: PathList, *, out: str | PathLike[str] | None = None, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> ReadBatch
Read the PTM site occupancy of many MetaMorpheus protein-group tables into one table.
:func:read_occupancy for a list. Each file's truncated_cell_count is in its
:class:FileReport.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
PathList
|
The files to read, as a list (or any iterable) of |
required |
out
|
str | PathLike[str] | None
|
Write the table to this path as tab-separated text and return only a summary
(:attr: |
None
|
threads
|
int
|
Files to read at once: |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow for the whole batch. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ReadBatch
|
class: |
ReadBatch
|
and |
Raises:
| Type | Description |
|---|---|
UsageError
|
|
BridgeError
|
with |
Examples:
>>> # Not run in CI: the replay bridge answers single-path calls only.
>>> sites = read_occupancy_many(["s1/AllQuantifiedProteinGroups.tsv",
... "s2/AllQuantifiedProteinGroups.tsv"])
>>> [f.truncated_cell_count for f in sites.files]
[0, 0]
Source code in pkg/python/src/pymzlib/readers.py
pymzlib.sdrf¶
sdrf ¶
Read SDRF-Proteomics experimental-design files, and pool several into one table.
Every other reader in pyMzLib answers what did the search find. SDRF answers what was searched - which sample, which organism part, which replicate, which instrument settings - and that is the half you need to group results across experiments::
>>> import pymzlib
>>> doc = pymzlib.sdrf.read("PXD000070.sdrf.tsv")
>>> doc.row_count, len(doc.columns)
(6, 31)
>>> doc.value("characteristics[organism]") # doctest: +ELLIPSIS
['plasmodium falciparum', 'plasmodium falciparum', ...]
Pool several experiments into one analysis table, giving each a name you choose::
>>> pooled = pymzlib.sdrf.pool({
... "PXD000070.sdrf.tsv": "malaria",
... "PXD026824.sdrf.tsv": "colon",
... }, limit=4)
>>> pooled.document_count, pooled.row_count, pooled.labels
(2, 24, ['malaria', 'colon'])
This module is row-major, and every other reader here is columnar. That is not a style
choice. :func:pymzlib.readers.read_records and friends hand back columns, a
name-to-values dict, because their column names are a schema. SDRF's are data, and they
repeat: 649 files in the curated corpus carry comment[modification parameters] more than
once, up to eight times in one file, and one file repeats an empty name 23 times. A dict keyed
by name would silently keep one occurrence and drop the rest. So :attr:SdrfDocument.columns is
a list that may contain duplicates, :attr:SdrfDocument.rows is a list of cell lists, and
position is what links them. Use :meth:SdrfDocument.value for the first cell under a name and
:meth:SdrfDocument.all for every one.
Three things worth knowing before you index anything:
Rows are ragged. len(row) may be less than len(columns). Real files are like this -
PXD059974 in mzLib's own fixtures has a 46-column header with 17 of its 23 rows carrying 42
cells - and mzLib preserves it rather than padding, so the file round-trips byte for byte.
:meth:SdrfDocument.value returns None for a position a row does not reach.
Cells are raw strings, never interpreted. The SDRF key=value grammar
("NT=Oxidation;AC=UNIMOD:35") arrives exactly as written. It is not decoded, because it
cannot be told apart from a cell that merely contains = and ; - comment[file uri]
routinely carries pre-signed download URLs whose query strings contain Signature= and
Expires=.
A reserved word is a real value. "not available" and "not applicable" mean the
experiment stated an absence, which is not the same as a column the document does not have.
None means the latter. Do not collapse the two.
Three questions this module answers about a document, and one about ages. Each is mzLib's own answer, projected once in the bridge for all three bindings:
- :func:
validate- is this file well-formed? Structural findings from mzLib'sSdrfValidator: required columns, column order and casing, cell shape, row-key uniqueness. - :func:
lint- do these files write the same thing the same way? Cross-document drift fromSdrfDriftLint: one accession under two names, a column that is a CV term in one file and free text in another,"Homo sapiens"against"homo sapiens". - :func:
assess- does this file describe its samples at all?SdrfSampleInformativeness's verdict -Informative,PartialorSkeleton- with the counts behind it. - :func:
samples- what does it say about each sample?SdrfSampleBlock: one sample persource name, its characteristics and factor values, and ages read into years. - :func:
parse_ages-SdrfAge.TryParseover any age cells, SDRF or not. - :func:
design- can this file drive a quantification?SdrfLabelFreeDesign: the label-free experimental design MetaMorpheus and FlashLFQ take, or every reason it was refused.
The first three are blind in different places, which is why there are three. A file of
"not available" validates cleanly and lints clean, and only :func:assess sees that it says
nothing. Twenty individually valid files can still disagree, and only :func:lint looks across
them. Each result's caveats names the blind spot it leaves.
:func:validate, :func:assess and :func:samples each have a *_many form that reads a whole
corpus in one bridge call, with an explicit threads count - the batch is parallelised inside
the bridge, never by a Python loop.
WrittenSdrf
dataclass
¶
Where :func:pool wrote the merged document, when asked to write one.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The path written. |
row_count |
int
|
Rows written - the whole merged document, not the windowed slice. |
Source code in pkg/python/src/pymzlib/sdrf.py
SdrfDocument
dataclass
¶
One SDRF-Proteomics document: an ordered header, and rows of raw cells.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The path that was read. |
columns |
list[str]
|
The column names, verbatim and in document order. Names may repeat, and the
order is part of the document, so this is a list rather than a set. Names are never
case-normalised: the corpus contains |
rows |
list[list[str]]
|
One list of cells per row. Ragged: a row may be shorter than |
row_count |
int
|
Rows in the whole document, regardless of |
returned_count |
int
|
Rows actually carried back in :attr: |
offset |
int
|
The offset that was applied, in rows. |
truncated |
bool
|
Whether rows were left behind, by either |
caveats |
list[str]
|
What this document's data cannot tell you about itself - raggedness, repeated names, reserved words. Worth printing the first time you read an unfamiliar file. |
Source code in pkg/python/src/pymzlib/sdrf.py
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 239 240 241 242 243 244 245 | |
records
property
¶
The rows as dicts, for the common case of a document with no repeated column names.
Lossy when a name repeats - later positions overwrite earlier ones - which is exactly
why it is not the primary shape. :attr:has_repeated_columns says whether that applies to
this document. For a repeating document use :meth:all instead.
has_repeated_columns
property
¶
Whether any column name appears more than once - see :attr:records.
ragged_row_count
property
¶
How many returned rows carry fewer cells than there are columns.
index_of ¶
The position of the first column with this name, or -1 if absent.
Comparison is exact and case-sensitive, matching the SDRF specification and mzLib.
Source code in pkg/python/src/pymzlib/sdrf.py
indexes_of ¶
Every position carrying this name, in document order. Empty when the column is absent.
value ¶
The first cell under column, one entry per returned row.
None means the document does not have this column, or the row is too short to reach
it. It does not mean "empty": the SDRF reserved words "not available" and
"not applicable" are real values that an experiment chose to write, and they come back
as themselves.
Examples:
>>> doc = read("PXD000070.sdrf.tsv")
>>> doc.value("characteristics[disease]")
['not applicable', 'not applicable', ...]
Source code in pkg/python/src/pymzlib/sdrf.py
all ¶
Every cell under column, one list per returned row.
The accessor for a multi-cardinality column such as comment[modification parameters],
which legitimately repeats - up to eight times in one corpus file. Positions a row is too
short to reach are skipped rather than reported as None, so each inner list holds only
cells that exist.
Source code in pkg/python/src/pymzlib/sdrf.py
PooledSdrf
dataclass
¶
Bases: SdrfDocument
Several SDRF documents merged into one table.
Everything :class:SdrfDocument offers, plus where the rows came from. path is empty:
a pooled table is not a file that was read.
Attributes:
| Name | Type | Description |
|---|---|---|
columns |
list[str]
|
The merged header, a list that may repeat names: the union of every document's
columns in SDRF block order, a repeated name at the highest multiplicity any one
document used, and |
rows |
list[list[str]]
|
One list of raw cells per returned row. A cell a document did not have is
|
row_count |
int
|
Merged rows in the whole pooled table, regardless of |
returned_count |
int
|
Rows actually carried back in :attr: |
offset |
int
|
The offset that was applied, in rows. |
truncated |
bool
|
Whether rows were left behind by |
caveats |
list[str]
|
What a pooled table cannot tell you about itself - including, when no labels were given, that its provenance depends on where the files sat. |
document_count |
int
|
How many documents were pooled. |
paths |
list[str]
|
The paths pooled, in the order given. |
labels |
list[str]
|
The provenance label used for each, in the same order - either what you supplied
or mzLib's |
written |
WrittenSdrf | None
|
Where the merged document was written, when |
Source code in pkg/python/src/pymzlib/sdrf.py
source_documents ¶
The provenance label of each returned row - which document it came from.
FileError
dataclass
¶
Why one document in a *_many call produced no result, under on_error="skip".
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
|
message |
str
|
What went wrong, naming the file. |
Source code in pkg/python/src/pymzlib/sdrf.py
ValidationMessage
dataclass
¶
One finding from mzLib's SdrfValidator, located as precisely as its rule allows.
Attributes:
| Name | Type | Description |
|---|---|---|
severity |
str
|
|
rule |
str
|
The stable rule name, e.g. |
message |
str
|
A human-readable description including the offending value. |
row_index |
int | None
|
0-based index into the document's data rows, or |
line_number |
int | None
|
The 1-based line in the file - |
column_name |
str | None
|
The column involved, or |
Source code in pkg/python/src/pymzlib/sdrf.py
SdrfValidation
dataclass
¶
Bases: _Table
The structural findings for one SDRF document.
The findings are a table - columns maps severity, rule, message, row_index,
line_number and column_name to one value per finding, ready for
pandas.DataFrame(result.columns). :attr:messages gives the same rows as objects.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path validated. |
is_valid |
bool
|
|
error_count |
int
|
Findings of severity |
warning_count |
int
|
Findings of severity |
message_count |
int
|
All findings; the length of every column. |
row_count |
int
|
Data rows in the document (the header is not a row). |
column_names |
list[str]
|
The table's columns, in order. |
columns |
dict[str, list[Any]]
|
Column name to one value per finding. |
caveats |
list[str]
|
What a clean result does not mean - read these once. |
Source code in pkg/python/src/pymzlib/sdrf.py
ValidatedFile
dataclass
¶
One document's summary in a :func:validate_many result.
Every count is None when the document could not be read, and :attr:error then says why.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path. |
is_valid |
bool | None
|
No |
error_count |
int | None
|
|
warning_count |
int | None
|
|
message_count |
int | None
|
All findings; |
row_count |
int | None
|
Data rows in the document; |
error |
FileError | None
|
Why it was not read, or |
Source code in pkg/python/src/pymzlib/sdrf.py
SdrfValidationBatch
dataclass
¶
Bases: _Table
The findings for many SDRF documents, as one long table.
columns holds the same six columns as :class:SdrfValidation, preceded by
source_index (the document's 0-based position in the list you passed) and source_path.
Rows are in input order, then mzLib's order within a document, whatever threads was.
Attributes:
| Name | Type | Description |
|---|---|---|
file_count |
int
|
Documents given. |
read_count |
int
|
Documents validated. |
failed_count |
int
|
Documents that could not be read (only non-zero under |
record_count |
int
|
Rows in |
valid_count |
int
|
Documents read with no |
message_count |
int
|
Findings over every document read. |
files |
list[ValidatedFile]
|
One :class: |
column_names |
list[str]
|
The table's columns, |
columns |
dict[str, list[Any]]
|
Column name to one value per finding. |
caveats |
list[str]
|
As for :class: |
Source code in pkg/python/src/pymzlib/sdrf.py
messages
property
¶
Every finding as a :class:ValidationMessage; use columns to keep the source.
SdrfDrift
dataclass
¶
Bases: _Table
Concepts a set of SDRF documents wrote inconsistently, from mzLib's SdrfDriftLint.
columns is a long table, one row per finding x variant: a finding with three spellings
is three rows sharing a finding_index. Its columns:
finding_index- which finding the row belongs to, 0-based, most impactful first.kind-AccessionNameConflict(one accession, several names),NameAccessionConflict(one name, several accessions - the serious one),MixedTermAndFreeText,ColumnNameVariant(names differing only by case or spacing),ValueCaseVariant.concept- what was written inconsistently: an accession, a name, a normalised value, or a normalised column name, depending onkind.column_name- the column involved;NoneforColumnNameVariant, whose finding is about a name rather than a column's values.variant_rank- 0 for the majority spelling, then by frequency.value- this spelling exactly as written.occurrences- how widely it was used (a count of documents, at mzLib 1.0.592).documents- the labels of the documents that used it, as a list.
Attributes:
| Name | Type | Description |
|---|---|---|
document_count |
int
|
Documents linted. |
paths |
list[str]
|
The paths, in the order given. |
labels |
list[str]
|
The label each document is named by in |
finding_count |
int
|
Distinct findings (not rows). |
column_names |
list[str]
|
The table's columns. |
columns |
dict[str, list[Any]]
|
Column name to one value per finding x variant. |
caveats |
list[str]
|
Including why the majority spelling is not advice. |
Source code in pkg/python/src/pymzlib/sdrf.py
findings ¶
The rows grouped by finding: one list of variant dicts per finding, majority first.
Source code in pkg/python/src/pymzlib/sdrf.py
SdrfAssessment
dataclass
¶
Bases: _Table
Whether one SDRF document's sample half describes an experimental design.
mzLib's SdrfSampleInformativeness asks three questions, and the verdict is how many pass:
all three is Informative, none is Skeleton, anything between is Partial.
columns is the evidence: one row per column a check read, with role
(factor_value, sample_characteristic or biological_replicate), column_name,
rows, filled (rows with a real answer), absent (empty or a reserved word),
distinct_values (compared ignoring case and surrounding space) and fill_rate
(filled / rows, a fraction from 0 to 1).
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path assessed. |
verdict |
str
|
|
factor_value_varies |
bool
|
Some |
sample_is_described |
bool
|
Some |
biological_replicate_varies |
bool
|
|
row_count |
int
|
Data rows in the document. |
column_names |
list[str]
|
The evidence table's columns. |
columns |
dict[str, list[Any]]
|
Column name to one value per evidence row. |
caveats |
list[str]
|
Including when |
Source code in pkg/python/src/pymzlib/sdrf.py
AssessedFile
dataclass
¶
One document's verdict in an :func:assess_many result; None fields mean unread.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path. |
verdict |
str | None
|
|
factor_value_varies |
bool | None
|
As :attr: |
sample_is_described |
bool | None
|
As :attr: |
biological_replicate_varies |
bool | None
|
As :attr: |
row_count |
int | None
|
Data rows; |
error |
FileError | None
|
Why it was not read, or |
Source code in pkg/python/src/pymzlib/sdrf.py
SdrfAssessmentBatch
dataclass
¶
Bases: _Table
Verdicts for many SDRF documents, with the evidence as one long table.
Attributes:
| Name | Type | Description |
|---|---|---|
file_count |
int
|
Documents given. |
read_count |
int
|
Documents assessed. |
failed_count |
int
|
Documents that could not be read (only under |
record_count |
int
|
Rows in |
verdict_counts |
dict[str, int]
|
|
files |
list[AssessedFile]
|
One :class: |
column_names |
list[str]
|
The evidence columns of :class: |
columns |
dict[str, list[Any]]
|
Column name to one value per evidence row. |
caveats |
list[str]
|
As for :class: |
Source code in pkg/python/src/pymzlib/sdrf.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 | |
paths_with ¶
The paths whose verdict is one of verdicts, in input order.
Raises:
| Type | Description |
|---|---|
UsageError
|
a verdict that is not one of :data: |
Examples:
>>> batch = assess_many(
... ["sdrf_cohort.sdrf.tsv", "sdrf_skeleton.sdrf.tsv", "PXD000070.sdrf.tsv"]
... )
>>> [os.path.basename(p) for p in batch.paths_with("Informative", "Partial")]
['sdrf_cohort.sdrf.tsv', 'PXD000070.sdrf.tsv']
Source code in pkg/python/src/pymzlib/sdrf.py
SdrfSamples
dataclass
¶
Bases: _Table
Every sample in one SDRF document and what its rows agree on, as a long table.
A sample is a source name, matched ignoring case and surrounding space, exactly as mzLib's
SdrfSampleBlock.BySourceName keys it: one sample measured in three fractions is one sample.
columns has one row per sample x column x position, samples in document order:
source_name- the sample, as its first row spelled it.sample_row_count- how many rows of the document carry it.column_name- the header's own spelling (characteristics[Age]stays itself).column_kind-source_name,characteristicorfactor_value.position- 0 for the first occurrence of a repeated column, 1 for the second, and so on;Noneon a conflicting row.status-"agreed", or"conflicting"when the sample's rows disagree about the column: mzLib then withholds it rather than guess, andvalueisNone.value- the cell, verbatim. Reserved words are real answers and come back as themselves.age_years,age_min_years,age_max_years,age_precision,age_follows_specification,age_refusal- filled only oncharacteristics[age]rows, with exactly the meanings :class:ParsedAgesdocuments. On any other row all six areNone.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path read. |
sample_count |
int
|
Distinct samples (source names). |
row_count |
int
|
Data rows in the document. |
conflict_count |
int
|
Sample x column pairs withheld as conflicting. |
problems |
list[str]
|
Rows mzLib could not place - no |
column_names |
list[str]
|
The table's columns. |
columns |
dict[str, list[Any]]
|
Column name to one value per row of the table. |
caveats |
list[str]
|
Including how to key samples across documents. |
Source code in pkg/python/src/pymzlib/sdrf.py
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 | |
SampledFile
dataclass
¶
One document's summary in a :func:samples_many result; None fields mean unread.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path. |
sample_count |
int | None
|
Distinct samples; |
row_count |
int | None
|
Data rows; |
conflict_count |
int | None
|
Columns withheld as conflicting; |
problems |
list[str] | None
|
Rows mzLib could not place; |
error |
FileError | None
|
Why it was not read, or |
Source code in pkg/python/src/pymzlib/sdrf.py
SdrfSamplesBatch
dataclass
¶
Bases: _Table
The samples of many SDRF documents, as one long table.
columns has the columns of :class:SdrfSamples, preceded by source_index and
source_path. A source name is only unique within one document - two studies may both
have a "Sample 1" - so key a sample on (source_index, source_name).
Attributes:
| Name | Type | Description |
|---|---|---|
file_count |
int
|
Documents given. |
read_count |
int
|
Documents read. |
failed_count |
int
|
Documents that could not be read (only under |
record_count |
int
|
Rows in |
sample_count |
int
|
Samples over every document read. |
files |
list[SampledFile]
|
One :class: |
column_names |
list[str]
|
The table's columns. |
columns |
dict[str, list[Any]]
|
Column name to one value per row. |
caveats |
list[str]
|
As for :class: |
Source code in pkg/python/src/pymzlib/sdrf.py
ParsedAges
dataclass
¶
Bases: _Table
Age cells read into years by mzLib's SdrfAge.TryParse, one row per cell given.
columns has one row per input cell, in input order (blank cells included), with:
cell- the cell exactly as you gave it.years- the single figure to place the sample on an age axis, in years: the age, a range's midpoint, or a bound.Nonewhen refused.min_years- the youngest the cell allows, in years;0for an upper bound.Nonewhen refused.max_years- the oldest the cell allows, in years.Nonewhen refused or when there is no upper bound (precision == "LowerBound", e.g.>=90Y): mzLib's value is +infinity, which JSON cannot carry.precisiontells the two apart.precision- one of :data:AGE_PRECISIONS.Nonewhen refused.follows_specification-Truefor the specification's ownnYnMnD/nWgrammar,Falsefor unambiguous words ("3 year","6-8 weeks").Nonewhen refused.refusal-Nonewhen the cell was read, else one of :data:AGE_REFUSALS.
A month is 1/12 year, a week 7/365.25, a day 1/365.25, an hour 1/(365.25 x 24).
Attributes:
| Name | Type | Description |
|---|---|---|
cell_count |
int
|
Cells given; the length of every column. |
parsed_count |
int
|
Cells read as an age. |
column_names |
list[str]
|
The table's columns. |
columns |
dict[str, list[Any]]
|
Column name to one value per cell. |
caveats |
list[str]
|
The unit conventions and refusal rules. |
Source code in pkg/python/src/pymzlib/sdrf.py
DesignedFile
dataclass
¶
One run in a label-free design, in mzLib's SpectraFileInfo coordinates.
The design coordinates are 0-based, exactly as :func:pymzlib.flashlfq.quantify and
:func:pymzlib.flashlfq.median_polish take them. ExperimentalDesign.tsv writes the same
numbers plus one.
Attributes:
| Name | Type | Description |
|---|---|---|
full_path |
str
|
The file as the SDRF names it, or the searched path you passed for it. |
file_name |
str
|
|
condition |
str
|
The condition columns' values joined with |
biological_replicate |
int
|
0-based, ranked within the condition. |
technical_replicate |
int
|
0-based. |
fraction |
int
|
0-based. |
Source code in pkg/python/src/pymzlib/sdrf.py
SdrfDesign
dataclass
¶
Bases: _Table
A label-free experimental design read from an SDRF, or the reasons it was refused.
A refusal is an answer, not an exception. When is_valid is False, refusals lists
every reason at once and the table is empty, so a design that MetaMorpheus would reject can
never be used by mistake. mzLib refuses rather than repairs because MetaMorpheus skips
quantification with only a warning when its design file is invalid.
columns maps full_path, file_name, condition, biological_replicate,
technical_replicate and fraction to one value per run, in SDRF row order;
:attr:files gives the same rows as :class:DesignedFile objects.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The SDRF path as given. |
is_valid |
bool
|
|
file_key_column |
str | None
|
The column runs were keyed on - |
condition_columns |
list[str]
|
The |
condition_columns_declared |
bool
|
Whether you passed |
searched_files_given |
bool
|
Whether you passed |
file_count |
int
|
Runs (files) in the design; |
refusals |
list[str]
|
Every reason the design was refused, in mzLib's words. Empty when valid. |
notes |
list[str]
|
Every relabelling on the way to a valid design: biological replicates ranked within
a condition (with the |
report |
str
|
mzLib's human-readable account of all of the above. Print it. |
column_names |
list[str]
|
The table's columns, in order. |
columns |
dict[str, list[Any]]
|
Column name to one value per run. |
written |
dict[str, Any] | None
|
|
caveats |
list[str]
|
What the design does and does not cover - read these once. |
Source code in pkg/python/src/pymzlib/sdrf.py
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 | |
files
property
¶
Every run as a :class:DesignedFile, in SDRF row order. Empty when refused.
spectra ¶
The design as :func:pymzlib.flashlfq.quantify takes its spectra argument.
One mapping per run - path plus the four design fields - so the SDRF drives FlashLFQ
with no hand-written design. Each path is full_path; pass searched_files to
:func:design when the SDRF names files without the directory you keep them in.
Raises:
| Type | Description |
|---|---|
UsageError
|
the design was refused (mzLib's |
Source code in pkg/python/src/pymzlib/sdrf.py
run_design ¶
The design as :func:pymzlib.flashlfq.median_polish takes its design argument.
One mapping per run, keyed by file_name (the Intensity_<file_name> column of a
QuantifiedPeptides.tsv).
Raises:
| Type | Description |
|---|---|
UsageError
|
the design was refused. |
Source code in pkg/python/src/pymzlib/sdrf.py
read ¶
read(path: str | PathLike[str], *, limit: int | None = None, offset: int = 0, timeout: float | None = 60) -> SdrfDocument
Read one SDRF-Proteomics file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to a |
required |
limit
|
int | None
|
Maximum rows to return. |
None
|
offset
|
int
|
Rows to skip. |
0
|
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
SdrfDocument
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank, or the file is missing or unreadable as SDRF. |
Examples:
>>> doc = read("PXD000070.sdrf.tsv")
>>> doc.value("characteristics[organism part]")[0]
'human erythrocytes'
>>> doc.all("comment[modification parameters]")[0]
['NT=Carbamidomethyl;AC=UNIMOD:4;TA=C;MT=Fixed', 'NT=Oxidation;AC=UNIMOD:35;...]
Source code in pkg/python/src/pymzlib/sdrf.py
pool ¶
pool(documents: Sequence[str] | Mapping[str, str], *, out: str | PathLike[str] | None = None, limit: int | None = None, offset: int = 0, timeout: float | None = 60) -> PooledSdrf
Merge several SDRF documents into one analysis table.
Columns are the union of every document's, ordered by SDRF's own block structure, and a name
that repeats is carried at the highest multiplicity any single document used, so nothing is
dropped. A cell a document did not have is filled with the reserved word "not available",
and a comment[source document] column records which document each row came from.
Give your documents names. Pass a mapping to choose them. With a plain sequence, mzLib
falls back to containing-folder/file-stem, which depends on where the files happen to sit -
so the same two documents pooled from a different directory produce a different table. The
returned :attr:PooledSdrf.caveats says so when that fallback was used.
The result is an analysis table, not something to deposit. source name + assay
name + comment[label] is unique within one document, but two experiments may both have a
"Sample 1", so a pooled table will usually violate SDRF's uniqueness rule. Use the
source-document column as part of any key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
documents
|
Sequence[str] | Mapping[str, str]
|
The files to pool - a sequence of paths, or a |
required |
out
|
str | PathLike[str] | None
|
Write the merged document here as SDRF. The whole document is written regardless
of |
None
|
limit
|
int | None
|
Maximum rows to return over the wire. |
None
|
offset
|
int
|
Rows to skip. |
0
|
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
PooledSdrf
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
no documents were given, a path is missing, or a label is blank. |
Examples:
>>> pooled = pool({"PXD000070.sdrf.tsv": "malaria", "PXD026824.sdrf.tsv": "colon"}, limit=4)
>>> pooled.returned_count, pooled.truncated, set(pooled.source_documents())
(4, True, {'malaria'})
Source code in pkg/python/src/pymzlib/sdrf.py
validate ¶
Check one SDRF file against the SDRF-Proteomics specification's structural rules.
Calls mzLib's SdrfValidator.Validate. Structure only - required and recommended columns,
column order, casing, malformed names, ragged rows, integer replicate and fraction columns,
reserved-word casing, and the one hard row rule: source name + assay name +
comment[label] must be unique. Controlled-vocabulary accessions are not resolved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to a |
required |
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
SdrfValidation
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank or the file does not exist. |
BridgeError
|
mzLib could not read the file at all (for example, it is empty). |
Examples:
>>> result = validate("sdrf_cohort.sdrf.tsv")
>>> result.is_valid, result.error_count, result.warning_count
(True, 0, 2)
>>> for m in result.warnings:
... print(m.line_number, m.rule, m.column_name)
10 ReservedWordCase characteristics[age]
11 ReservedWordCase characteristics[age]
>>> skeleton = validate("sdrf_skeleton.sdrf.tsv")
>>> skeleton.is_valid, skeleton.errors[0].rule, skeleton.errors[0].line_number
(False, 'RequiredColumn', None)
Source code in pkg/python/src/pymzlib/sdrf.py
validate_many ¶
validate_many(paths: Sequence[str | PathLike[str]], *, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> SdrfValidationBatch
Validate many SDRF files in one bridge call.
One process for the whole corpus instead of one per file - roughly 120 ms saved per document -
with the parallelism inside the bridge, where it belongs. The result does not depend on
threads: rows are always in input order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
Sequence[str | PathLike[str]]
|
The files, in the order you want them reported. Each may be given once. |
required |
threads
|
int
|
Documents validated at once. |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow for the whole batch. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
SdrfValidationBatch
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
no paths, a blank or repeated path, a bad |
BridgeError
|
under |
Examples:
>>> batch = validate_many(
... ["sdrf_skeleton.sdrf.tsv", "sdrf_cohort.sdrf.tsv", "missing.sdrf.tsv"],
... on_error="skip",
... )
>>> batch.file_count, batch.read_count, batch.valid_count
(3, 2, 1)
>>> [f.is_valid for f in batch.files]
[False, True, None]
>>> batch.files[2].error.kind
'usage'
Source code in pkg/python/src/pymzlib/sdrf.py
lint ¶
Find the concepts a set of SDRF documents annotated inconsistently.
Validity is a property of one file; comparability is a property of the relationship between
files. Every document can pass :func:validate and the pooled table still be unusable because
one file writes "Homo sapiens" and another "homo sapiens". This is mzLib's check for that.
Columns that are unique per row by construction are never compared - source name,
assay name, comment[data file], comment[searched data file] (since mzLib 1.0.592),
comment[file uri] and comment[source document] - so differing file names are not
reported as drift. Reserved words and empty cells are skipped too, so a set of documents that
say nothing lints clean: use :func:assess for that.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
documents
|
Sequence[str] | Mapping[str, str]
|
The files - a sequence of paths, or a |
required |
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
SdrfDrift
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
no documents, a missing file, or a blank label. |
Examples:
>>> drift = lint({"sdrf_cohort.sdrf.tsv": "cohort", "sdrf_cohort_partner.sdrf.tsv": "partner"})
>>> drift.finding_count
4
>>> for variants in drift.findings():
... print(variants[0]["kind"], [v["value"] for v in variants])
AccessionNameConflict ['Exploris 480', 'Orbitrap Exploris 480']
MixedTermAndFreeText ['controlled vocabulary term', 'free text']
ColumnNameVariant ['Characteristics[sex]', 'characteristics[sex]']
ValueCaseVariant ['Homo sapiens', 'homo sapiens']
Source code in pkg/python/src/pymzlib/sdrf.py
assess ¶
Decide whether an SDRF file actually describes its samples, or is a valid skeleton.
A file generated from a list of data files - reserved words in every sample column, one
replicate number, no factor - passes :func:validate, because reserved words are the
specification's correct way to say nothing. For grouping results by biology it is the same as
having no SDRF at all. mzLib's SdrfSampleInformativeness.Assess is the gate for that.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to a |
required |
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
SdrfAssessment
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank or the file does not exist. |
BridgeError
|
mzLib could not read the file. |
Examples:
>>> a = assess("sdrf_cohort.sdrf.tsv")
>>> a.verdict, a.factor_value_varies, a.sample_is_described, a.biological_replicate_varies
('Informative', True, True, True)
>>> a.columns["column_name"][0], a.columns["distinct_values"][0]
('factor value[disease]', 2)
Source code in pkg/python/src/pymzlib/sdrf.py
assess_many ¶
assess_many(paths: Sequence[str | PathLike[str]], *, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> SdrfAssessmentBatch
Assess many SDRF files in one bridge call - the gate for a corpus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
Sequence[str | PathLike[str]]
|
The files, in the order you want them reported. Each may be given once. |
required |
threads
|
int
|
Documents assessed at once. |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds for the whole batch. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
SdrfAssessmentBatch
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
as for :func: |
BridgeError
|
under |
Examples:
>>> batch = assess_many(
... ["sdrf_cohort.sdrf.tsv", "sdrf_skeleton.sdrf.tsv", "PXD000070.sdrf.tsv"]
... )
>>> batch.verdict_counts
{'informative': 1, 'partial': 1, 'skeleton': 1}
>>> [f.verdict for f in batch.files]
['Informative', 'Skeleton', 'Partial']
Source code in pkg/python/src/pymzlib/sdrf.py
samples ¶
Lift each sample's characteristics and factor values out of an SDRF file, ages parsed.
Calls mzLib's SdrfSampleBlock.BySourceName: the sample half of the document (source
name, every characteristics[...], every factor value[...]) per sample, merged over
the sample's rows. Where those rows disagree - one fraction says normal and another
COVID-19 - mzLib names the column and withholds it rather than let the first row win.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to a |
required |
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
SdrfSamples
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank or the file does not exist. |
BridgeError
|
mzLib could not read the file. |
Examples:
>>> s = samples("sdrf_cohort.sdrf.tsv")
>>> s.sample_count, s.conflicts()
(6, [('S6', 'characteristics[disease]')])
>>> for a in s.ages():
... print(a["source_name"], a["value"], a["age_years"], a["age_precision"], a["age_refusal"])
S1 58Y 58 Exact None
S2 40Y-85Y 62.5 Range None
S3 >=90Y 90 LowerBound None
S4 63 None None no_unit
S5 Not available None None reserved_word
S6 40Y-40Y 40 Exact None
Source code in pkg/python/src/pymzlib/sdrf.py
samples_many ¶
samples_many(paths: Sequence[str | PathLike[str]], *, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> SdrfSamplesBatch
Lift the samples of many SDRF files in one bridge call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
Sequence[str | PathLike[str]]
|
The files, in the order you want them reported. Each may be given once. |
required |
threads
|
int
|
Documents read at once. |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds for the whole batch. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
SdrfSamplesBatch
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
as for :func: |
BridgeError
|
under |
Examples:
>>> batch = samples_many(["sdrf_cohort.sdrf.tsv", "sdrf_cohort_partner.sdrf.tsv"])
>>> batch.sample_count, [f.sample_count for f in batch.files]
(8, [6, 2])
Source code in pkg/python/src/pymzlib/sdrf.py
parse_ages ¶
Read characteristics[age] cells into years, refusing anything that would need a guess.
Calls mzLib's SdrfAge.TryParse on each cell. It reads the specification's grammar
(58Y, 30Y6M, 16W), ranges (40Y-85Y, 6-8 weeks), bounds (>=90Y,
<1Y) and unambiguous words (3 year, 4 hour). It refuses a bare number - 63
is 11% of real age cells, and 63 years and 63 days are both plausible in one study - as well as
reserved words and free text. A refused cell has no age; refusal says why.
One bridge call for any number of cells, so pass them all at once rather than looping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cells
|
Sequence[str | None]
|
The cells, e.g. |
required |
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ParsedAges
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
|
Examples:
>>> ages = parse_ages(["58Y", "30Y6M", "40Y-85Y", "40Y-40Y", ">=90Y", "<1Y", "6-8 weeks",
... "63", "not available", "", "about forty"])
>>> ages.parsed_count, ages.cell_count
(7, 11)
>>> for row in ages.records[:5]:
... print(row["cell"], row["years"], row["min_years"], row["max_years"], row["precision"])
58Y 58 58 58 Exact
30Y6M 30.5 30.5 30.5 Exact
40Y-85Y 62.5 40 85 Range
40Y-40Y 40 40 40 Exact
>=90Y 90 90 None LowerBound
>>> ages.columns["refusal"][7:]
['no_unit', 'reserved_word', 'empty', 'unreadable']
Source code in pkg/python/src/pymzlib/sdrf.py
design ¶
design(path: str | PathLike[str], *, condition_columns: Sequence[str] | None = None, searched_files: Sequence[str | PathLike[str]] | None = None, out: str | PathLike[str] | None = None, timeout: float | None = 60) -> SdrfDesign
Read a label-free experimental design out of an SDRF, or every reason it cannot be read.
Calls mzLib's SdrfLabelFreeDesign.Read. It runs every check MetaMorpheus's own design
validator runs and refuses rather than repairs: a factor written not available, two
files claiming the same replicate and fraction, a document with several factor columns and no
declaration - each is a refusal, and all of them are reported at once. It relabels in only two
ways, both recorded in notes: study-wide biological replicate numbers are ranked within each
condition (22 -> 1), and rows for files the search does not read are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to a |
required |
condition_columns
|
Sequence[str] | None
|
The |
None
|
searched_files
|
Sequence[str | PathLike[str]] | None
|
The files the search will read, as paths or bare names. Each must be named
exactly (case and extension) by one SDRF row; rows for other files are dropped and
reported in |
None
|
out
|
str | PathLike[str] | None
|
Also write MetaMorpheus's |
None
|
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
SdrfDesign
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the path is blank or the file does not exist; |
BridgeError
|
mzLib could not parse the SDRF at all, or |
Examples:
A valid two-factor design - 24 runs, 8 conditions of 3 biological replicates:
>>> both = ["factor value[genotype]", "factor value[treatment]"]
>>> d = design("PXD067622.sdrf.tsv", condition_columns=both)
>>> d.is_valid, d.file_count, len(set(d.columns["condition"]))
(True, 24, 8)
>>> run = d.files[0]
>>> run.file_name, run.condition, run.biological_replicate
('20240830_HF_LC3_MAA_RK_12032_CA_DMSO4', 'SPRTN-TurboID CA_DMSO (vehicle)', 0)
A refusal lists every reason at once - here one per run, because the deposit's treatment
is not available:
>>> refused = design("PXD049018.sdrf.tsv", condition_columns=both)
>>> refused.is_valid, len(refused.refusals), refused.file_count
(False, 20, 0)
>>> print(refused.refusals[0])
Line 2 (MSB67868ABand_01.raw): 'factor value[treatment]' is 'not available'. A condition
cannot be built from an unknown factor; fill it in, or leave the column out of the
declared condition columns to pool these rows.
Study-wide replicate numbers are ranked within each condition, and the mapping is kept:
>>> ranked = design("PXD067622_studywide.sdrf.tsv", condition_columns=both)
>>> ranked.is_valid, len(ranked.notes)
(True, 7)
>>> print(ranked.notes[1])
Condition 'SPRTN-TurboID CA_formaldehyde 1 mM, 1 h': biological replicates renumbered
22 -> 1, 23 -> 2, 24 -> 3.
Source code in pkg/python/src/pymzlib/sdrf.py
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 | |
pymzlib.isobaric¶
isobaric ¶
Isobaric labelling kits - TMT, TMTpro, iTRAQ, DiLeu - with every channel's reporter-ion m/z.
An isobaric experiment is read out of the low-m/z reporter ions: one ion per channel, a few
millidaltons apart. Getting a channel's label or its m/z wrong mislabels every sample after it, so
pyMzLib does not keep its own table. :func:kits returns mzLib's::
>>> import pymzlib
>>> tmtpro = pymzlib.isobaric.kits("TMT18")
>>> kit = tmtpro.kits[0]
>>> kit.name, kit.channel_count
('TMT18', 18)
>>> for channel in kit.channels[:3]:
... print(channel.label, round(channel.reporter_ion_mz, 5))
126 126.12773
127N 127.12476
127C 127.13108
Nothing in that table is typed in. mzLib holds only the channel labels. Each m/z is a DI HCD
diagnostic-ion line of the kit's Multiplex Label modification in mzLib's embedded TMT.txt,
plus one proton, sorted ascending and paired with the labels by position. The m/z are therefore
the same ones MetaMorpheus uses to quantify a TMT search.
The kit is looked up the way MetaMorpheus looks it up: by its whole name, case-insensitively,
optionally followed by " on <motif>" - "TMT10", "tmt10", "TMT6-plex",
"iTRAQ-4plex on K". Never by substring, so "TMT10plex" is refused rather than mistaken for a
kit whose name it contains.
ReporterChannel
dataclass
¶
One channel of a kit and the theoretical m/z of its reporter ion.
Attributes:
| Name | Type | Description |
|---|---|---|
kit |
str
|
mzLib's kit name (an |
index |
int
|
0-based position within the kit, ascending with |
label |
str
|
The channel's name as MetaMorpheus spells it - |
reporter_ion_mz |
float
|
Theoretical m/z at charge 1, in m/z (Th): the diagnostic-ion mass
from mzLib's |
mz_min |
float
|
|
mz_max |
float
|
|
Source code in pkg/python/src/pymzlib/isobaric.py
IsobaricKit
dataclass
¶
One kit and its channels, in ascending reporter-ion m/z.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
mzLib's kit name, an |
channel_count |
int
|
How many channels the kit has. |
channels |
list[ReporterChannel]
|
Every channel as a :class: |
Source code in pkg/python/src/pymzlib/isobaric.py
IsobaricKits
dataclass
¶
Bases: _Table
The kits :func:kits returned, as a long table and as objects.
columns maps kit, channel_index, channel_label, reporter_ion_mz, mz_min
and mz_max to one value per (kit, channel) - ready for pandas.DataFrame(result.columns).
:attr:kits groups the same rows by kit.
Attributes:
| Name | Type | Description |
|---|---|---|
kit |
str | None
|
The name you asked for, exactly as given, or |
kit_count |
int
|
Kits listed. |
record_count |
int
|
Channels listed, over every kit; the length of every column. |
absolute_tolerance |
float
|
The half-width, in Da, of each channel's matching window. mzLib reads a reporter intensity as the most intense peak within it. |
column_names |
list[str]
|
The table's columns, in order. |
columns |
dict[str, list[Any]]
|
Column name to one value per channel. |
kit_summaries |
list[dict[str, Any]]
|
The wire's per-kit summaries, |
caveats |
list[str]
|
What the m/z are and are not - read these once. |
Source code in pkg/python/src/pymzlib/isobaric.py
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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | |
channels
property
¶
Every channel as a :class:ReporterChannel, kits in mzLib's order.
kit_named ¶
The listed kit whose :attr:IsobaricKit.name is exactly name.
Raises:
| Type | Description |
|---|---|
UsageError
|
no listed kit has that name. |
Source code in pkg/python/src/pymzlib/isobaric.py
kits ¶
The isobaric kits mzLib can name, with every channel's label and reporter-ion m/z.
Calls mzLib's IsobaricMassTag.TryGetIsobaricMassTag for each IsobaricMassTagType, or for
the one kit resolves to through IsobaricMassTag.TryGetTagType. No file, no network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kit
|
str | None
|
One kit, matched by mzLib's whole-name rule: case-insensitive, optionally followed by
|
None
|
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
IsobaricKits
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
|
Examples:
Every kit mzLib knows:
>>> catalogue = kits()
>>> [(k.name, k.channel_count) for k in catalogue.kits]
[('TMT6', 6), ('TMT10', 10), ('TMT11', 11), ('TMT16', 16), ('TMT18', 18),
('iTRAQ4', 4), ('iTRAQ8', 8), ('diLeu4', 4), ('diLeu12', 12)]
>>> catalogue.absolute_tolerance
0.003
>>> catalogue.kit_named("iTRAQ8").labels
['113', '114', '115', '116', '117', '118', '119', '121']
TMTpro 18-plex, whose top channel sits at 135.15:
>>> tmtpro = kits("TMT18")
>>> last = tmtpro.kits[0].channels[-1]
>>> last.label, round(last.reporter_ion_mz, 4), round(last.mz_max - last.mz_min, 6)
('135N', 135.1516, 0.006)
Source code in pkg/python/src/pymzlib/isobaric.py
pymzlib.proteins¶
proteins ¶
Protein databases: what each protein is, which gene it belongs to, and whether a peptide identifies it.
Questions a search result cannot answer on its own, each answered from the protein database you searched, by mzLib:
What is this accession? :func:read loads a UniProt XML or a FASTA and returns one row per
protein - organism, NCBI taxonomy id, gene names, length, monoisotopic mass - and, on request, its
Gene Ontology terms and Ensembl gene links as long tables::
>>> db = pymzlib.proteins.read(
... ["human_subset.xml", "human_extra.fasta", "mouse_aifm1.fasta"],
... contaminants=["contaminants.fasta"], tables=pymzlib.proteins.TABLES)
>>> db.taxonomy()["Q9Z0X1"], db.organisms()["P02769"]
('10090', 'Bos taurus')
>>> db.go_terms.columns["term_name"][:3]
['cytoplasm', 'cytosol', 'extracellular exosome']
Which gene is it, reproducibly? :func:resolve_genes resolves every protein to a stable
Ensembl gene id, counted against a gene set you supply and pin - an Ensembl GTF for one release -
and says, per protein, how it resolved (resolved, multi_gene, off_primary_only,
not_in_source, ...). Every row carries the sha256 of the database, the GTF and the optional
cross-reference table it was computed from::
>>> genes = pymzlib.proteins.resolve_genes(
... ["human_subset.xml", "human_extra.fasta"], contaminants=["contaminants.fasta"],
... gtf="Homo_sapiens.GRCh38.116.gtf", xref="Homo_sapiens.GRCh38.116.uniprot.tsv")
>>> genes.gene_set.release, genes.gene_set.genome_build, genes.outcome_counts["resolved"]
('116', 'GRCh38.p14', 1)
Does this peptide identify one protein? :func:classify_peptides classifies each peptide as
Unique, SharedWithinGene, SharedAcrossGenes or NotInDatabase, treating I and L as
the same residue, because a mass spectrometer cannot tell them apart::
>>> calls = pymzlib.proteins.classify_peptides(
... ["VGVNGFGR", "LVLNGNPLTLFQER", "ALSEQINIFFDYSGR", "YLYEIAR", "AEFVEVTK", "PEPTIDEK"],
... ["human_subset.xml", "human_extra.fasta"], contaminants=["contaminants.fasta"])
>>> calls.columns["sharing"]
['Unique', 'Unique', 'SharedWithinGene', 'SharedAcrossGenes', 'Unique', 'NotInDatabase']
What does each protein group do, every member kept? :func:annotate_go reads the protein-group
table MetaMorpheus wrote, the UniProt XML it searched and a go.obo you pinned, and returns one row
per (group, GO term) that any member holds - directly or through an ancestor in the ontology -
naming the members that carry it. Consensus and direct-only views are filters on the rows.
:func:update_go is the one function that fetches a go.obo; :func:annotate_go never does::
>>> go = pymzlib.proteins.annotate_go(
... "PXD036557_AllQuantifiedProteinGroups.tsv", "pxd036557_proteins.xml",
... go_obo="go-pxd036557.obo", category_map="organelle_map.tsv")
>>> go.group_count, go.row_count, go.header["status_contaminant"]
(5, 563, '1')
These examples are the calls that recorded the payloads in pyMzLib's test fixtures, over the small
databases in pkg/python/tests/fixtures/proteins/. The GO example's table is a real MetaMorpheus
1.1.11 search (PXD036557).
:func:read, :func:resolve_genes and :func:classify_peptides take one database or many.
Pass a list and they are read in one bridge call, in order; threads says how many are read at
once (default 1), and the answer is identical at any value.
Mark contaminant databases with contaminants= - it changes answers: a contaminant is never mapped
to a gene, and a peptide it shares with a target is shared.
What these functions will not tell you, and say so instead:
- A FASTA knows no GO terms and no Ensembl genes. Its headers carry organism (
OS=), taxonomy (OX=) and gene name (GN=) and nothing else, so it contributes nogo_termsorensembl_genesrows and :func:resolve_genescalls every FASTA proteinnot_in_source. That is the format's silence, not a biological absence, and each result says so in :attr:DatabaseFile.absent_fieldsandcaveats. Read the UniProt XML of the same proteome. - No decoys are generated and no variants are expanded. A database is read as written. A decoy
already in the file (an accession starting
DECOY) is kept and flaggedis_decoy. A UniProt XML that records a genotype still has those variants applied by mzLib, which renames the accession (P38936_C117Y); the file's caveats say how many. - Masses are of the unmodified sequence as written - the precursor, initiator methionine and signal peptide included - so they are not the mass of the mature protein.
Wire verbs: proteins read, genes resolve, proteins classify-peptides,
proteins annotate-go and proteins update-go; their language-neutral specs live in the bridge
repository under design/verbs/.
FileError
dataclass
¶
Why one database could not be read, under on_error="skip".
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
|
type |
str
|
The error type as the bridge classified it - |
message |
str
|
What went wrong, naming the file. |
Source code in pkg/python/src/pymzlib/proteins.py
DatabaseFile
dataclass
¶
What happened to one input database.
One per input, in input order, whether it was read or not - so a result for many databases always says which of them contributed.
Attributes:
| Name | Type | Description |
|---|---|---|
source_index |
int
|
Position in the input: databases first, then |
path |
str
|
The absolute path. |
file_type |
str | None
|
|
reader |
str | None
|
The mzLib loader used, e.g. |
contaminant |
bool
|
Whether this database was loaded as contaminants. |
protein_count |
int
|
Proteins mzLib loaded from it, before any accession filter. |
decoy_count |
int
|
Of those, how many the file itself marks as decoys (accession starts
|
record_count |
int
|
Rows this database contributed to the main table. For :func: |
search_database_sha256 |
str | None
|
For :func: |
caveats |
list[str]
|
What this file cannot tell you, or what mzLib did to it: a FASTA has no GO or Ensembl source; genotype variants were applied; FASTA lines the loader skipped. |
absent_fields |
list[str]
|
Tables and columns this format has no source for, so that an empty value
reads as "this file cannot say" and never as "there is none". For a FASTA:
|
error |
FileError | None
|
|
Source code in pkg/python/src/pymzlib/proteins.py
Table
dataclass
¶
Bases: _Table
A long table: one row per record, column-major.
Attributes:
| Name | Type | Description |
|---|---|---|
row_count |
int
|
Rows in the table. |
column_names |
list[str]
|
Column order. |
columns |
dict[str, list[Any]]
|
Column name -> list of values, all the same length. Hand it straight to
|
Source code in pkg/python/src/pymzlib/proteins.py
ProteinDatabase
dataclass
¶
Bases: _Table
What :func:read returns: the proteins, and the long tables asked for.
The proteins table (:attr:columns) has one row per protein, in database order:
====================== ============= ======================================================
column type / unit meaning; None means
====================== ============= ======================================================
source_index int which input (:attr:files) the row came from
source_path str that input's absolute path
accession str as the database wrote it (P04406, Q13409-2)
name str entry name (G3P_HUMAN); None: not recorded
full_name str protein name; None: not recorded
organism str OS= / <organism> scientific name;
None: not recorded
ncbi_taxonomy_id str NCBI taxon ("9606") from XML or FASTA OX=;
None: the entry records none. Kept a string: it
is an identifier, not a quantity.
primary_gene_name str the primary gene name (GN=); None: none given
gene_names list[str] every gene name the entry gives, primary first,
synonyms, ORF and locus names after; may be empty
length int, residues sequence length
monoisotopic_mass float, Da unmodified sequence plus one water; None: the
sequence holds a letter with no defined mass (X, B,
Z, J)
is_contaminant bool loaded from a contaminants= database
is_decoy bool the file marks it a decoy (DECOY prefix)
is_entrapment bool mzLib's entrapment flag (accession contains
Random)
ensembl_gene_ids list[str] distinct stable Ensembl gene ids, ordinal order;
empty for FASTA (see absent_fields)
sequence str only with sequences=True
====================== ============= ======================================================
Attributes:
| Name | Type | Description |
|---|---|---|
file_count |
int
|
Database files given. |
read_count |
int
|
Database files read. |
failed_count |
int
|
Database files that failed ( |
record_count |
int
|
Proteins that passed the accession filter - the rows of the |
tables |
list[str]
|
The tables returned, in :data: |
accession_filter_count |
int | None
|
Distinct accessions in the filter, or |
accessions_not_found |
list[str] | None
|
Filter accessions no database contained, in the order given; |
caveats |
list[str]
|
Traps in this result as a whole, e.g. proteins with no computable mass. |
files |
list[DatabaseFile]
|
One :class: |
column_names |
list[str] | None
|
The |
columns |
dict[str, list[Any]] | None
|
The |
go_terms |
Table | None
|
One row per (protein, GO term), or |
ensembl_genes |
Table | None
|
One row per (protein, Ensembl transcript), or |
Source code in pkg/python/src/pymzlib/proteins.py
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 411 412 413 414 | |
taxonomy ¶
Accession -> NCBI taxonomy id, for every protein in the table.
Raises:
| Type | Description |
|---|---|
UsageError
|
the |
Examples:
>>> db = read(["human_subset.xml", "human_extra.fasta", "mouse_aifm1.fasta"],
... contaminants=["contaminants.fasta"], tables=TABLES)
>>> db.taxonomy()["Q9Z0X1"]
'10090'
Source code in pkg/python/src/pymzlib/proteins.py
organisms ¶
Accession -> organism name, for every protein in the table.
Raises:
| Type | Description |
|---|---|
UsageError
|
the |
Source code in pkg/python/src/pymzlib/proteins.py
GeneSet
dataclass
¶
The Ensembl gene set every resolution was counted against, and where it came from.
Attributes:
| Name | Type | Description |
|---|---|---|
source_file_name |
str
|
The GTF's file name. With |
sha256 |
str
|
Lower-case hex sha256 of the GTF's bytes as read - the compressed bytes for a
|
release |
str | None
|
The Ensembl release parsed from the file name ( |
genome_build |
str | None
|
The |
genebuild_last_updated |
str | None
|
The |
gene_count |
int
|
Genes in the set. |
Source code in pkg/python/src/pymzlib/proteins.py
XrefTable
dataclass
¶
Ensembl's own accession-to-gene cross-references, when xref= was given.
Attributes:
| Name | Type | Description |
|---|---|---|
source_file_name |
str
|
The file's name (e.g. |
sha256 |
str
|
Lower-case hex sha256 of the file's bytes as read. |
release |
str | None
|
The Ensembl release from the file name; |
accession_count |
int
|
Distinct accessions the table links. |
Source code in pkg/python/src/pymzlib/proteins.py
GeneResolutions
dataclass
¶
Bases: _Table
What :func:resolve_genes returns: one row per (protein, gene), or one outcome row per
protein with no gene. Never a |-joined cell, and never a pick among several genes.
The column names after source_index and source_path are mzLib's own
GeneResolutionTsv schema, so this table and one written by mzLib's TSV writer mean the same:
========================== ========= ===========================================================
column type meaning; None means
========================== ========= ===========================================================
accession str as the search reported it, variant suffix and all
entry_accession str the UniProt entry / unversioned RefSeq; verbatim otherwise
isoform int UniProt isoform number; None: no -N suffix
namespace str uniprot, refseq or unrecognized
outcome str one of :data:OUTCOMES
n_genes int genes on the gene set's assembly (0, 1, or more)
gene_id str stable id (ENSG...); None: no gene on the assembly
versioned_gene_id str the id as the database wrote it; None: no gene
gene_symbol str the release's symbol (display only); None: no gene,
or the GTF gives it no name
gene_biotype str the release's biotype; None: no gene
off_primary_genes int linked genes outside the set (ALT haplotypes, patches):
dropped from n_genes, but counted here
uniprot_gene_name str the database's own primary gene name, a label;
None: none
source str search_database_dbreference, or ensembl_xref for a
gene only Ensembl links (adds an answer, never changes the
outcome)
search_database_sha256 str sha256 of the decompressed database
gene_set_release str Ensembl release; None: the GTF name carries none
gene_set_sha256 str sha256 of the GTF
ensembl_xref_agrees bool whether Ensembl's xref links this pair; None: no gene on
the row, or no xref= given (unknown, not false)
ensembl_xref_info_type str Ensembl's evidence (DIRECT, SEQUENCE_MATCH,
INFERRED_PAIR); None: no xref link
ensembl_xref_sha256 str sha256 of the xref file; None: no xref=
========================== ========= ===========================================================
Attributes:
| Name | Type | Description |
|---|---|---|
file_count |
int
|
Database files given. |
read_count |
int
|
Database files read. |
failed_count |
int
|
Database files that failed ( |
protein_count |
int
|
Proteins resolved. |
record_count |
int
|
Rows in the table: at least one per protein, one per gene for
|
gene_set |
GeneSet
|
The gene set and its provenance. |
xref |
XrefTable | None
|
The xref table and its provenance, or |
outcome_counts |
dict[str, int]
|
Outcome -> number of proteins with it. Every key in :data: |
caveats |
list[str]
|
Traps in this result: FASTA proteins, a GTF with no release in its name, no xref. |
files |
list[DatabaseFile]
|
One :class: |
column_names |
list[str]
|
Column order. |
columns |
dict[str, list[Any]]
|
Column name -> list of values. |
Source code in pkg/python/src/pymzlib/proteins.py
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 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | |
PeptideClassification
dataclass
¶
Bases: _Table
What :func:classify_peptides returns: one row per peptide, in the order given.
==================== ========= ===============================================================
column type meaning
==================== ========= ===============================================================
peptide str exactly as given - not I/L-folded
sharing str :data:UNIQUE, :data:SHARED_WITHIN_GENE,
:data:SHARED_ACROSS_GENES or :data:NOT_IN_DATABASE
accession_count int target proteins containing it
accessions list[str] those proteins, distinct, ordinal order; empty when not found
shared_gene_keys list[str] the gene keys common to all of them, e.g.
"ensembl:ENSG00000111640", "gene:Homo sapiens:GAPDH",
"entry:P04406". Empty for NotInDatabase and
SharedAcrossGenes
==================== ========= ===============================================================
Attributes:
| Name | Type | Description |
|---|---|---|
file_count |
int
|
Database files searched. |
peptide_count |
int
|
Rows: peptides, one per input peptide, duplicates included. |
target_protein_count |
int
|
Proteins searched. Contaminants count: they are real sequences in the search space. |
decoy_proteins_ignored |
int
|
Decoy proteins in the databases, which are never searched. |
i_and_l_equivalent |
bool
|
Always |
sharing_counts |
dict[str, int]
|
Class -> peptides in it; every class present, zeros included. |
files |
list[DatabaseFile]
|
One :class: |
column_names |
list[str]
|
Column order. |
columns |
dict[str, list[Any]]
|
Column name -> list of values. |
Source code in pkg/python/src/pymzlib/proteins.py
sharing_of ¶
Peptide -> sharing class. A peptide given twice appears once (it classifies the same).
Examples:
>>> calls = classify_peptides(
... ["VGVNGFGR", "LVLNGNPLTLFQER", "ALSEQINIFFDYSGR", "YLYEIAR", "AEFVEVTK", "PEPTIDEK"],
... ["human_subset.xml", "human_extra.fasta"], contaminants=["contaminants.fasta"])
>>> calls.sharing_of()["YLYEIAR"]
'SharedAcrossGenes'
Source code in pkg/python/src/pymzlib/proteins.py
GoRelease
dataclass
¶
The go.obo a result was computed against. Record it with your results.
Attributes:
| Name | Type | Description |
|---|---|---|
source_file_name |
str
|
The file name read. |
sha256 |
str
|
Lower-case hex sha256 of the file's bytes. This, not the release, is what proves two runs used the same ontology. |
release |
str | None
|
The file's |
term_count |
int
|
Terms in the file, obsolete terms included (alternative ids are not counted). |
Source code in pkg/python/src/pymzlib/proteins.py
AnnotationDatabase
dataclass
¶
The protein database whose GO terms annotated the groups.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path. |
file_type |
str | None
|
|
reader |
str | None
|
The mzLib loader used, |
protein_count |
int
|
Entries loaded, as written (no decoys generated, no variants applied). |
sha256 |
str
|
Lower-case hex sha256 of the decompressed database, so |
caveats |
list[str]
|
What mzLib did to the file while loading it, e.g. genotype variants applied. |
Source code in pkg/python/src/pymzlib/proteins.py
WrittenTable
dataclass
¶
A file :func:annotate_go wrote, when asked to.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The absolute path written. |
row_count |
int | None
|
Rows written: the whole table, never the |
Source code in pkg/python/src/pymzlib/proteins.py
GoCategories
dataclass
¶
Bases: _Table
Your category map applied to the annotated terms: one row per (term, category, subcategory).
A term belongs to a category when one of that category's anchors is the term itself or one of
its ancestors. A term under no anchor has no row, so absence means "outside your map". Join
to :class:GoAnnotations on go_id: both tables come from the same go.obo release.
=============== ===== ===================================================================
column type meaning; None means
=============== ===== ===================================================================
go_id str an annotated term at or below one of the map's anchors
category str the category label, as your map writes it
subcategory str "category:subcategory", the most specific anchor within the
category; None: the term reaches only the category's own anchor
=============== ===== ===================================================================
Attributes:
| Name | Type | Description |
|---|---|---|
map_name |
str
|
The map's declared |
map_version |
str
|
The map's declared |
source_file_name |
str
|
The map file read. |
sha256 |
str
|
Lower-case hex sha256 of the map file. A version is a claim; the hash is proof. |
anchor_count |
int
|
Rows (anchors) in the map. |
row_count |
int
|
Rows in the table. |
column_names |
list[str]
|
Column order. |
columns |
dict[str, list[Any]]
|
Column name -> list of values. |
Source code in pkg/python/src/pymzlib/proteins.py
GoAnnotations
dataclass
¶
Bases: _Table
What :func:annotate_go returns: one row per (protein group, GO term) that any member of
the group holds, directly or through an ancestor.
No member of a group is privileged - MetaMorpheus never picks a leading protein - so the table
is the union, and every row says which members carry its term. The views people usually want
are filters you apply: consensus is n_with == n_members; direct annotations only is
propagated is False; leave out isoform inheritance is inherited is False.
The column names are mzLib's own GoAnnotationTsv schema, in its order, so this table and
the file written by out= (or by mzLib inside a search) mean the same thing:
========================= ========== ===========================================================
column type meaning; None means
========================= ========== ===========================================================
protein_group str the group, as MetaMorpheus named it (P0C0S5|Q71UI9)
accession_used list[str] members carrying the term, directly or by propagation
accession_direct list[str] of those, members annotated to this exact term
accession_inherited list[str] of those, members whose terms were borrowed: an isoform
(P04406-2) or sequence variant (P04406_A20T) absent
from the database takes its entry's terms
go_id str the term's primary id; None: a term-less row
go_name str the term's name; None: a term-less row
aspect str biological_process, cellular_component,
molecular_function or unknown; None: term-less
evidence list[str] evidence codes (ECO) pooled over the carrying members
evidence_by_member dict member -> its own evidence codes for this term
inherited bool every carrying member's terms were borrowed;
None: a term-less row
propagated bool no member is annotated to this exact term - it is implied
by a more specific one; None: a term-less row
n_members int members in the group
n_with int members carrying the term (0 on a term-less row)
entrapment_members list[str] the group's entrapment members, on every row of the group
annotation_status str one of :data:ANNOTATION_STATUSES
q_value float the group's q-value from the table (never filtered on)
go_release str the go.obo data-version; None: the file has none
go_obo_sha256 str sha256 of the go.obo
annotation_db_sha256 str sha256 of the decompressed annotation database
========================= ========== ===========================================================
Attributes:
| Name | Type | Description |
|---|---|---|
groups_file |
str
|
The absolute path of the protein-group table read. |
groups_file_sha256 |
str
|
Lower-case hex sha256 of that table, also in :attr: |
table_row_count |
int
|
Rows in the table, decoys included. |
decoy_group_count |
int
|
Of those, decoy groups, which are skipped: decoys carry no GO. |
group_count |
int
|
Groups annotated: every non-decoy group, contaminants included, each once even if MetaMorpheus wrote it twice. |
annotation_database |
AnnotationDatabase
|
The database the terms came from. |
go |
GoRelease
|
The ontology release the terms were propagated against. |
skip_unknown_go_ids |
bool
|
Whether |
unresolved_go_ids |
list[str]
|
GO ids the database cites that the ontology release lacks, dropped
because |
header |
dict[str, str]
|
mzLib's |
row_count |
int
|
Rows in the whole table. |
returned_count |
int
|
Rows returned here (the |
offset |
int
|
Rows skipped before the window: the |
truncated |
bool
|
True when rows were left out of :attr: |
caveats |
list[str]
|
What this result cannot tell you: ids dropped from the database, a go.obo with no release, what mzLib did loading the database. |
written |
WrittenTable | None
|
Where the whole table was written, when |
categories |
GoCategories | None
|
Your category map applied to these terms, when |
categories_written |
WrittenTable | None
|
Where the category table was written, when |
column_names |
list[str]
|
Column order: mzLib's schema. |
columns |
dict[str, list[Any]]
|
Column name -> list of values, for the returned window. |
Source code in pkg/python/src/pymzlib/proteins.py
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 | |
GoUpdate
dataclass
¶
What :func:update_go returns: which go.obo is now on disk, and whether it changed.
Attributes:
| Name | Type | Description |
|---|---|---|
go_obo_file |
str
|
The absolute path written. |
url |
str
|
Where it was fetched from: GO's PURL, which always serves the current release. |
existed_before |
bool
|
Whether a file was already at the path. |
previous_sha256 |
str | None
|
That file's sha256; |
changed |
bool
|
Whether the file on disk is now different. When it is and a file existed, the old
one was kept beside it as |
go |
GoRelease
|
The release now at the path. |
caveats |
list[str]
|
The backup kept, or a file with no |
Source code in pkg/python/src/pymzlib/proteins.py
read ¶
read(databases: _PathLike | Iterable[_PathLike], *, tables: Sequence[str] = ('proteins',), accessions: Iterable[str] | None = None, contaminants: _PathLike | Iterable[_PathLike] | None = None, sequences: bool = False, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> ProteinDatabase
Read protein databases: one row per protein, and GO and Ensembl tables on request.
Loads each database with mzLib's ProteinDbLoader, exactly as a search would but with no
decoys generated. A UniProt XML carries everything; a FASTA carries organism, taxon (OX=)
and gene name (GN=) only - see :attr:DatabaseFile.absent_fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
databases
|
_PathLike | Iterable[_PathLike]
|
A UniProt XML ( |
required |
tables
|
Sequence[str]
|
Which tables to return, from :data: |
('proteins',)
|
accessions
|
Iterable[str] | None
|
Keep only proteins whose accession is one of these, exact match. Applies to
every table. Misses are listed in :attr: |
None
|
contaminants
|
_PathLike | Iterable[_PathLike] | None
|
Databases to load as contaminants; |
None
|
sequences
|
bool
|
Add a |
False
|
threads
|
int
|
Databases read at once. Default 1; |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ProteinDatabase
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
no database, a blank or repeated path, an unknown table, a bad |
BridgeError
|
mzLib could not parse a database (under |
Examples:
>>> db = read(["human_subset.xml", "human_extra.fasta", "mouse_aifm1.fasta"],
... contaminants=["contaminants.fasta"], tables=TABLES)
>>> db.record_count, db.go_terms.row_count, db.ensembl_genes.row_count
(8, 47, 6)
>>> db.files[1].file_type, db.files[1].absent_fields
('Fasta', ['go_terms', 'ensembl_genes', 'ensembl_gene_ids'])
Source code in pkg/python/src/pymzlib/proteins.py
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 | |
resolve_genes ¶
resolve_genes(databases: _PathLike | Iterable[_PathLike], *, gtf: _PathLike | None = None, gene_set: _PathLike | None = None, xref: _PathLike | None = None, contaminants: _PathLike | Iterable[_PathLike] | None = None, threads: int = 1, on_error: str = 'fail', timeout: float | None = None) -> GeneResolutions
Resolve every protein to stable Ensembl gene ids, against a gene set you pin.
Wraps mzLib's EnsemblGeneResolver. The gene links come from the database itself (UniProt's
<dbReference type="Ensembl">), and each is counted against the gene set you pass: a gene
in the set counts; a gene outside it (an ALT haplotype, a patch) is dropped from n_genes but
counted in off_primary_genes, and a protein with only such genes is off_primary_only.
You supply the gene set, and you should pin it. Gene ids, versions, symbols and the very
set of genes on the primary assembly change between Ensembl releases, so a resolution means
something only relative to one release. Use Ensembl's primary-assembly GTF (
Species.Assembly.Release.gtf.gz, not the chr_patch_hapl_scaff one): counting ALT
haplotypes as separate genes made human release 116 look 6.99% multi-gene when it is 0.36%.
Keep Ensembl's file name so the release is recorded, and record :attr:GeneSet.sha256 with your
results. Nothing is downloaded or defaulted here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
databases
|
_PathLike | Iterable[_PathLike]
|
The search database(s), UniProt XML for real answers. A FASTA carries no gene
links, so every FASTA protein is |
required |
gtf
|
_PathLike | None
|
An Ensembl GTF, plain or |
None
|
gene_set
|
_PathLike | None
|
Instead of |
None
|
xref
|
_PathLike | None
|
Optional. Ensembl's |
None
|
contaminants
|
_PathLike | Iterable[_PathLike] | None
|
Databases to load as contaminants. Their proteins are
|
None
|
threads
|
int
|
Databases read at once. Default 1; |
1
|
on_error
|
str
|
|
'fail'
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
GeneResolutions
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
neither or both of |
BridgeError
|
a GTF gene row without |
Examples:
>>> genes = resolve_genes(
... ["human_subset.xml", "human_extra.fasta"], contaminants=["contaminants.fasta"],
... gtf="Homo_sapiens.GRCh38.116.gtf", xref="Homo_sapiens.GRCh38.116.uniprot.tsv")
>>> genes.gene_set.release, genes.gene_set.genome_build
('116', 'GRCh38.p14')
>>> genes.outcome_counts["contaminant_not_mapped"]
1
Source code in pkg/python/src/pymzlib/proteins.py
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 | |
classify_peptides ¶
classify_peptides(peptides: Iterable[str], databases: _PathLike | Iterable[_PathLike], *, contaminants: _PathLike | Iterable[_PathLike] | None = None, threads: int = 1, timeout: float | None = None) -> PeptideClassification
Classify peptides by how widely they are shared across the databases, with I = L.
Wraps mzLib's PeptideUniquenessClassifier.Classify. A protein contains a peptide when its
sequence contains it anywhere, whatever the protease - deliberately conservative, so a
peptide called Unique cannot be explained by another entry at a site the search's cleavage
rules happened to skip. I and L are the same residue throughout: LVLNGNPLTLFQER finds
GAPDH's LVINGNPITIFQER.
Unique: every protein containing it has the same sequence (identical entries under two accessions count as one; both are listed).SharedWithinGene: several distinct sequences, all sharing a gene - isoforms. The peptide supports the gene, not an isoform.SharedAcrossGenes: sequences with no gene in common.NotInDatabase: no target protein contains it.
Two proteins share a gene when they share any key: an Ensembl gene id, organism plus primary
gene name (so human and bovine ALB stay apart), or the UniProt entry (so P12345-2 meets
P12345). Decoys are ignored; contaminants are included, because they are real sequences in
the search space.
Every database is part of one search space, so there is no on_error="skip": dropping a
database that failed to load would report the peptides it contains as unique.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
peptides
|
Iterable[str]
|
Unmodified base sequences, upper case ( |
required |
databases
|
_PathLike | Iterable[_PathLike]
|
The search database(s): UniProt XML or FASTA, optionally gzipped. |
required |
contaminants
|
_PathLike | Iterable[_PathLike] | None
|
Contaminant databases searched alongside. |
None
|
threads
|
int
|
Databases read at once (the classification itself is one pass). Default 1;
|
1
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
PeptideClassification
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
no peptides, a blank one, one that is not upper-case A-Z (from mzLib, naming
it), or any database problem :func: |
BridgeError
|
mzLib could not parse a database. |
Examples:
>>> calls = classify_peptides(
... ["VGVNGFGR", "LVLNGNPLTLFQER", "ALSEQINIFFDYSGR", "YLYEIAR", "AEFVEVTK", "PEPTIDEK"],
... ["human_subset.xml", "human_extra.fasta"], contaminants=["contaminants.fasta"])
>>> calls.records[3]["peptide"], calls.records[3]["sharing"], calls.records[3]["accessions"]
('YLYEIAR', 'SharedAcrossGenes', ['P02768', 'P02769'])
Source code in pkg/python/src/pymzlib/proteins.py
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 | |
annotate_go ¶
annotate_go(groups: _PathLike, database: _PathLike, *, go_obo: _PathLike, category_map: _PathLike | None = None, skip_unknown_go_ids: bool = False, out: _PathLike | None = None, categories_out: _PathLike | None = None, limit: int | None = None, offset: int = 0, timeout: float | None = None) -> GoAnnotations
Annotate MetaMorpheus protein groups with Gene Ontology terms, keeping every member.
Wraps mzLib's GoGroupAnnotator over a stored protein-group table
(ProteinGroupFromTsv.ToGoAnnotationGroups). For each group it returns one row per GO term
that any member holds - directly, or by propagation up is_a and part_of - and each
row names the members that carry it. Nothing is collapsed: the union, the consensus and the
direct-only views are filters on the rows (see :class:GoAnnotations).
Every non-decoy group gets at least one row. A group with no term gets a single row whose
annotation_status says why: no_go_terms (its members have none), no_entry (a member
is not in the database - annotate against the database the search used), or contaminant.
Pin the ontology. Terms and their ancestors change between GO releases, so a result means
something only relative to one go.obo. This reads the file you name and never downloads one;
fetch a release on purpose with :func:update_go, keep the file, and record
:attr:GoAnnotations.go (its sha256) with your results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
groups
|
_PathLike
|
A MetaMorpheus protein-group table: |
required |
database
|
_PathLike
|
The UniProt XML ( |
required |
go_obo
|
_PathLike
|
A go.obo file. It must exist; nothing is fetched. |
required |
category_map
|
_PathLike | None
|
Optional. Your own term-to-category map in mzLib's format
( |
None
|
skip_unknown_go_ids
|
bool
|
|
False
|
out
|
_PathLike | None
|
Write the whole table here with mzLib's own |
None
|
categories_out
|
_PathLike | None
|
Write the category table here with mzLib's |
None
|
limit
|
int | None
|
At most this many rows (rows, not groups) in :attr: |
None
|
offset
|
int
|
Rows to skip before the window. Default 0. |
0
|
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
GoAnnotations
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
a missing groups table, database, go.obo or category map; a FASTA database;
an |
BridgeError
|
the database cites GO ids the release lacks ( |
Examples:
>>> go = annotate_go("PXD036557_AllQuantifiedProteinGroups.tsv", "pxd036557_proteins.xml",
... go_obo="go-pxd036557.obo", category_map="organelle_map.tsv")
>>> go.group_count, go.row_count, go.go.release
(5, 563, 'releases/2026-07-26')
>>> go.header["status_annotated"], go.header["status_contaminant"]
('4', '1')
>>> histones = [r for r in go.records if r["protein_group"] == "P0C0S5|Q71UI9"]
>>> len(histones), sum(r["n_with"] == r["n_members"] for r in histones)
(106, 57)
Source code in pkg/python/src/pymzlib/proteins.py
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 | |
update_go ¶
Download the current Gene Ontology release to go_obo, on purpose.
Wraps mzLib's Loaders.UpdateGeneOntology. The whole go.obo (about 37 MB) is streamed from
GO's PURL, which always serves the current release. When a file is already at the path, it
is kept beside the new one as go.obo.<yyyyMMdd-HHmmss-fff> if the download differs, and left
alone if it is the same, so earlier runs stay reproducible. A failed download leaves any
existing file untouched.
This is the only function in pyMzLib that fetches go.obo. :func:annotate_go never does, so
the release a result was computed against is always a file you chose to keep.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
go_obo
|
_PathLike
|
Where to write, e.g. |
required |
timeout
|
float | None
|
Seconds to allow. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
GoUpdate
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
the folder does not exist. |
BridgeError
|
GO's server is unreachable or answered with an error. |
Examples:
>>> update = update_go("go.obo")
>>> update.go.release, update.go.term_count, update.changed
('releases/2026-07-26', 48340, True)
Source code in pkg/python/src/pymzlib/proteins.py
pymzlib.stats¶
stats ¶
Differential abundance with no R: limma's moderated t-test, Benjamini-Hochberg, and random-effects meta-analysis, computed by mzLib.
Three questions, each answered by mzLib's StatisticalModels (mzLib #1341 and #1357):
========================================================== ===================== =============================================
You want to know Call mzLib computes it with
========================================================== ===================== =============================================
Which features change with a coefficient, and how surely? :func:fit LinearModel.Fit + EmpiricalBayes.Moderate
Which of these p-values survive a false discovery rate? :func:adjust MultipleTesting.BenjaminiHochberg
What is one feature's effect, pooled across studies? :func:meta RandomEffectsMeta.Pool (DerSimonian-Laird)
========================================================== ===================== =============================================
It is limma, checked. :func:fit is limma's lmFit followed by eBayes(legacy = TRUE)
(Smyth 2004), and mzLib holds it to limma 3.68.5 to 1e-8 relative on limma's own reference output.
pyMzLib ships that reference - limma's input, and limma's own eBayes output for it - so you
can run the comparison yourself::
>>> fit = pymzlib.stats.fit("limma_reference_responses.tsv", "limma_reference_design.tsv",
... ["age_decades"])
>>> import csv
>>> with open("limma_ebayes_notrend.tsv", newline="") as fh:
... limma = list(csv.DictReader(fh, delimiter="\t"))
>>> def worst(ours, theirs):
... return max(abs(a - float(b)) / abs(float(b)) for a, b in zip(ours, theirs))
>>> worst(fit.columns["t"], [row["t_age"] for row in limma]) < 1e-8
True
>>> worst(fit.columns["bh_adjusted"], [row["bh_age"] for row in limma]) < 1e-8
True
>>> fit.feature_count, fit.residual_df_differ
(400, True)
Every one of the 400 moderated t-statistics and adjusted p-values agrees with limma to better than one part in 10^8.
What it is not. It is limma's legacy estimator. When features have different residual
degrees of freedom - which omitting missing values causes, so in most label-free data - limma 3.61
and later default to a different prior estimator, and :attr:ModeratedFit.residual_df_differ
says when your input is such a case. robust = TRUE, contrasts, the B-statistic and observation
weights are not implemented; write a contrast as its own design column instead.
Your data, as files. :func:fit reads two tab-separated files - a feature-by-sample table of
(already log-transformed) responses, and a sample-by-coefficient design - because that is the
shape a table library writes (df.to_csv(path, sep="\t")) and it keeps a 10,000-protein table
off the command line. A blank, NA or NaN cell is missing and is left out of that feature's
fit, never imputed. A 0 is an observation, as in mzLib, so blank out any 0 that means "not
measured".
Wire verbs: stats fit, stats adjust and stats meta; their language-neutral specs live in
the bridge repository under design/verbs/.
VariancePrior
dataclass
¶
The fitted prior of the per-feature residual variances, s²_g ~ s0² · χ²(d0)/d0.
It depends only on the fit, never on which coefficient is tested, so one prior serves every
coefficient in a :class:ModeratedFit.
Attributes:
| Name | Type | Description |
|---|---|---|
df |
float | None
|
Prior degrees of freedom d0, or |
df_infinite |
bool
|
|
trended |
bool
|
Whether s0² varies with each feature's average response ( |
spline_basis_count |
int
|
Basis functions the trend spline used, intercept included; 1 without a trend. |
scale |
float | None
|
s0², the prior variance, in squared response units; |
Source code in pkg/python/src/pymzlib/stats.py
ModeratedFit
dataclass
¶
Bases: _Table
What :func:fit returns: one row per (tested coefficient, feature), with limma's moderated t.
columns holds one block of feature_count rows per tested coefficient, in the order you
named them, each block in the responses file's feature order:
====================== ============================== ====================================================
column unit meaning; None means
====================== ============================== ====================================================
feature - the id in the responses file's first column
coefficient - the coefficient this row tests
status - one of :data:FIT_STATUSES
estimate response units per coefficient least-squares coefficient: a log2 fold change
unit for a 0/1 group column on log2 intensities;
None = not fitted
standard_error response units per coefficient moderated standard error; None = not fitted
unit
t standard errors moderated t; None = not fitted
df_total degrees of freedom df_residual + prior df, capped at the pooled df
p_value fraction (0 to 1) two-sided; None = not fitted
bh_adjusted fraction (0 to 1) Benjamini-Hochberg over this coefficient's fitted
features; not a target-decoy q-value
posterior_variance squared response units the moderated residual variance
prior_variance squared response units s0² for this feature
sigma response units residual standard deviation before moderation
df_residual - observed samples minus coefficients
observed samples samples with a finite response
average_response response units the covariate trend=True fits on
====================== ============================== ====================================================
Attributes:
| Name | Type | Description |
|---|---|---|
responses_file |
str
|
Absolute path of the responses table. |
design_file |
str
|
Absolute path of the design table. |
feature_count |
int
|
Feature rows read (features). |
sample_count |
int
|
Sample columns read (samples). |
sample_names |
list[str]
|
In the responses header's order. |
coefficient_names |
list[str]
|
Every design column, in order: the model always fits all of them. |
tested_coefficients |
list[str]
|
The coefficients you asked to test, in order. |
trend |
bool
|
Whether the prior variance was allowed to trend with average response. |
threads |
int
|
The thread count used (threads); the answer is identical at any count. |
missing_count |
int
|
Response cells that were blank, NA or NaN (cells), left out of their fits. |
zero_count |
int
|
Response cells that are exactly 0 (cells), fitted as observations. |
status_counts |
dict[str, int]
|
Features per status (features), keyed by :data: |
residual_df_differ |
bool
|
|
prior |
VariancePrior
|
The fitted :class: |
row_count |
int
|
Rows in the table (rows): |
column_names |
list[str]
|
The table's columns, in order. |
columns |
dict[str, list[Any]]
|
Column name -> list of values - the shape |
caveats |
list[str]
|
What the numbers are and are not, including any that apply to this input
(unfitted features, zeros, |
Source code in pkg/python/src/pymzlib/stats.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 239 240 241 242 243 244 245 246 247 248 | |
rows ¶
The rows testing one coefficient, as dicts, in feature order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coefficient
|
str
|
One of :attr: |
required |
Raises:
| Type | Description |
|---|---|
UsageError
|
|
Source code in pkg/python/src/pymzlib/stats.py
Adjusted
dataclass
¶
Bases: _Table
What :func:adjust returns: one row per p-value given, in input order.
columns["p_value"] is each p-value as read (a fraction, 0 to 1), None where you passed
None or NaN; columns["bh_adjusted"] is its Benjamini-Hochberg adjusted value (a
fraction, 0 to 1), None for an untested entry.
Attributes:
| Name | Type | Description |
|---|---|---|
line_count |
int
|
Values given (lines); the length of every column. |
tested_count |
int
|
m, the finite p-values the adjustment is over (p-values). |
row_count |
int
|
Rows in the table (rows), equal to |
column_names |
list[str]
|
|
columns |
dict[str, list[Any]]
|
Column name -> one value per input. |
caveats |
list[str]
|
What the adjustment is and is not. |
Source code in pkg/python/src/pymzlib/stats.py
bh_adjusted
property
¶
The adjusted values alone, aligned with the input (None = not tested).
MetaAnalysis
dataclass
¶
Bases: _Table
What :func:meta returns: one pooled row per feature, in order of first appearance.
=========================== ==================================== ===========================================
column unit meaning; None means
=========================== ==================================== ===========================================
feature - as given
studies studies studies pooled
estimate units of the study estimates random-effects pooled estimate
standard_error units of the study estimates its standard error
confidence_low / _high units of the study estimates the interval at :attr:confidence
p_value fraction (0 to 1) two-sided, normal reference; not adjusted
across features
tau2 squared units of the study estimates between-study variance; 0 for one study
q chi-square statistic Cochran's Q; None = one study
i_squared fraction (0 to 1) share of variation from heterogeneity;
None = one study
direction_agree studies studies with the pooled estimate's sign
direction_disagree studies studies with the opposite sign
leave_one_out_max_delta units of the study estimates largest change from dropping one study;
None = one study
=========================== ==================================== ===========================================
Attributes:
| Name | Type | Description |
|---|---|---|
study_count |
int
|
Studies read, over every feature (studies). |
feature_count |
int
|
Distinct features (features); the table's row count. |
confidence |
float
|
The interval's coverage, as a fraction (0 to 1). |
row_count |
int
|
Rows in the table (rows), equal to |
column_names |
list[str]
|
The table's columns, in order. |
columns |
dict[str, list[Any]]
|
Column name -> one value per feature. |
caveats |
list[str]
|
What the pooling assumes. |
Source code in pkg/python/src/pymzlib/stats.py
fit ¶
fit(responses: _PathLike, design: _PathLike, coefficients: Sequence[str], *, trend: bool = False, spline_basis: int | None = None, threads: int = 1, timeout: float | None = 600) -> ModeratedFit
Fit one linear model per feature and test coefficients with limma's moderated t.
Runs mzLib's LinearModel.Fit once - every design column is fitted - and then
EmpiricalBayes.Moderate for each coefficient you name, which also applies
Benjamini-Hochberg across that coefficient's fitted features. This is limma's
lmFit(...) then eBayes(..., legacy = TRUE), reproduced by mzLib to 1e-8 relative.
A feature is fitted on the samples where it was observed, and is reported - never dropped -
when it cannot be: too_few_observations when it has no more observed samples than the
design has coefficients, rank_deficient when its observed samples cannot separate the
coefficients (a feature seen in only one group cannot have a group effect).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
responses
|
_PathLike
|
A TSV with a header row. First column the feature id; every other column one
sample, named by its header. Use the values as you want them modelled - log2
intensities, usually. Blank, |
required |
design
|
_PathLike
|
A TSV with a header row and one row per sample: first column the sample name (matching the responses header exactly, in any order), then one numeric column per coefficient. Include an intercept column yourself if you want one. |
required |
coefficients
|
Sequence[str]
|
Design column names to test, each with its own moderated test and its own Benjamini-Hochberg family. |
required |
trend
|
bool
|
Let the prior variance follow average response (limma's |
False
|
spline_basis
|
int | None
|
Basis functions of the trend spline, intercept included (default 4). Only
with |
None
|
threads
|
int
|
Features fitted at once (threads), or |
1
|
timeout
|
float | None
|
Seconds to allow. |
600
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ModeratedFit
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
a file is missing or malformed; the design's samples are not exactly the responses' samples; a coefficient is not in the design or is named twice; the design is not of full rank; or fewer than two features can be fitted, so no prior exists. |
Examples:
A dilution series from mzLib's own RNA test data: MALAT1 loaded at 500, 250 and 125 ng
against a constant 500 ng FLuc spike, log2 intensities normalised to FLuc in each run (see
tests/fixtures/stats/README.md). Halving MALAT1 should read as about -1:
>>> fit = pymzlib.stats.fit("malat_dilution_log2_vs_fluc.tsv", "malat_dilution_design.tsv",
... ["malat_250ng", "malat_125ng"])
>>> fit.feature_count, fit.sample_count, fit.status_counts
(492, 27, {'fitted': 212, 'too_few_observations': 214, 'rank_deficient': 66})
>>> fit.residual_df_differ, round(fit.prior.df, 1)
(True, 19.6)
>>> import statistics
>>> malat = [r["estimate"] for r in fit.rows("malat_250ng")
... if r["status"] == "fitted" and r["feature"].startswith("MALAT1:")]
>>> len(malat), round(statistics.median(malat), 2)
(116, -0.89)
Source code in pkg/python/src/pymzlib/stats.py
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 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 | |
adjust ¶
Benjamini-Hochberg adjust a list of p-values, keeping every position.
For the i-th smallest of m p-values the adjusted value is min over j >= i of p_(j) m / j, capped
at 1 (Benjamini and Hochberg 1995), computed by mzLib's MultipleTesting.BenjaminiHochberg.
None or NaN marks a feature that was not tested: it stays None and is not counted in
m, which is the honest family. Do not write 1 for an untested feature; that enlarges m.
:func:fit already reports bh_adjusted; this is for p-values from anywhere else.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_values
|
Sequence[float | None]
|
The p-values, each a fraction from 0 to 1, or |
required |
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
Adjusted
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
|
Examples:
>>> adjusted = pymzlib.stats.adjust([0.0002, 0.004, 0.019, None, 0.031, 0.2, float("nan"), 0.74])
>>> adjusted.tested_count
6
>>> [None if v is None else round(v, 4) for v in adjusted.bh_adjusted]
[0.0012, 0.012, 0.038, None, 0.0465, 0.24, None, 0.74]
Source code in pkg/python/src/pymzlib/stats.py
meta ¶
meta(studies: Iterable[Sequence[Any] | Mapping[str, Any]], *, confidence: float = 0.95, timeout: float | None = 60) -> MetaAnalysis
Pool one effect size per study into a random-effects estimate per feature.
Each feature is pooled on its own by mzLib's RandomEffectsMeta.Pool, with the
DerSimonian-Laird (1986) moment estimator of the between-study variance, as metafor's
rma(method = "DL") does (mzLib matches metafor 5.2.1 to 1e-8 relative). Every row also says
how many studies agree in direction and how far the estimate moves when any one is dropped -
the two checks a reader of a pooled result asks for first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
studies
|
Iterable[Sequence[Any] | Mapping[str, Any]]
|
One entry per study: |
required |
confidence
|
float
|
Coverage of the reported interval, as a fraction (0 to 1). |
0.95
|
timeout
|
float | None
|
Seconds to allow. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
MetaAnalysis
|
class: |
Raises:
| Type | Description |
|---|---|
UsageError
|
no studies; an entry without the three values; a feature name that is empty
or holds a tab or newline; an estimate or standard error that is not a finite number,
or a standard error that is not positive; |
Examples:
metafor's own DerSimonian-Laird reference cases, from mzLib's test data:
>>> import csv
>>> with open("metafor_dl_inputs.tsv", newline="") as fh:
... studies = [(r["case"], float(r["yi"]), float(r["sei"]))
... for r in csv.DictReader(fh, delimiter="\t")]
>>> pooled = pymzlib.stats.meta(studies)
>>> for r in pooled.records:
... print(r["feature"], r["studies"], round(r["estimate"], 4), round(r["tau2"], 4),
... r["direction_agree"], r["direction_disagree"])
homogeneous 5 0.3097 0 5 0
heterogeneous 6 0.2513 0.0752 5 1
two_studies 2 -0.2 0.06 1 1
random_eight 8 0.107 0.0911 6 2
Source code in pkg/python/src/pymzlib/stats.py
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 | |
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
BridgeVersion ¶
Bases: TypedDict
What :func:bridge_version returns: a plain dict with these keys.
A TypedDict only so its keys are documented and type-checkable; at runtime it is the
dict it always was. mzlib and verbs are absent from bridges built before they were
added, so read them with .get("mzlib") and .get("verbs") rather than indexing.
Attributes:
| Name | Type | Description |
|---|---|---|
bridge |
str
|
The bridge assembly's own version string. |
protocol |
int
|
The wire-format version. This - not the mzLib version - is the compatibility contract: a binding is compatible with a bridge by protocol. |
runtime |
str
|
The bundled .NET runtime's version string. |
mzlib |
'str | None'
|
Which mzLib this bridge was built against, as |
verbs |
'list[str]'
|
Every command this bridge dispatches, e.g. |
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.
Returns:
| Name | Type | Description |
|---|---|---|
A |
BridgeVersion
|
class: |
BridgeVersion
|
|
Raises:
| Type | Description |
|---|---|
PyMzLibError
|
if the bridge speaks a different wire format than this package. |
Examples:
>>> info = pymzlib.bridge_version()
>>> info["protocol"], "readers read-protein-groups" in info["verbs"]
(1, True)