API Reference¶
Every name in spxtacular.__all__, grouped by area:
from spxtacular import (
# Core data structures
Spectrum, MsnSpectrum, Peak, Precursor, SpectrumType,
# Enums and their permissive type aliases
PeakSelection, PeakSelectionLike,
ActivationType, ActivationTypeLike,
IMType, IMTypeLike,
Analyzer, AnalyzerLike,
# Readers and peak-list writers
Reader, DReader, MzmlReader, ThermoReader, CentroidConfig, AcquisitionType,
MgfReader, Ms2Reader, MspReader, write_mgf, write_ms2, write_msp,
# The .ms1 / .ms2 lookup objects each reader returns
SpectrumLookup, DReaderMs1Lookup, DReaderMs2Lookup, MzmlSpectraLookup,
ThermoScanLookup, PeakListLookup,
# Spectral libraries (mzSpecLib)
read_mzspeclib, MzSpecLibReader, write_mzspeclib, SpectralLibrary, LibraryEntry, Analyte, Interpretation, CvParam,
write_indexed_mzml_gzip,
# Matching and scoring
match_fragments, MatchedFragment, score, cosine, modified_cosine, entropy_similarity,
# Isobaric reporter ions (TMT, TMTpro, iTRAQ)
ReporterIons, extract_reporter_ions, reporter_ion_table,
# Diagnostic ions (named mzPAF reference and immonium ions)
DIAGNOSTIC_IONS, DiagnosticIons, find_diagnostic_ions,
isotope_correction_matrix, correct_isotope_impurities,
# Isotope envelopes and average-composition models
IsotopeModel, IsotopeModelType, IsotopeModelLike,
ISOTOPE_MODELS,
PEPTIDE_ISOTOPE_MODEL, GLYCAN_ISOTOPE_MODEL, LIPID_ISOTOPE_MODEL,
DNA_ISOTOPE_MODEL, RNA_ISOTOPE_MODEL,
brain_isotopic_distribution, resolve_isotope_model,
# Ionization models and deconvolution provenance
IonizationModel, IonizationModelLike, DeconvolutionProvenance,
PROTONATED, DEPROTONATED, SODIATED, AMMONIATED,
IONIZATION_MODELS, resolve_ionization_model,
# Run-level extraction
Chromatogram, extract_chromatogram, extract_xic,
# Visualization
plot_spectrum, mirror_plot, annotate_spectrum, mass_error_plot, facet_plot,
sequence_coverage_plot, profile_centroid_plot, reporter_ion_plot,
plot_chromatogram, plot_xic, save_figure,
# Figure specification, styles and multi-panel composition
FigureSpec, render, FigureStyle, get_style, compose_figure,
# Plot tables
build_plot_table, build_annot_plot_table, plot_from_table, table_view,
# Theme (a submodule, not a function)
theme,
# Utilities
da_to_ppm, ppm_to_da,
# Remote / serialised spectra
fetch_usi, spectrum_from_proxi_response,
to_inline_spectrum, get_json_schema,
to_spectrl_token, from_spectrl_token,
to_spectrl_url, from_spectrl_url,
# Ecosystem interoperability
to_matchms, from_matchms,
to_spectrum_utils, from_spectrum_utils,
# Errors
SpxtacularError,
)
estimate_noise_level is the only name used in this reference that is not exported from the
package root; import it from spxtacular.noise. Everything else, including MatchedFragment, the
SpectrumLookup protocol and the four reader lookup classes, imports from spxtacular.
Each entry below gives the signature as the code declares it: parameter names, types and defaults,
and the return type. A parameter after * is keyword-only. Spectrum and MsnSpectrum carry too
many methods for one table, so Spectrum below lists each of them with its return type
and a one-line summary, and Spectrum methods gives every method's full
signature and parameter table. A runnable example of each is in the
Spectrum guide.
Setup for the examples¶
The example blocks on this page share one spectrum, read from the spectral library fixture in a
clone of the repository:
tests/data/mzspeclib/fetal_brain_tiny.mzSpecLib.txt.gz, a 21-spectrum excerpt of a human fetal
brain HCD library that needs no optional extra. Run this block first. Every later block that is an example — rather than a signature, which is
shown without a body — runs as written after it, with one exception: the
USI fetch needs network access to a public repository. run.mzML and run.d
elsewhere on this page stand in for your own instrument files; the fixtures that can replace them
are listed under Readers — Example files.
from pathlib import Path
import numpy as np
import peptacular as pt
import spxtacular as spx
from spxtacular import MsnSpectrum, Spectrum
library = Path("tests/data/mzspeclib/fetal_brain_tiny.mzSpecLib.txt.gz")
peptide = "LAQANGWGVM[Oxidation]VSHR/2"
entries = list(spx.read_mzspeclib(library))
spectra = [entry.spectrum for entry in entries]
spec = msn = next(e.spectrum for e in entries if e.name and peptide in e.name)
mz, intensity = spec.mz, spec.intensity
intensity_array = intensity
tic = spx.extract_chromatogram(spectra)
Ecosystem interoperability¶
The adapters import their optional dependency only when called. Install spxtacular[matchms],
spxtacular[spectrum-utils], or spxtacular[interop] for both.
to_matchms / from_matchms¶
to_matchms(
spectrum: Spectrum,
*,
extra_metadata: Mapping[str, object] | None = None,
include_spxtacular_metadata: bool = True,
) -> matchms.Spectrum
from_matchms(
spectrum: matchms.Spectrum,
*,
prefer_spxtacular_metadata: bool = True,
) -> Spectrum | MsnSpectrum
to_matchms stable-sorts peaks by m/z and populates matchms fields including id,
precursor_mz, charge, retention_time, ionmode, scan_number, and collision_energy.
extra_metadata adds values outside spxtacular's model, such as smiles or inchikey;
spxtacular-derived values win on a key collision.
By default, spxtacular_metadata contains a namespaced JSON payload with all spxtacular metadata
and the per-peak charge, im, and iso_score arrays. A matchms operation that removes peaks is
supported: return conversion aligns surviving m/z values with those arrays. If an operation changes
m/z values and alignment is no longer possible, the extension arrays are dropped with a warning
rather than attached to the wrong peaks. Set include_spxtacular_metadata=False for a conventional,
intentionally lossy matchms object; set prefer_spxtacular_metadata=False to ignore an existing
payload while importing.
Import returns MsnSpectrum when the payload or conventional matchms metadata contains scan-level
fields. Otherwise it returns Spectrum.
to_spectrum_utils / from_spectrum_utils¶
to_spectrum_utils(
spectrum: MsnSpectrum,
*,
precursor_index: int = 0,
identifier: str | None = None,
warn_on_loss: bool = True,
) -> spectrum_utils.spectrum.MsmsSpectrum
from_spectrum_utils(
spectrum: spectrum_utils.spectrum.MsmsSpectrum,
*,
warn_on_loss: bool = True,
) -> MsnSpectrum
The target model requires centroided peaks, one precursor m/z and charge, and an identifier.
identifier falls back to native_id, then scan=<scan_number>; absent required information
raises instead of being invented. Use precursor_index when an MsnSpectrum has multiple
precursors.
This conversion is explicitly lossy. spectrum_utils has no fields for per-peak charge, ion
mobility, isotope score, multiple precursors, or most acquisition metadata, and internally stores
intensities as float32. Populated unsupported fields produce a UserWarning. ProForma
annotations applied by spectrum_utils are likewise warned about and dropped by
from_spectrum_utils, because MsnSpectrum has no persistent annotation field.
Core classes¶
Spectrum¶
Central data structure for a mass spectrum. Holds parallel numpy arrays for mz, intensity, and optionally charge, im (ion mobility), and iso_score. Transformation methods are chainable and return a new Spectrum unless inplace=True is requested.
Constructor:
Spectrum(
mz: NDArray[np.float64],
intensity: NDArray[np.float64],
*,
charge: NDArray[np.int32] | None = None,
im: NDArray[np.float64] | None = None,
iso_score: NDArray[np.float64] | None = None,
spectrum_type: SpectrumType | str | None = None,
denoised: str | None = None,
normalized: str | None = None,
deconvolution: DeconvolutionProvenance | None = None,
calibration: CalibrationProvenance | None = None,
)
iso_score sits between im and spectrum_type — pass the trailing fields by keyword to avoid
positional mix-ups. mz and intensity must have the same length, and charge, im and
iso_score must match that length when provided. == compares the arrays and the metadata, not
identity, and a Spectrum is unhashable.
Fields:
| Field | Type | Description |
|---|---|---|
mz |
NDArray[np.float64] |
Peak m/z values, sorted ascending |
intensity |
NDArray[np.float64] |
Parallel peak intensities |
charge |
NDArray[np.int32] \| None |
Charge state per peak. None before deconvolution |
im |
NDArray[np.float64] \| None |
Ion mobility per peak. None if not acquired |
iso_score |
NDArray[np.float64] \| None |
Per-peak isotopic profile score (0–1). Populated after deconvolute(); None otherwise. Singletons have iso_score=0.0. |
spectrum_type |
SpectrumType \| str \| None |
Stage tag: CENTROID, PROFILE, or DECONVOLUTED |
denoised |
str \| None |
Name of the denoising method applied, or None |
normalized |
str \| None |
Name of the normalization method applied, or None |
deconvolution |
DeconvolutionProvenance \| None |
Isotope and ionization models plus every deconvolution parameter, recorded by deconvolute() |
calibration |
CalibrationProvenance \| None |
The fitted m/z correction and its residual spread, recorded by recalibrate() |
Validation rules enforced in __post_init__:
len(charge) == len(mz)whenchargeis notNonelen(im) == len(mz)whenimis notNonelen(iso_score) == len(mz)wheniso_scoreis notNone- Supplying a
chargearray forcesspectrum_typetoDECONVOLUTED(it is rewritten, not rejected)
is_decharged property — True when every (non-dropped) peak's charge == 0, i.e. the spectrum has already been through decharge(). Used internally by decharge(), remove_precursor_peak(), and match_fragments() to detect neutral-mass spectra.
Methods:
| Method | Returns | Summary |
|---|---|---|
.peaks |
list[Peak] |
All peaks as Peak objects |
.is_decharged |
bool |
Property: True once every peak's charge == 0 |
len(spec) |
int |
Number of peaks (__len__) |
.top_peaks(n, by, reverse) |
list[Peak] |
Top N peaks sorted by attribute |
.has_peak(target_mz, ...) |
bool |
Check for a peak near target m/z |
.get_peak(target_mz, ...) |
Peak \| None |
Single best-matching peak |
.get_peaks(target_mz, ...) |
list[Peak] |
All peaks matching criteria |
.filter(...) |
Spectrum |
Remove peaks outside bounds; top_n / top_n_per_window=(n, width) keep the most intense peaks globally or per fixed-width m/z window |
.normalize(method) |
Spectrum |
Scale intensities (max / tic / median) |
.scale_intensity(method, ...) |
Spectrum |
Non-linear scaling: "root", "log", "rank" |
.denoise(method) |
Spectrum |
Remove peaks below noise threshold |
.centroid(min_intensity=...) |
Spectrum |
Convert profile to centroid via Gaussian fit, optionally applying a noise or absolute intensity floor |
.merge(mz_tolerance, mz_tolerance_unit, im_tolerance, im_tolerance_unit) |
Spectrum |
Merge nearby peaks by weighted average |
.round_mz(decimals, combine) |
Spectrum |
Round m/z, then sum / max-reduce duplicates |
.deconvolute(..., ionization_model=...) |
Spectrum |
Assign isotope clusters and charge magnitudes using a selected adduct/carrier model |
.decharge(..., ionization_model=...) |
Spectrum |
Convert charged m/z to neutral masses, reusing recorded ionization provenance by default |
.remove_precursor_peak(...) |
Spectrum |
Strip precursor + isotopes + charge states |
.sort(by, reverse) |
Spectrum |
Reorder peaks by attribute |
.copy() |
Spectrum |
Deep copy with all arrays duplicated |
Spectrum.combine(spectra) |
Spectrum |
Classmethod: concatenate multiple spectra |
.match_fragments(fragments, ...) |
list[MatchedFragment] |
Fragment-to-peak matching |
.score(fragments, ...) |
dict[str, float] |
All PSM scores |
.to_dict() |
dict |
Versioned JSON-compatible spectrum payload |
Spectrum.from_dict(payload) |
Spectrum |
Reconstruct Spectrum or MsnSpectrum from a payload |
.to_json(indent=...) |
str |
Encode the versioned spectrum payload as strict JSON |
Spectrum.from_json(value) |
Spectrum |
Reconstruct from JSON text or UTF-8 bytes |
.to_spectrl_token(...) |
str |
Encode as a spectrl.… URL-safe token (requires [spectrl] extra) |
Spectrum.from_spectrl_token(t) |
Spectrum \| MsnSpectrum |
Decode a spectrl.… token (classmethod) |
.to_spectrl_url(*, base, mode, ...) |
str |
Encode as a shareable URL or data: URI (requires [spectrl] extra) |
Spectrum.from_spectrl_url(url) |
Spectrum \| MsnSpectrum |
Decode a token from a URL fragment, query, or data: URI (classmethod) |
Spectrum.from_usi(usi, ...) |
Spectrum \| MsnSpectrum |
Fetch via PROXI from USI (classmethod) |
.save(path) |
None |
Serialise to .npz |
Spectrum.load(path) |
Spectrum |
Load from .npz (classmethod) |
.update(**kwargs) |
Spectrum |
Return copy with specified fields replaced |
.plot(title, color, show_scores, ...) |
go.Figure |
Stick or profile plot, selected from spectrum type (requires plotly) |
.annotate(fragments, ...) |
go.Figure |
Plot with fragment annotations |
.mass_error_plot(fragments, ...) |
go.Figure |
Bubble chart of fragment mass errors |
.facet_plot(*, fragments, mirror_spectrum, ...) |
go.Figure |
Multi-panel facet plot |
.plot_table(show_scores, *, color) |
pd.DataFrame |
Build an editable plot table (one row per peak) |
.annot_plot_table(fragments, ...) |
pd.DataFrame |
Build an editable annotated plot table with fragment labels |
Each method's signature and parameter table: Spectrum methods. A runnable walkthrough: Spectrum guide.
MsnSpectrum¶
Extends Spectrum with instrument metadata fields. Returned by every reader.
Additional fields (all optional):
| Field | Type | Description |
|---|---|---|
scan_number |
int \| None |
Native scan or frame number |
ms_level |
int \| None |
MS level (1, 2, …) |
native_id |
str \| None |
Instrument-specific scan identifier |
rt |
float \| None |
Retention time in seconds |
injection_time |
float \| None |
Ion accumulation time in ms |
total_ion_current |
float \| None |
Total ion current for the scan |
mz_range |
tuple[float, float] \| None |
Acquisition m/z window |
im_range |
tuple[float, float] \| None |
Ion mobility acquisition window |
isolation_mz_range |
tuple[float, float] \| None |
MS2 precursor isolation window (m/z) |
isolation_ook0_range |
tuple[float, float] \| None |
MS2 precursor isolation window (ion mobility) |
im_type |
IMType \| str \| None |
Ion mobility unit (closed vocabulary) |
polarity |
"positive" \| "negative" \| None |
Scan polarity (tacular.types.Polarity, lowercase only) |
resolution |
float \| None |
Instrument resolution |
analyzer |
Analyzer \| str \| None |
Mass analyser type (open vocabulary) |
ramp_time |
float \| None |
timsTOF ramp time in ms |
collision_energy |
float \| None |
Fragmentation collision energy |
activation_type |
ActivationType \| str \| None |
Fragmentation type (open vocabulary) |
precursors |
list[Precursor] \| None |
Precursor ions (MS2 only) |
All fields are keyword-only, including the inherited Spectrum fields. mz_range / im_range
describe the acquisition window of the scan; isolation_mz_range / isolation_ook0_range
describe the precursor isolation window used to select ions for MS2.
See Metadata enums below for the ActivationType, IMType, and Analyzer member lists.
Every Spectrum method is available on an MsnSpectrum: Spectrum methods. A
runnable walkthrough: Spectrum guide — MsnSpectrum.
Metadata enums¶
Three StrEnums are exported from spxtacular root and back the MsnSpectrum fields above:
| Enum | Vocabulary | Members |
|---|---|---|
ActivationType |
Open | CID, HCD, ETD, ECD, EAD, ETHCD ("EThcD"), ETCID ("ETciD"), NETD, UVPD, PD, PQD, SID, IRMPD, BIRD, SORI, PASEF |
IMType |
Closed | OOK0 ("ook0"), IM ("im"), DRIFT_TIME_MS ("drift_time_ms"), CCS ("ccs") |
Analyzer |
Open | ORBITRAP, FT_ICR, TOF, QUADRUPOLE, ION_TRAP, LINEAR_ION_TRAP, QUADRUPOLE_ION_TRAP, MAGNETIC_SECTOR, ELECTROSTATIC_ENERGY_ANALYZER |
IMType is closed: a string must name a member (case-insensitive; also accepts "1/k0" and "drift_time"), anything else raises SpxtacularError. Polarity is not an enum: it is the plain string "positive" or "negative" (tacular.types.Polarity), lowercase only; anything else raises SpxtacularError. ActivationType and Analyzer are open: a member name in any case or a PSI-MS accession ("MS:1002481" from DReader) becomes the member, and other vendor strings are kept as plain strings.
from spxtacular import MsnSpectrum, ActivationType
spec = MsnSpectrum(mz=mz, intensity=intensity, activation_type=ActivationType.HCD)
Type aliases¶
Every enum ships a …Like alias — the permissive union that the library's own parameters and
fields are annotated with. Use them when you type your own wrappers so callers can pass either an
enum member or a plain string.
from tacular.types import Polarity, ToleranceUnit
from spxtacular import PeakSelectionLike, ActivationTypeLike, IMTypeLike, AnalyzerLike
| Alias | Definition |
|---|---|
ToleranceUnit (tacular) |
Literal["da", "ppm"] |
PeakSelectionLike |
PeakSelection \| Literal["closest", "largest", "all"] |
Polarity (tacular) |
Literal["positive", "negative"] |
ActivationTypeLike |
ActivationType \| str |
IMTypeLike |
IMType \| str |
AnalyzerLike |
Analyzer \| str |
ToleranceUnit, PeakSelectionLike and Polarity are closed unions (only the listed literals type-check); the last three are open —
any str is accepted so raw PSI-MS accessions and vendor shorthands pass through.
PeakSelection (CLOSEST, LARGEST, ALL) is the processing-side enum behind the
peak_selection parameter. The tolerance_unit parameter used throughout matching, scoring,
and plotting takes the plain strings "da" or "ppm" (lowercase only; "Da" raises).
Peak¶
Frozen dataclass for a single spectral peak. Returned by peak access methods.
Peak(mz: float, intensity: float, *, charge: int | None = None, im: float | None = None, iso_score: float | None = None)
charge, im, and iso_score are optional. Peak objects are returned by .peaks,
.top_peaks(), .get_peak(), and .get_peaks(). They are read-only snapshots, not references
into the underlying arrays.
iso_score holds the isotopic profile score (0–1) assigned during deconvolution, or None for
peaks that have not been through deconvolution.
>>> peak = Peak(mz=500.1, intensity=1e5, charge=2)
>>> repr(peak)
'Peak(mz=500.1000, int=1.00e+05, z=2)'
Charge conventions¶
charge value |
Meaning |
|---|---|
> 0 |
Peak belongs to an assigned isotope cluster with that charge state |
-1 |
Singleton — no isotope neighbours found at any tested charge |
0 |
After .decharge() — neutral mass, charge state no longer tracked |
Precursor¶
Frozen, slotted, keyword-only dataclass for a selected precursor ion (no longer a Peak
subclass). Exported from the package root: from spxtacular import Precursor.
Precursor(
*,
precursor_mz: float,
intensity: float = 0.0,
charge: int | None = None,
im: float | None = None,
im_type: IMTypeLike | None = None, # unit of `im`: "ook0", "drift_time_ms", ...
iso_score: float | None = None,
is_monoisotopic: bool | None = None,
)
Stored in MsnSpectrum.precursors. The selected-ion m/z is precursor_mz, not mz. im holds
whatever mobility value the source recorded; im_type says which kind it is (Bruker and most mzML
files give 1/K0, some mzML files give drift time).
SpectrumType¶
Exported from the package root:
StrEnum with three members:
| Member | Value | Meaning |
|---|---|---|
CENTROID |
"centroid" |
Peak-picked data |
PROFILE |
"profile" |
Raw continuous data |
DECONVOLUTED |
"deconvoluted" |
Isotope clusters assigned |
Several methods check or set this flag to keep operations in order — decharge() on a
spectrum that has not been deconvoluted raises, and centroid() on an already-centroided
spectrum is a no-op.
Spectrum methods¶
Every Spectrum method, with its signature as the code declares it; MsnSpectrum inherits all of
them. The one-line summaries and return types are in the Spectrum table above, and a
runnable example of each method is in the Spectrum guide. Methods that wrap a
module-level function are documented beside that function:
to_dict / to_json, save / load,
to_spectrl_token, to_spectrl_url,
from_usi, match_fragments, score,
plot, annotate,
mass_error_plot, facet_plot,
plot_table and annot_plot_table.
Peak access¶
peaks¶
Returns all peaks as a list of Peak objects. Iterates the full spectrum; prefer numpy operations on .mz / .intensity for performance on large spectra.
top_peaks¶
def top_peaks(
self,
n: int,
*,
by: Literal["intensity", "mz", "charge", "im", "score"] = "intensity",
reverse: bool = True,
) -> list[Peak]
Returns the top n peaks sorted by the chosen attribute.
| Parameter | Description |
|---|---|
n |
Number of peaks to return |
by |
Sort key: "intensity" (default), "mz", "charge", "im", "score" |
reverse |
True (default) returns highest values first |
"charge" requires a charge array, "im" an ion mobility array, and "score" an iso_score array. Each raises ValueError when the corresponding array is absent.
Peak finding¶
has_peak¶
def has_peak(
self,
target_mz: float,
*,
tolerance: float = 0.01,
tolerance_unit: Literal["da", "ppm"] = "da",
target_charge: int | None = None,
target_im: float | None = None,
im_tolerance: float = 0.01,
) -> bool
Returns True if at least one peak matches all supplied criteria.
get_peak¶
def get_peak(
self,
target_mz: float,
*,
tolerance: float = 0.01,
tolerance_unit: Literal["da", "ppm"] = "da",
target_charge: int | None = None,
target_im: float | None = None,
im_tolerance: float = 0.01,
peak_selection: Literal["largest", "closest"] = "largest",
) -> Peak | None
Returns a single matching peak, or None if no match is found. When multiple peaks fall within tolerance, peak_selection="largest" picks the most intense; peak_selection="closest" picks the nearest in m/z. Use get_peaks to get all of them.
get_peaks¶
def get_peaks(
self,
target_mz: float,
*,
tolerance: float = 0.01,
tolerance_unit: Literal["da", "ppm"] = "da",
target_charge: int | None = None,
target_im: float | None = None,
im_tolerance: float = 0.01,
) -> list[Peak]
Returns all peaks matching the criteria (may be empty).
Filtering and processing¶
Transformation methods that expose inplace default to False. In that mode they return a new
Spectrum, leave the input unchanged, and support method chaining.
filter¶
def filter(
self,
*,
min_mz: float | None = None,
max_mz: float | None = None,
min_intensity: float | None = None,
max_intensity: float | None = None,
min_charge: int | None = None,
max_charge: int | None = None,
min_im: float | None = None,
max_im: float | None = None,
min_score: float | None = None,
max_score: float | None = None,
top_n: int | None = None,
top_n_per_window: tuple[int, float] | None = None,
inplace: bool = False,
) -> Self
Removes peaks outside the given bounds. All parameters are optional and combinable. top_n is applied last — after all range filters — keeping the top_n most intense survivors. top_n_per_window=(n, width) is its windowed counterpart: keep the n most intense peaks per fixed-width m/z window (bins anchored at 0, [k*width, (k+1)*width)), preserving quiet regions that a global top_n erases. The two are mutually exclusive.
Charge, ion mobility, and score filters are silently ignored if the spectrum lacks those arrays.
Score filter parameters:
| Parameter | Type | Description |
|---|---|---|
min_score |
float \| None |
Keep peaks with score >= this value. Only effective when the iso_score array is present. |
max_score |
float \| None |
Keep peaks with score <= this value. Only effective when the iso_score array is present. |
normalize¶
def normalize(
self,
*,
method: Literal["max", "tic", "median"] = "max",
inplace: bool = False,
) -> Self
Scales all intensities so that the chosen reference equals 1.0.
method |
Normalization factor |
|---|---|
"max" (default) |
Most intense peak |
"tic" |
Total ion current (sum of all intensities) |
"median" |
Median intensity |
Calling normalize on an already-normalized spectrum rescales it again with the requested method
(normalizing is idempotent for a given method, so this is safe).
Removing peaks, replacing intensities, rounding peaks, or combining multiple nonempty spectra clears the normalization marker. Normalize again after those operations when the resulting spectrum needs a unit reference.
denoise¶
def denoise(
self,
*,
method: Literal["mad", "percentile", "histogram", "baseline", "iterative_median"]
| float | int = "mad",
inplace: bool = False,
) -> Self
Removes peaks below an estimated noise threshold. Peaks at or above the threshold are kept.
method |
Threshold strategy |
|---|---|
"mad" (default) |
median + 3 × 1.4826 × MAD |
"percentile" |
5th percentile of intensities |
"histogram" |
Mode of 100-bin histogram + 3 σ (FWHM-derived) |
"baseline" |
Mean + 3 σ of the bottom 25th percentile |
"iterative_median" |
Iteratively refines median/MAD estimate over 3 passes |
float or int |
Used directly as the absolute threshold |
Calling denoise on an already-denoised spectrum is a silent no-op: it returns an independent
copy (or the spectrum itself with inplace=True).
centroid¶
def centroid(
self,
*,
min_intensity: float | Literal["noise"] | None = None,
inplace: bool = False,
) -> Self
Converts a profile-mode spectrum to centroid mode using vectorized Gaussian fitting. Sharp local
maxima use a three-point log-space fit for sub-bin positions. Flat maxima use the midpoint of the
plateau's m/z bounds and its observed height, since a Gaussian fit is not identifiable there.
Ion mobility is taken from the apex sample, or the lower middle sample of a plateau.
min_intensity="noise" uses the MAD noise estimate. A number applies an absolute floor,
and None applies no intensity floor. Boundary peaks without both flanks are excluded.
Calling this on an already-centroided spectrum is a silent no-op: it returns an independent copy
(or the spectrum itself with inplace=True).
merge¶
def merge(
self,
*,
mz_tolerance: float = 0.01,
mz_tolerance_unit: Literal["ppm", "da"] = "da",
im_tolerance: float = 0.05,
im_tolerance_unit: Literal["relative", "absolute"] = "relative",
inplace: bool = False,
) -> Self
Merges nearby peaks using a greedy intensity-ordered strategy. Peaks are processed from most to least intense; each unused neighbour within the tolerance window is merged into the current peak. The merged peak carries the intensity-weighted average m/z (and ion mobility if present) and the summed intensity. Charge arrays are preserved — only peaks with matching charge are merged together.
deconvolute¶
def deconvolute(
self,
*,
tolerance: float = 50,
tolerance_unit: Literal["ppm", "da"] = "ppm",
charge_range: tuple[int, int] = (1, 3),
intensity: Literal["base", "total"] = "total",
max_dpeaks: int = 2000,
inplace: bool = False,
min_intensity: float | Literal["min"] = "min",
min_score: float = 0.0,
isotope_model: IsotopeModel | IsotopeModelType | str = "peptide",
min_isotope_abundance: float = 0.01,
max_isotope_fold_error: float = 2.0,
max_isotope_gaps: int = 0,
max_isotopes: int | None = None,
im_tolerance: float = 0.05,
im_tolerance_unit: Literal["relative", "absolute"] = "relative",
ionization_model: IonizationModel | str | float | None = None,
) -> Self
Assigns each peak to an isotope cluster and records the charge state. Returns a spectrum with spectrum_type=DECONVOLUTED and a populated charge array.
| Parameter | Description |
|---|---|
tolerance |
Peak matching tolerance (default 50 ppm) |
tolerance_unit |
"ppm" (default) or "da" |
charge_range |
(min_charge, max_charge) inclusive; default (1, 3) |
intensity |
"total" sums matched peaks; "base" uses observed A+0 or zero when it is absent |
max_dpeaks |
Maximum output peaks (default 2000) |
min_intensity |
float \| "min" — Absolute intensity floor for isotope detectability. The sentinel "min" (default) uses the spectrum's own minimum intensity as the S/N floor. |
min_score |
float — Clusters whose best isotopic profile score falls below this threshold are recorded as singletons. Default 0.0 accepts all clusters. |
isotope_model |
Built-in name or custom IsotopeModel. Available presets are "peptide", "glycan", "lipid", "dna", and "rna". |
min_isotope_abundance |
Relative theoretical abundance at which directional expansion stops. Default 0.01. |
max_isotope_fold_error |
Hard observed-to-expected intensity gate. Default 2.0 accepts 0.5x to 2x expected. |
max_isotope_gaps |
Missing positions allowed before stopping one direction. Default 0. |
max_isotopes |
Optional hard envelope-length limit. Default None is adaptive. |
im_tolerance |
Candidate-to-seed mobility tolerance when ion mobility is available. Default 0.05. |
im_tolerance_unit |
"relative" (default) or "absolute". |
ionization_model |
Adduct preset, signed carrier mass, or custom model. Defaults from scan polarity |
After deconvolution the charge array follows the charge conventions table: > 0 for assigned clusters, -1 for singletons.
See Deconvolution for a detailed walkthrough.
decharge¶
def decharge(
self,
*,
inplace: bool = False,
ionization_model: IonizationModel | str | float | None = None,
) -> Self
Converts deconvoluted m/z values to neutral monoisotopic masses using the ionization model recorded
by deconvolute(). Singletons (charge == -1) are dropped. The resulting charge array is set to
all zeros, which marks neutral masses.
Pass ionization_model only to override recorded provenance. Without provenance, positive scans
use [M+H]+ and negative scans use [M-H]-.
Raises ValueError if the spectrum is not in DECONVOLUTED state.
Calling decharge() again on an already-decharged spectrum (spec.is_decharged) warns and leaves
the neutral m/z values unchanged. The default non-inplace path returns an independent copy.
The
iso_scorearray is propagated throughdecharge()— each surviving neutral-mass peak retains the score of its charged precursor.
sort¶
def sort(
self,
*,
by: Literal["mz", "intensity", "charge", "im", "score"] = "mz",
reverse: bool = False,
inplace: bool = False,
) -> Self
Reorders every parallel array by the chosen attribute. by="charge", "im", and "score" raise
ValueError when the corresponding array is absent. Any other value of by raises ValueError.
update¶
Low-level helper to create a new Spectrum with arbitrary fields replaced. Prefer the named methods above for normal use.
Precursor removal and scaling¶
remove_precursor_peak¶
def remove_precursor_peak(
self,
*,
precursor_mz: float | None = None,
precursor_charge: int | None = None,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
isotopes: int | Literal["auto"] = "auto",
isotope_threshold: float = 0.01,
remove_charge_states: bool = True,
inplace: bool = False,
isotope_model: IsotopeModel | IsotopeModelType | str = "peptide",
ionization_model: IonizationModel | str | float | None = None,
) -> Self
Remove the precursor peak, its isotope envelope, and (optionally) all lower charge states. Adapts to spectrum state:
| State | Behaviour |
|---|---|
| Centroid | Removes all charge states 1..z and their isotope envelopes |
| Deconvoluted | Targets only the monoisotopic peak at the precursor charge (charge-aware) |
| Decharged | Targets the precursor neutral mass directly |
| Profile | Raises ValueError (call .centroid() first) |
When called on an MsnSpectrum without an explicit precursor_mz, the method auto-detects from MsnSpectrum.precursors and removes peaks for all precursors. With isotopes="auto", it uses the selected isotope model to determine the significant isotopes. The ionization model defaults to recorded deconvolution provenance, then scan polarity.
scale_intensity¶
def scale_intensity(
self,
*,
method: Literal["root", "log", "rank"] = "root",
degree: int = 2,
base: float = 2.0,
inplace: bool = False,
) -> Self
Non-linear intensity scaling (independent of normalize(), which divides by a reference). "root" applies an nth-root transform (default sqrt), "log" applies log_base(intensity + 1), "rank" replaces intensities with their rank.
round_mz¶
def round_mz(
self,
*,
decimals: int = 0,
combine: Literal["sum", "max"] = "sum",
inplace: bool = False,
) -> Self
Round m/z values to decimals decimals and merge duplicate peaks via sum or max of their intensities.
Clears normalization, mobility, and isotope scores. Charged spectra also lose their charge assignments
and deconvolution record. Already decharged spectra retain their zero-charge marker and provenance
so the rounded values remain identifiable as neutral masses.
Combining spectra¶
Spectrum.combine¶
Concatenate peaks from multiple spectra into a single new Spectrum, sorted by m/z ascending.
Empty inputs do not erase metadata from nonempty inputs. Optional per-peak arrays (charge, im,
iso_score) are carried over when every contributing input provides them. Combining multiple
nonempty inputs clears normalization. Other scalar metadata is preserved when all inputs agree.
Combining neutral masses with m/z values raises ValueError. Charged inputs with differing
deconvolution records also raise, including records that differ only in processing parameters.
Decharge those inputs separately before combining them, so each conversion uses its own carrier.
A charged scan whose negative polarity would be lost in the base Spectrum also requires this
explicit conversion.
The return type is always the base Spectrum — MSn metadata cannot be sensibly combined across scans.
Readers¶
.ms1 and .ms2 are lookup objects, not generators: iterable and indexable, but not
iterators. next(reader.ms2) raises TypeError — use next(iter(reader.ms2)).
Lookup objects¶
Every reader builds its own lookup objects; you never construct one yourself. They all satisfy the
SpectrumLookup protocol, so code that only iterates or indexes works across formats:
from collections.abc import Iterator
from typing import Any, Protocol
from spxtacular import MsnSpectrum
class SpectrumLookup(Protocol):
def __iter__(self) -> Iterator[MsnSpectrum]: ... # a fresh walk each time
def __getitem__(self, key: Any, /) -> MsnSpectrum: ... # the key its format uses
DReaderMs1Lookup(dreader: DReader)
DReaderMs2Lookup(dreader: DReader)
MzmlSpectraLookup(reader: MzmlReader, *, ms_level: int | None = None)
ThermoScanLookup(reader: ThermoReader, *, ms_level: int | None = None)
PeakListLookup(reader: MgfReader | Ms2Reader | MspReader, *, ms_level: int | None = None)
What the index means differs per format and is given in each reader's section below.
Reader¶
Format-agnostic entry point. Detects .d (Bruker timsTOF), .mzML, .raw (Thermo), .mgf,
.ms2, or .msp from the path suffix — a trailing .gz is stripped first — and delegates to DReader /
MzmlReader / ThermoReader / MgfReader / Ms2Reader / MspReader; any other suffix raises
ValueError.
Reader(
path: str | Path,
*,
centroid_config: CentroidConfig | None = None,
mzml_gzip_mode: Literal["auto", "indexed", "stream"] = "auto",
mzml_in_memory: bool = False,
)
| Property / Method | Type | Description |
|---|---|---|
.ms1 |
DReaderMs1Lookup \| MzmlSpectraLookup \| ThermoScanLookup \| PeakListLookup |
MS1 spectra. Iterate or index. Empty for .mgf / .ms2 / .msp |
.ms2 |
DReaderMs2Lookup \| MzmlSpectraLookup \| ThermoScanLookup \| PeakListLookup |
MS2 spectra — iterate or index |
.access_strategy |
str \| None |
Concrete mzML access route, or None for other formats |
.get_by_scan(n, *, ms_level=None) |
MsnSpectrum |
Spectrum by scan number |
.get_by_native_id(id) |
MsnSpectrum |
Spectrum by native id |
.get_by_sage_scannr(scannr, *, precursor_offset=None) |
MsnSpectrum |
Spectrum for a Sage scannr; precursor_offset is .d only |
.open() / .close() |
None |
Open / close the delegate; also driven by with |
The three lookups exist on every format reader too. Missing keys raise KeyError; keys that cannot
name one spectrum (no scan numbers in the file, duplicates, ambiguous Bruker numbers) raise
SpxtacularError. The rules per format: Readers — Lookup by scan number or native id.
from spxtacular import Reader
with Reader("tests/data/example.mzML") as r: # or your own file, or Reader("/data/sample.d")
for ms1_spectrum in r.ms1:
print(ms1_spectrum)
Full documentation: Readers — Reader
MzmlReader¶
Reads .mzML files. A context manager is optional but recommended — it keeps one file handle open
instead of reopening the file per operation.
MzmlReader(
mzml_path: str | Path,
*,
gzip_mode: Literal["auto", "indexed", "stream"] = "auto",
in_memory: bool = False,
)
The default "auto" mode uses a self-indexed gzip file, else rapidgzip in place, else an
in-memory decompression; it never writes next to the input. For intentional sequential reads, use gzip_mode="stream".
| Property / Method | Type | Description |
|---|---|---|
.ms1 |
MzmlSpectraLookup |
MS1 spectra — iterate, or index by overall index / native ID |
.ms2 |
MzmlSpectraLookup |
MS2 spectra — iterate, or index by overall index / native ID |
reader[key] |
MsnSpectrum |
Spectrum by 0-based index (reader[0]) or native ID (reader["scan=19"]) |
.get_by_scan(n, *, ms_level=None) / .get_by_native_id(id) / .get_by_sage_scannr(s) |
MsnSpectrum |
Scan number from scan= / Thermo / index= / spectrum= ids; SpxtacularError if the file's ids carry none |
.access_strategy |
str \| None |
Concrete route selected by mzMLPy |
.open() / .close() |
None |
Open / close the persistent mzmlpy handle |
Index access is not MS-level filtered — reader.ms2[0] is the first spectrum in the file, not the
first MS2 spectrum.
Full documentation: Readers — MzmlReader
DReader¶
Reads Bruker timsTOF .d directories. Must be opened before use — via open()/close() or, preferably, as a context manager.
DReader(analysis_dir: str | Path, *, centroid_config: CentroidConfig | None = None)
| Property / Attribute | Type | Description |
|---|---|---|
.ms1 |
DReaderMs1Lookup |
All MS1 frames — iterate, or index by tdfpy frame_id |
.ms2 |
DReaderMs2Lookup |
All MS2 spectra — iterate, or index by tdfpy precursor_id (DDA only; DIA/PRM raise NotImplementedError) |
.get_by_scan(n, *, ms_level=None) |
MsnSpectrum |
MS1 frame_id, DDA precursor_id, DIA/PRM frame_id; pass ms_level for DDA |
.get_by_native_id(id) |
MsnSpectrum |
frame=F, precursor=P, F@wI (DIA), F@tT (PRM) |
.get_by_sage_scannr(s, *, precursor_offset=1) |
MsnSpectrum |
DDA only; precursor id = scannr + precursor_offset (0 for Sage on timsrust >= 0.6) |
.acquisition_type |
AcquisitionType |
DDA / DIA / PRM / UNKNOWN |
.open() / .close() |
None |
Open / close the underlying tdfpy reader |
Full documentation: Readers — DReader
ThermoReader¶
Reads Thermo .raw files via fisher-py (Thermo's RawFileReader .NET assemblies — a .NET runtime
must be installed on the machine). Must be opened before use — via open()/close() or,
preferably, as a context manager.
ThermoReader(raw_path: str | Path, *, prefer_vendor_centroid: bool = True)
| Property / Method | Type | Description |
|---|---|---|
.ms1 |
ThermoScanLookup |
MS1 spectra — iterate, or index by native 1-based scan number |
.ms2 |
ThermoScanLookup |
MS2 spectra — iterate, or index by native 1-based scan number |
reader[scan] |
MsnSpectrum |
Spectrum of any MS level by native scan number |
.get_by_scan(n, *, ms_level=None) / .get_by_native_id(id) / .get_by_sage_scannr(s) |
MsnSpectrum |
Native id controllerType=0 controllerNumber=1 scan=N or scan=N |
.open() / .close() |
None |
Open / release the RawFileReader handle |
With prefer_vendor_centroid=True (default), profile-mode FTMS scans yield Thermo's own centroid
stream (CENTROID, with per-peak charge annotations — unknown charge arrives as -1); with
False, they yield the full PROFILE trace.
Full documentation: Readers — ThermoReader
MgfReader / Ms2Reader / MspReader¶
Read the MGF, MS2, and MSP (NIST spectral-library) peak-list formats. Pure standard library — no
optional extra, always available. All three formats hold fragmentation spectra only: every
spectrum comes back with ms_level=2 and spectrum_type=SpectrumType.CENTROID. Gzip is detected
by magic bytes, so .mgf.gz / .ms2.gz / .msp.gz just work. MspReader handles both the
NIST/SpectraST peptide-library dialect and metabolomics exports (MoNA, GNPS, MS-DIAL) with
case-insensitive header matching.
MgfReader(path: str | Path)
Ms2Reader(path: str | Path)
MspReader(path: str | Path)
| Property / Method | Type | Description |
|---|---|---|
iter(reader) |
Iterator[MsnSpectrum] |
Every spectrum, in file order |
len(reader) |
int |
Spectra in the file — one counting pass, then cached |
reader[key] |
MsnSpectrum |
Spectrum by 0-based position (reader[0]) or native_id (reader["scan=19"]); a native_id is indexed (first match wins), falling back to a streaming search when the index cannot answer, a position is O(n) |
.get_by_scan(n, *, ms_level=None) / .get_by_native_id(id) / .get_by_sage_scannr(s) |
MsnSpectrum |
Indexed: the first call parses the file once, later calls seek. MSP has no scan numbers |
.ms1 |
PeakListLookup |
Always empty — peak lists carry no survey scans |
.ms2 |
PeakListLookup |
Every spectrum — iterate or index |
.open() / .close() |
None |
open() checks the file exists; close() is a no-op (each walk streams its own handle) |
Malformed input raises ValueError naming the file and line number. Unknown headers, multi-charge
values, comment lines, and peak-less blocks are tolerated.
Full documentation: Readers — MGF / MS2 / MSP
write_mgf / write_ms2 / write_msp¶
Write spectra to a peak-list file, returning the path. A .gz suffix gzips the output.
write_mgf(spectra: Iterable[Spectrum] | Spectrum, path: str | Path, *, annotations=None) -> Path
write_ms2(spectra: Iterable[Spectrum] | Spectrum, path: str | Path, *, ionization_model=None) -> Path
write_msp(spectra: Iterable[Spectrum] | Spectrum, path: str | Path, *, annotations=None) -> Path
| Behaviour | Detail |
|---|---|
| Peak values | mz / intensity at repr precision — a write → read round trip is exact |
SpectrumType.PROFILE |
Raises ValueError; peak lists are centroid data |
| Polarity | MGF/MS2: carried by the sign of the written charge (CHARGE=2-, Z -2). MSP: explicit Ion_mode: P/N line |
MS2 Z mass |
Singly protonated [M+H]+ mass in every mode: the neutral mass from the precursor m/z, charge magnitude and ionization_model (default: deconvolution provenance, then [M-H]- for a negative charge, else [M+H]+), plus one proton |
| Missing metadata | Omitted, except MS2's mandatory S fields (scan number → 1-based position, precursor m/z → 0.0) |
annotations= (MGF, MSP) |
Optional mzPAF, one entry per spectrum: one item per peak (None, string, PafAnnotation, or a list) or a list of MatchedFragment. Adds a quoted last column, mz intensity "b2/0.1ppm,y3^2" |
Full documentation: Readers — Writing
read_mzspeclib / MzSpecLibReader / write_mzspeclib¶
Read and write HUPO-PSI mzSpecLib 1.0 spectral libraries, text or JSON, optionally gzipped.
read_mzspeclib(path: str | Path) -> SpectralLibrary
SpectralLibrary(entries: list[LibraryEntry] = [], attributes: tuple[CvParam, ...] = (),
clusters: dict[int, tuple[CvParam, ...]] = {})
MzSpecLibReader(path: str | Path) # context manager; iterate for LibraryEntry, one at a time
.open() / .close(); .attributes, .format ("text" | "json"), .clusters (after a full pass)
write_mzspeclib(entries: SpectralLibrary | Iterable[LibraryEntry] | LibraryEntry, path: str | Path,
*, format: Literal["text", "json"] | None = None) -> Path
LibraryEntry(spectrum: MsnSpectrum, *, key=None, name=None, analytes=(), interpretations=(),
peak_annotations=None, peak_attributes=None, attributes=())
LibraryEntry.from_spectrum(spectrum, peptidoform=None, *, charge=None, score=None, key=None, name=None,
peak_annotations=None, attributes=()) -> LibraryEntry
Analyte(*, id=1, peptidoform: ProFormaAnnotation | str | None = None, charge=None, attributes=())
Interpretation(*, id=1, members=(), score=None, attributes=(), member_attributes={})
CvParam(accession, name, value=None, value_accession=None, group=None)
| Behaviour | Detail |
|---|---|
| Format | Read: detected from content and gzip magic. Write: JSON for *.json[.gz], else text |
| Streaming | MzSpecLibReader yields entries one at a time, in memory that does not grow with the number of spectra (text and JSON, gzipped or not), with attributes available before iterating; same entries and errors as read_mzspeclib |
| Spectrum fields | Precursor m/z and charge, RT, ion mobility, CE, dissociation, polarity, MS level, scan number, native id, TIC, injection time map to MsnSpectrum; other terms stay in attributes |
| Analytes | peptidoform is a peptacular ProFormaAnnotation carrying the charge |
| Peaks | peak_annotations: tuple of paftacular PafAnnotation per peak, or None. JSON writes one mzPAF string per peak, "?" when unannotated |
| Invalid input | SpxtacularError (bad structure, version other than 1.x, bad mzPAF or ProForma) |
Full documentation: Spectral libraries
write_indexed_mzml_gzip¶
Compress an mzML file into mzMLPy's self-indexed gzip format, which MzmlReader can open with
random access. Requires the [mzml] extra.
write_indexed_mzml_gzip(
source: str | Path,
output: str | Path,
*,
compression_level: int = 6,
)
Returns whatever mzMLPy's write_indexed_gzip returns. Full documentation:
Readers — MzmlReader
CentroidConfig¶
Dataclass of parameters forwarded to tdfpy's frame.centroid(). Only used by DReader (and by
Reader for .d inputs); ignored by MzmlReader.
CentroidConfig(
*,
mz_tolerance: float = 8.0,
mz_tolerance_unit: Literal["ppm", "da"] = "ppm",
im_tolerance: float = 0.1,
im_tolerance_unit: Literal["relative", "absolute"] = "relative",
min_peaks: int = 3,
noise_filter: Literal["mad", "percentile", "histogram", "baseline", "iterative_median"]
| float | None = None,
)
Full documentation: Readers — CentroidConfig
AcquisitionType¶
Exported from the package root:
StrEnum with four members: DDA, DIA, PRM, UNKNOWN.
Noise estimation¶
estimate_noise_level is not exported from the package root but is the function backing Spectrum.denoise().
from spxtacular.noise import estimate_noise_level
threshold = estimate_noise_level(intensity_array, method="mad")
method |
Strategy |
|---|---|
"mad" |
median + 3 × 1.4826 × MAD |
"percentile" |
5th percentile |
"histogram" |
Histogram mode + 3 σ |
"baseline" |
Bottom-quartile mean + 3 σ |
"iterative_median" |
Three-pass iterative median refinement |
float or int |
Used directly as the absolute threshold |
Isotope and ionization models¶
The deconvolution guide explains how these models affect cluster finding and neutral-mass
conversion. All names below are exported from spxtacular.
Isotope models¶
IsotopeModel(
atoms_per_da: Mapping[str, float],
*,
fixed_composition: Mapping[str, int] = ...,
isotope_abundances: Mapping[str, Sequence[tuple[int, float]]] | None = None,
name: str = "custom",
)
brain_isotopic_distribution(
composition: Mapping[str, int],
*,
max_isotopes: int | None = None, # None: 32 peaks, longer when the mass needs it
isotope_abundances=None,
) -> NDArray[np.float64]
resolve_isotope_model(model: IsotopeModel | IsotopeModelType | str = "peptide") -> IsotopeModel
IsotopeModelType has PEPTIDE, GLYCAN, LIPID, DNA, and RNA members. The corresponding
objects are PEPTIDE_ISOTOPE_MODEL, GLYCAN_ISOTOPE_MODEL, LIPID_ISOTOPE_MODEL,
DNA_ISOTOPE_MODEL, and RNA_ISOTOPE_MODEL. ISOTOPE_MODELS maps their lowercase names to the
objects. Custom models store expected atoms per Dalton plus any fixed terminal composition. When
omitted, fixed_composition is an empty mapping.
A model answers four questions about a neutral mass:
IsotopeModel.distribution(neutral_mass: float, max_isotopes: int | None = None) -> NDArray[np.float64]
IsotopeModel.adaptive_distribution(
neutral_mass: float,
*,
min_relative_abundance: float = 0.01,
max_isotopes: int | None = None,
) -> NDArray[np.float64]
IsotopeModel.apex_index(neutral_mass: float, max_isotopes: int | None = None) -> int
IsotopeModel.estimate_composition(neutral_mass: float) -> dict[str, int]
distribution() returns the relative abundances of the isotope peaks, cached per integer Dalton;
max_isotopes=None gives 32 peaks, or more when a high mass needs them to reach its apex, and an
integer truncates to exactly that many. adaptive_distribution() instead chooses the length from
the mass, extending it until the whole trailing window falls below min_relative_abundance, and
always keeps the A+0 peak. apex_index() is the index of the most abundant peak, which above
roughly 1900 Da is no longer A+0 — deconvolution uses it to anchor a cluster on its apex.
estimate_composition() gives the integer elemental composition the model expects at that mass.
The fields are atoms_per_da, fixed_composition, fixed_mass (the monoisotopic mass of that
fixed composition), isotope_abundances and name. to_dict() and from_dict() round-trip a model
through JSON, which is how a custom model reaches a saved spectrum's deconvolution provenance.
Ionization models¶
IonizationModel(
name: str,
polarity: Polarity, # "positive" or "negative"
carrier_mass: float,
*,
carrier: str = "custom",
)
resolve_ionization_model(
model: IonizationModel | str | float = PROTONATED,
) -> IonizationModel
The presets are PROTONATED ([M+H]+), DEPROTONATED ([M-H]-), SODIATED ([M+Na]+), and
AMMONIATED ([M+NH4]+). IONIZATION_MODELS maps accepted names and aliases to these objects.
Each model provides ion_mz(), neutral_mass(), notation(), to_dict(), and from_dict().
Charge arrays keep positive magnitudes. Polarity and carrier mass live in the model.
DeconvolutionProvenance(
isotope_model: str,
ionization_model: IonizationModel,
charge_range: tuple[int, int],
tolerance: float,
tolerance_unit: ToleranceUnit,
intensity_mode: str,
min_intensity: float,
min_score: float,
*,
isotope_model_definition: IsotopeModel | None = None,
min_isotope_abundance: float = 0.01,
max_isotope_fold_error: float = 2.0,
max_isotope_gaps: int = 0,
max_isotopes: int | None = None,
im_tolerance: float = 0.05,
im_tolerance_unit: Literal["relative", "absolute"] = "relative",
)
DeconvolutionProvenance records the resolved isotope and ionization models plus every
deconvolution parameter that affects matching. It is attached to deconvoluted spectra and is
preserved by native persistence, matchms, and spectrl round trips. decharge() and automatic
precursor removal reuse it by default. See Deconvolution for the full parameter
set and examples.
Token serialisation (spectrl)¶
The single supported wire format for sharing a spectrum as a string is the spectrl token. Encodes a full spectrum (peaks, metadata, precursors) into a compact URL-safe token that mirrors mzML semantics, with PSI-MS CV params in a single compressed CBOR document and an integrity checksum.
Requires the optional [spectrl] extra.
from spxtacular import Spectrum, to_spectrl_token, from_spectrl_token, to_inline_spectrum
token = spec.to_spectrl_token() # lossy (bounded-error), default
token_exact = spec.to_spectrl_token(lossless=True) # bit-exact arrays
restored = Spectrum.from_spectrl_token(token)
inline = to_inline_spectrum(spec) # → spectrl.InlineSpectrum
Method forms:
def to_spectrl_token(self, *, lossless: bool = False, max_len: int | None = None) -> str
@classmethod
def from_spectrl_token(cls, token: str) -> Spectrum | MsnSpectrum
The round-trip is faithful — every spxtacular field is carried.
Via mzML-native CV params: mz, intensity, charge (including singletons),
im under its exact PSI-MS array accession, im_type, spectrum type, and — for MsnSpectrum — native_id,
ms_level, polarity, rt, mz_range, total_ion_current, precursors,
isolation_mz_range, collision_energy, activation_type.
iso_score rides in spectrl's extra_arrays slot under key "iso_score"
(encoded as a non-standard mzML binary array MS:1000786).
spxtacular scalar fields without an mzML CV counterpart —
denoised/normalized provenance strings, scan_number, resolution,
analyzer, ramp_time, im_range, isolation_ook0_range — are carried
losslessly as namespaced user_params (spxtacular: prefix).
URL sharing¶
to_spectrl_url / from_spectrl_url bind a token into a shareable link (or
decode one back). Also available as Spectrum.to_spectrl_url /
Spectrum.from_spectrl_url.
from spxtacular import to_spectrl_url, from_spectrl_url
url = to_spectrl_url(spec, base="https://example.com/view") # fragment (default)
url = to_spectrl_url(spec, base="https://example.com/view", mode="query", param="d")
uri = to_spectrl_url(spec, mode="data") # data: URI, no base
spec = from_spectrl_url(url) # extract + decode
mode selects the binding:
mode |
Result | base |
|---|---|---|
"fragment" (default) |
base#spectrl.… — token in the URL fragment (never sent to the server) |
required |
"query" |
base?<param>=spectrl.… — token as a query parameter |
required |
"data" |
data:application/vnd.spectrl;v=…,… URI |
ignored |
lossless and max_len are forwarded to the token encoder.
Method forms:
def to_spectrl_url(
self,
*,
base: str | None = None,
mode: str = "fragment", # "fragment" | "query" | "data"
param: str = "d",
lossless: bool = False,
max_len: int | None = None,
) -> str
@classmethod
def from_spectrl_url(cls, url: str) -> Spectrum | MsnSpectrum
base names whatever will decode the token: the
spxtacular spectrum viewer reads a …#spectrl.v3.… URL directly,
as does any page using spectrl's decoder, and
from_spectrl_url reads one back here. With the default fragment binding the spectrum travels in
the part of the URL a browser keeps to itself, so sharing a link uploads nothing and leaves no copy
in the host's logs.
USI loading¶
Fetch spectra from public proteomics repositories by Universal Spectrum Identifier via the PROXI protocol. This is the one block on the page that needs network access.
from spxtacular import fetch_usi, spectrum_from_proxi_response
# or via Spectrum.from_usi(...) for the same result
spec = fetch_usi(
"mzspec:PXD000561:Adult_Frontalcortex_bRP_Elite_85_f09:scan:17555",
backend="aggregator", # or "pride", "massive", "peptideatlas", "jpost", or a full URL
timeout=30,
)
# For clients that perform the HTTP request themselves:
spec = spectrum_from_proxi_response(decoded_proxi_json, usi)
The parser preserves PROXI centroid/profile representation and scan polarity
metadata. It returns an MsnSpectrum when scan-level metadata or precursor
information is available, otherwise a plain Spectrum.
Method form:
@classmethod
def from_usi(
cls,
usi: str,
*,
backend: str = "aggregator",
timeout: float = 30,
) -> Spectrum | MsnSpectrum
JSON transport¶
Spectrum, MsnSpectrum, and Chromatogram provide versioned dictionary and
JSON round-trips for APIs, browser visualization, and cross-process messages.
The methods use only standard JSON values and require no optional dependency.
from spxtacular import Chromatogram, Spectrum, get_json_schema
spectrum_payload = spec.to_dict()
spectrum_json = spec.to_json()
restored_spec = Spectrum.from_json(spectrum_json)
chromatogram_payload = tic.to_dict()
chromatogram_json = tic.to_json()
restored_tic = Chromatogram.from_dict(chromatogram_payload)
spectrum_schema = get_json_schema("spectrum")
chromatogram_schema = get_json_schema("chromatogram")
Method forms:
def to_dict(self) -> dict[str, Any]
def to_json(self, *, indent: int | None = None) -> str
@classmethod
def from_dict(cls, payload: Mapping[str, Any]) -> Spectrum | MsnSpectrum
@classmethod
def from_json(cls, value: str | bytes | bytearray) -> Spectrum | MsnSpectrum
Compact JSON is the default; pass indent=2 for readable output. Peak columns stay in parallel
arrays, and kind records whether the original object was a Spectrum or an MsnSpectrum:
Spectrum.from_dict() dispatches to MsnSpectrum when the payload is an MSn one, while
MsnSpectrum.from_dict() requires an MSn payload. Version 1 rejects missing fields, unknown
fields, malformed arrays and non-finite numeric values instead of silently discarding data.
The spectrum envelope uses schema name spxtacular.spectrum, schema version
3 (versions 1 and 2 still load; they predate calibration and read back
with a null one), and kind spectrum or msn_spectrum. Its deconvolution
provenance block has its own schema_version 3 (versions 1 and 2, with
the old tolerance_type keys, still load), and its calibration block has
schema_version 1. The chromatogram
envelope uses schema name spxtacular.chromatogram, schema version 2
(version 1, with the old tolerance_type key, still loads), and kind
chromatogram. Unknown schema versions are rejected so consumers never
silently misinterpret a newer contract.
Peak columns are parallel arrays rather than one object per peak. Optional
arrays are explicit null values. Spectrum.from_dict() preserves the
concrete class, all MSn metadata, multiple precursors, ion mobility, charge,
isotope score, and processing provenance.
The JSON Schema documents are packaged as:
For large profile spectra, filter or decimate before transport when the browser
does not need every sample. Use .npz persistence when compact local storage
is more important than a language-neutral API representation.
Persistence (.npz)¶
Serialise spectra to / from numpy .npz archives. Arrays are stored natively;
scalar metadata is JSON-encoded under the meta key. The .npz extension is
appended automatically when missing.
from spxtacular import MsnSpectrum, Spectrum
spec.save("scan_001.npz")
restored = Spectrum.load("scan_001.npz")
msn.save("scan_001.npz")
restored_msn = MsnSpectrum.load("scan_001.npz")
Method forms:
def save(self, path: str | Path) -> None
@classmethod
def load(cls, path: str | Path) -> Spectrum
MsnSpectrum.save / MsnSpectrum.load preserve all MSn metadata (scan number,
RT, precursors, isolation window, …) in addition to the peak arrays.
Visualization¶
Every plot function takes backend="plotly" (default, returns a plotly.graph_objects.Figure),
"matplotlib" (returns a matplotlib.figure.Figure; pip install 'spxtacular[matplotlib]') or
"spec" (returns a FigureSpec), plus style="paper" | "screen" | "talk" | FigureStyle and
size="single" | "onehalf" | "double" | mm | (width_mm, height_mm). style=None means "screen"
for plotly and "paper" otherwise. An unknown backend or style raises SpxtacularError.
**layout_kwargs is plotly only.
Full documentation: Visualization
Conventions shared by every figure¶
These defaults apply to all the plotting functions below; they are described once here rather than repeated in each parameter table.
| Behaviour | Detail |
|---|---|
| Relative intensity by default | Table-driven figures (plot_spectrum, annotate_spectrum, plot_from_table) scale the y-axis so the base peak is 100% and title the axis Relative intensity (%). Pass intensity_scale="absolute" for raw counts. Tooltips always report the true intensity, whatever the scaling. |
| Optional intensity transform | intensity_transform="sqrt" or "log" compresses a range spanning orders of magnitude; the axis title is prefixed accordingly (√ relative intensity (%), log₁₀ …). |
| Labels are typeset, capped and never overlap | Ion labels are rich text (y₇²⁺, b₅−H₂O) read horizontally (label_angle, default 0). The layout places them in two dimensions, strongest peak first: a label that would collide moves up, with a leader line back to its peak, and one with no free space is dropped. max_labels (default 60) caps the count; max_labels=None removes the cap but not the collision pass. Dropped values stay in the hover text, in the plot table, and in table_view(). |
| Hovering does not require precision | Table-driven figures carry a transparent hit layer of 22px markers on the peak tips — the sticks themselves are hoverinfo="skip" — so being near a peak is enough rather than landing on a 1.6px hairline. Every figure additionally gets the m/z crosshair from the theme template (showspikes, spikemode="across", snapped to the cursor), with hoverdistance=24. |
| Autosize | "screen" plotly figures fill their container rather than a fixed pixel box; "paper" and "talk" figures have the fixed size from size=. |
| Theme | Every function takes theme_mode="light" \| "dark"; None (default) uses the module default from theme.set_plot_theme(). See Theme. |
Chromatograms and XICs¶
Chromatogram(
rt: NDArray[np.float64],
intensity: NDArray[np.float64],
*,
label: str = "",
mz: float | None = None,
tolerance: float | None = None,
tolerance_unit: str | None = None,
meta: dict = ...,
)
extract_chromatogram(
spectra: Iterable[Spectrum],
*,
mode: Literal["tic", "bpc"] = "tic",
mz_range: tuple[float, float] | None = None,
) -> Chromatogram
extract_xic(
spectra: Iterable[Spectrum],
targets: Sequence[float] | float,
*,
tolerance: float = 20.0,
tolerance_unit: Literal["ppm", "da"] = "ppm",
im_window: tuple[float, float] | None = None,
aggregate: Literal["sum", "max"] = "sum",
) -> list[Chromatogram]
extract_xic() handles every target in one pass. Chromatogram.apex_rt reports the most intense
time point and Chromatogram.total reports summed intensity. The omitted meta default is a new
empty dictionary for each object.
Extracted traces record meta["rt_unit"] as "s" when every scan has a retention time,
or "scan_index" when none do. Mixed missing and present times, or nonfinite times, raise
ValueError. Plots label scan indices explicitly and reject overlaid traces with different
axis units. total sums samples without integration over time.
The plotting wrappers are:
plot_chromatogram(
chromatograms: Chromatogram | Sequence[Chromatogram] | Iterable[Spectrum],
*,
title: str | None = None,
theme_mode: Literal["light", "dark"] | None = None,
show_apex: bool = True,
fill: bool | None = None,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
**layout_kwargs,
) -> go.Figure
plot_xic(
spectra: Iterable[Spectrum],
targets: Sequence[float] | float,
*,
tolerance: float = 20.0,
tolerance_unit: Literal["ppm", "da"] = "ppm",
im_window: tuple[float, float] | None = None,
aggregate: Literal["sum", "max"] = "sum",
title: str | None = None,
theme_mode: Literal["light", "dark"] | None = None,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
**layout_kwargs,
) -> go.Figure
Full documentation: Visualization, chromatograms and XICs
profile_centroid_plot¶
profile_centroid_plot(
profile: Spectrum,
*,
centroids: Spectrum | None = None,
title: str | None = None,
theme_mode: Literal["light", "dark"] | None = None,
max_points: int | None = 4000,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
**layout_kwargs,
) -> go.Figure
Overlays centroid sticks on the profile trace. When centroids is omitted, the function calls
profile.centroid(). Profile samples above max_points are reduced with min/max buckets.
plot_spectrum¶
plot_spectrum(
spectrum: Spectrum,
*,
title: str | None = None,
color: Literal["charge", "im"] | None = "charge",
show_scores: bool = True,
max_labels: int | None = 60,
theme_mode: Literal["light", "dark"] | None = None,
intensity_scale: Literal["absolute", "relative"] = "relative",
intensity_transform: Literal["sqrt", "log"] | None = None,
show_precursor: bool = True,
render: Literal["sticks", "profile"] | None = None,
max_points: int | None = 4000,
absolute_axis: bool = False,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
**layout_kwargs,
)
Everything after spectrum is keyword-only.
| Parameter | Default | Description |
|---|---|---|
color |
"charge" |
"charge" colours sticks by charge state on the ordinal ramp; "im" colours by ion mobility on the single-hue sequential scale with a colourbar (falls back to "charge" when no IM array is present); None renders every stick in one colour |
show_scores |
True |
Label peaks whose iso_score > 0 with their score |
max_labels |
60 |
Cap on directly drawn labels, strongest first; None for no count cap |
theme_mode |
None |
"light" / "dark"; None uses the global default |
intensity_scale |
"relative" |
"relative" (base peak = 100%) or "absolute" |
intensity_transform |
None |
None, "sqrt", or "log" |
show_precursor |
True |
On an MsnSpectrum carrying precursors, draw the precursor m/z hairline and the isolation window as recessive chrome behind the peaks |
render |
None |
Choose from spectrum_type, or explicitly force "sticks" or "profile" |
max_points |
4000 |
Profile-sample cap after min/max decimation. None draws every sample |
absolute_axis |
False |
Absolute intensities with a shared ×10ⁿ exponent in the axis title |
color="im" takes a separate rendering path that bins ion mobility into 20 steps of the sequential
scale; intensity_scale, intensity_transform, and show_precursor apply there as on the other
colour modes. Profile spectra cannot take the IM path — centroid first, or pass render="sticks"
explicitly.
Method form:
def plot(
self,
*,
title: str | None = None,
color: Literal["charge", "im"] | None = "charge",
show_scores: bool = True,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
**layout_kwargs,
)
title defaults to the spectrum type. The method takes only the parameters above, with
**layout_kwargs forwarded to plotly's update_layout; the labelling, scaling and render options
are on the function. See Visualization for style= and
size=.
annotate_spectrum¶
annotate_spectrum(
spectrum: Spectrum,
fragments,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
title: str | None = None,
peak_selection: Literal["closest", "largest", "all"] = "closest",
include_sequence: bool = False,
max_labels: int | None = 60,
theme_mode: Literal["light", "dark"] | None = None,
intensity_scale: Literal["absolute", "relative"] = "relative",
intensity_transform: Literal["sqrt", "log"] | None = None,
texture: bool = False,
show_precursor: bool = True,
peptide: str | ProFormaAnnotation | None = None,
mass_error_panel: bool = False,
absolute_axis: bool = False,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
**layout_kwargs,
)
| Parameter | Default | Description |
|---|---|---|
tolerance / tolerance_unit |
0.02 / "da" |
Matching tolerance |
peak_selection |
"closest" |
"closest", "largest", or "all" |
include_sequence |
False |
Embed the residue sequence in each label (b3{PEP} instead of b3) |
max_labels |
60 |
Cap on directly drawn ion labels |
theme_mode |
None |
"light" / "dark" |
intensity_scale / intensity_transform |
"relative" / None |
y-axis scaling, as above |
texture |
False |
Also encode ion series as a dash pattern (the non-colour channel) — for print, forced-colours modes, and readers who cannot separate two hues. Off by default because at stick density dashes add noise |
show_precursor |
True |
Draw precursor m/z + isolation window when present |
peptide |
None |
Draw the sequence above the spectrum with a tick for each observed b/y cleavage |
mass_error_panel |
False |
Add a mass-error strip below, sharing the m/z axis |
Matched peaks are coloured by ion series and labelled with a typeset form of their mzPAF identifier; unmatched peaks are drawn in grey, thinner and dimmer.
Method form:
def annotate(
self,
fragments,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
title: str | None = None,
peak_selection: Literal["closest", "largest", "all"] = "closest",
include_sequence: bool = False,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
**layout_kwargs,
)
mirror_plot¶
mirror_plot(
raw: Spectrum,
deconvoluted: Spectrum,
*,
fragments: FragmentInput | None = None,
lower_fragments: FragmentInput | None = None,
mirror_labels: Literal["auto", "both", "top"] = "auto",
names: tuple[str, str] | None = None,
similarity: Literal["cosine", "modified_cosine", "entropy"] | float | None = None,
title: str | None = None,
normalize: bool = True,
show_charges: bool = True,
show_scores: bool = True,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
max_labels: int | None = 60,
theme_mode: Literal["light", "dark"] | None = None,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
**layout_kwargs,
)
With fragments=, both halves are matched and coloured by ion series (a query/library
comparison). lower_fragments= annotates the lower half with other fragments (another peptide,
a modified form). mirror_labels="auto" (default) labels an ion shared by both halves once, on the
upper half, and repeats only the labels that differ; "both" labels both halves in full, "top"
the upper half only. names= labels the two halves. similarity= prints a score in the corner: a
method name computes it ("modified_cosine" needs a precursor m/z on both spectra, else
SpxtacularError), a number is printed as given.
The second parameter is named deconvoluted. show_charges colours the deconvoluted (upper) half
by charge state; show_scores annotates its peaks with their isotope profile score, capped by
max_labels. The raw half is drawn in the unmatched grey.
mirror_plot does not take intensity_scale, intensity_transform, or texture — its y-axis
scaling is controlled by normalize, which scales each half independently to its own maximum so the
two fill their halves symmetrically. Either way the hover reports the pre-normalisation intensity.
mass_error_plot¶
mass_error_plot(
spectrum: Spectrum,
fragments,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
unit: str = "ppm", # "ppm" or "da"
title: str | None = None,
max_labels: int | None = 60,
theme_mode: Literal["light", "dark"] | None = None,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
**layout_kwargs,
)
Bubbles are coloured by ion series from the categorical palette and labelled with their mzPAF
identifier, so a 2+ and a 1+ of the same ion do not both render as b3. max_labels caps direct
labels by peak intensity. There is no intensity_scale, intensity_transform, or texture because
the y-axis is mass error, not intensity.
Method form:
def mass_error_plot(
self,
fragments,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
unit: Literal["ppm", "da"] = "ppm",
title: str | None = None,
**layout_kwargs,
) -> Figure
Each matched fragment is a bubble whose x-position is the observed m/z, y-position is the mass error, and size is proportional to the peak intensity — useful for spotting calibration drifts or systematic mass errors.
facet_plot¶
facet_plot(
spectrum: Spectrum,
*,
fragments=None,
mirror_spectrum: Spectrum | None = None,
mirror_labels: Literal["auto", "both", "top"] = "auto",
title: str | None = None,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
include_sequence: bool = False,
unit: str = "ppm",
max_labels: int | None = 60,
theme_mode: Literal["light", "dark"] | None = None,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
**layout_kwargs,
)
Takes a single spectrum, not a list. The optional second spectrum is mirror_spectrum.
max_labels caps the ion labels in the annotated panel. Like mirror_plot and mass_error_plot,
facet_plot accepts no intensity_scale, intensity_transform, or texture; its panels are built
from plot tables at their defaults (so relative intensity), and each panel axis is titled
Intensity.
Method form:
def facet_plot(
self,
*,
fragments=None,
mirror_spectrum: Spectrum | None = None,
title: str | None = None,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
include_sequence: bool = False,
**layout_kwargs,
) -> Figure
Panel 1 is always the (optionally annotated) spectrum. Passing fragments adds a mass-error panel;
passing mirror_spectrum adds an inverted mirror panel below.
sequence_coverage_plot¶
sequence_coverage_plot(
spectrum: Spectrum,
peptide: str,
fragments,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
title: str | None = None,
theme_mode: Literal["light", "dark"] | None = None,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
**layout_kwargs,
) -> go.Figure
The coverage ladder: an annotated spectrum shows that peaks matched, this shows where along the peptide they matched — which is what tells you whether an identification is localised or leaning on one end of the molecule.
| Parameter | Default | Description |
|---|---|---|
spectrum |
The spectrum the fragments are matched against | |
peptide |
Residue sequence, one character per residue. Pass the stripped sequence — ProForma modification brackets are not rendered. Raises ValueError when empty |
|
fragments |
Fragment objects, as for match_fragments |
|
tolerance / tolerance_unit / peak_selection |
0.02 / "da" / "closest" |
Matching parameters |
title |
None |
Overrides the generated title |
theme_mode |
None |
"light" / "dark" |
Tick convention. Residues run left to right. A tick drawn above and to the left of a residue
marks an N-terminal (a/b/c) fragment that ended at that bond; a tick below and to the right
marks a C-terminal (x/y/z) fragment that started there. A bond carrying ticks on both sides is
confirmed from both directions. N-terminal ticks take the b colour, C-terminal ticks the y
colour, and both are named in the legend.
The default title reports the count of distinct bonds covered — e.g.
Sequence coverage — 17/17 backbone bonds covered (100%).
import numpy as np
import peptacular as pt
import spxtacular as spx
peptide = "FDSFGDLSSASAIMGNPK"
fragments = pt.fragment(peptide, ion_types=("b", "y"), charges=(1, 2))
# A toy spectrum: one peak per theoretical fragment.
mz = np.sort(np.array([f.mz for f in fragments]))
spectrum = spx.Spectrum(mz=mz, intensity=np.linspace(1e4, 1e5, len(mz)))
fig = spx.sequence_coverage_plot(spectrum, peptide, fragments) # note: spectrum first
print(fig.layout.title.text)
# Sequence coverage — 17/17 backbone bonds covered (100%)
reporter_ion_plot¶
reporter_ion_plot(
spectrum: Spectrum,
plex: str | IsobaricTagInfo | ReporterIons = "TMT10",
*,
tolerance: float = 20.0,
tolerance_unit: Literal["da", "ppm"] = "ppm",
impurities: ImpurityTable | pd.DataFrame | NDArray | None = None,
show_spectrum: bool = True,
normalize: bool = True,
title: str | None = None,
theme_mode: Literal["light", "dark"] | None = None,
backend="plotly", style=None, size=None,
**layout_kwargs,
)
Bars per channel from extract_reporter_ions (as % of the strongest
channel unless normalize=False), with the raw reporter region above (show_spectrum) and the
picked peaks highlighted. Missing channels are marked n.d.. A ReporterIons is plotted as is.
compose_figure¶
compose_figure(
figures: Sequence[FigureSpec],
*,
ncols: int | None = None,
labels: Sequence[str] | Literal["abc", "ABC"] | None = "abc",
size: SizeLike = None,
style: str | FigureStyle | None = None,
backend: Literal["plotly", "matplotlib", "spec"] = "matplotlib",
theme_mode: Literal["light", "dark"] | None = None,
)
Lays out several FigureSpecs (from backend="spec") as one lettered multi-panel figure at one
width and style. size=None is the double-column width, or a 16:9 slide (254 × 143 mm) for
style="talk". A panel too short for the style's text raises a UserWarning at layout. Anything
that is not a FigureSpec raises SpxtacularError.
FigureSpec / render¶
FigureSpec is the backend-neutral description every plot builds: what to draw, at what size, in
which style. backend="spec" returns one instead of a drawn figure, so layout can be inspected or
tested without a rendering engine.
FigureSpec(
cells: list[Cell],
style: FigureStyle,
theme_mode: Literal["light", "dark"],
width_mm: float,
height_mm: float,
ncols: int = 1,
layout_kwargs: dict[str, Any] = {}, # per-cell default: {}
check_panel_size: bool = False,
)
FigureSpec.panels -> list[Panel] # property
FigureSpec.resolve() -> ResolvedFigure
FigureSpec.render(backend: Literal["plotly", "matplotlib"] = "plotly") -> Any
render(spec: FigureSpec, backend: Literal["plotly", "matplotlib"] = "plotly") -> Any
spec.render(backend) and render(spec, backend) are the same call. resolve() returns the
laid-out figure in points (panel rectangles, ticks, label boxes) that both backends draw from.
FigureStyle / get_style¶
A style holds everything about a figure's geometry and type that is not colour (colour is
theme). The same style drives both backends, so a "paper" figure has 7 pt tick labels
and 0.6 pt axis lines whichever engine drew it. All sizes are in points (1/72 inch) unless the name
says otherwise.
get_style(style: Literal["paper", "screen", "talk"] | str | FigureStyle) -> FigureStyle
FigureStyle(
name: str,
width_mm: float,
aspect: float,
fonts: tuple[str, ...],
font_size: float,
axis_title_size: float,
title_size: float,
label_size: float,
panel_letter_size: float,
axis_width: float,
tick_length: float,
stick_width: float,
stick_width_context: float,
line_width: float,
leader_width: float,
grid: bool,
show_title: bool,
label_series_color: bool,
print_ink: bool,
strong_context: bool,
x_tick_spacing: float,
y_tick_spacing: float,
dpi: int,
label_gap: float,
horizontal_labels: bool,
autosize: bool = False,
)
FigureStyle.with_(**changes) -> FigureStyle # a copy with some fields changed
FigureStyle.font_family_css -> str # property: the stack as a CSS font-family
get_style accepts a preset name or a FigureStyle (returned unchanged); any other name raises
SpxtacularError. The three presets:
| Field | What it sets | "paper" |
"screen" |
"talk" |
|---|---|---|---|---|
width_mm |
Default figure width in mm | 85.0 | 238.0 | 254.0 |
aspect |
Default height as a fraction of the width | 0.62 | 0.5 | 0.5625 |
fonts |
Font stack, first available wins | Arial, Helvetica, … | Inter, system UI, … | Arial, Helvetica, … |
font_size |
Tick labels and legend | 7.0 | 8.25 | 14.0 |
axis_title_size |
Axis titles | 7.5 | 9.0 | 16.0 |
title_size |
Figure title | 8.0 | 12.0 | 20.0 |
label_size |
Ion labels and other direct annotations | 6.5 | 8.25 | 13.0 |
panel_letter_size |
Panel letters (a, b, c) | 9.0 | 11.0 | 20.0 |
axis_width |
Axis spine and tick line width | 0.6 | 0.75 | 1.25 |
tick_length |
Tick length | 2.5 | 3.0 | 5.0 |
stick_width |
Stick width for matched peaks | 0.8 | 1.2 | 2.0 |
stick_width_context |
Stick width for context (unmatched) peaks | 0.5 | 0.75 | 1.1 |
line_width |
Continuous traces (profile, chromatogram) | 0.8 | 1.05 | 2.0 |
leader_width |
Leader line from a displaced label to its peak | 0.35 | 0.5 | 0.8 |
grid |
Horizontal gridlines on the value axis | False |
True |
False |
show_title |
Draw the default title when none is passed | False |
True |
True |
label_series_color |
Colour ion labels with their series hue | True |
True |
True |
print_ink |
Dark print ink instead of recessive screen greys | True |
False |
True |
strong_context |
Darker neutral grey for context peaks | True |
False |
True |
x_tick_spacing |
Preferred tick spacing, x axis | 48.0 | 70.0 | 90.0 |
y_tick_spacing |
Preferred tick spacing, y axis | 30.0 | 40.0 | 55.0 |
dpi |
Raster resolution for PNG export | 600 | 192 | 200 |
label_gap |
Gap between a peak tip and its label | 1.2 | 2.0 | 2.5 |
horizontal_labels |
Horizontal ion labels, else rotated | True |
True |
True |
autosize |
Plotly only: let the figure fill its container | False |
True |
False |
save_figure¶
save_figure(fig, path: str | Path, *, scale: float | None = None, dpi: float | None = None, **kwargs) -> Path
| Parameter | Default | Description |
|---|---|---|
fig |
A plotly figure, a matplotlib figure or a FigureSpec (drawn with matplotlib when installed, else plotly; .html always plotly) |
|
path |
Destination; the suffix picks the writer | |
scale |
None |
Plotly rasters: device pixel ratio. Overrides dpi |
dpi |
None |
Raster resolution; defaults to the style's dpi (600 for "paper") |
**kwargs |
Forwarded to write_html / write_image / savefig |
| Figure | Suffixes | Extra install |
|---|---|---|
| plotly | .html or none (.html is appended) |
none |
| plotly | .png, .svg, .pdf, .jpg, .jpeg, .webp |
pip install 'spxtacular[plotly-export]' (kaleido); missing raises ImportError. kaleido drives a Chrome or Chromium browser and downloads none: without one the export raises RuntimeError naming plotly_get_chrome |
| matplotlib | .pdf, .svg, .eps, .png, .jpg, .jpeg, .tif, .tiff, .webp |
none; PDF/SVG embed fonts as TrueType |
| any | anything else | raises SpxtacularError |
Returns the path actually written.
import numpy as np
import spxtacular as spx
spectrum = spx.Spectrum(mz=np.array([100.0, 200.0]), intensity=np.array([10.0, 40.0]))
path = spx.save_figure(spx.plot_spectrum(spectrum), "spectrum") # -> Path('spectrum.html')
Theme¶
spxtacular.theme is the single source of truth for plot colour — both plot_table.py and
visualization.py read from it, so a palette change lands on every figure at once rather than being
kept in sync by comment. Every plotting function's theme_mode argument selects the mode for one
figure; theme.set_plot_theme() sets the default for all of them.
Colour is assigned by job, not by taste¶
| Job | Encoding | Lookup |
|---|---|---|
| Fragment ion series | Nominal categorical — eight fixed hues in the fixed slot order b, y, a, c, x, z, p, i |
ion_color |
| Charge state | Ordinal — one hue, running light → dark as charge rises, so the reader sees 1+ < 2+ < 3+ in the colour | charge_color |
Continuous magnitude — ion mobility (plot_spectrum(color="im")), and any per-peak score you colour yourself |
Sequential — one hue, light → dark, with a colourbar. Not Viridis: a multi-hue ramp invents banding that is not in the data | sequential_scale |
| Unmatched peaks | Recessive grey, also thinner and dimmer — unmatched peaks are context, not subject | unmatched_color |
Three consequences worth knowing:
- Ion hues never cycle. Slots are assigned in order and stop at eight. Anything not in the eight
slots — including internal fragments, whose ion types are two letters like
"by"— folds toneutral_color()rather than being handed a ninth hue that would collide with an existing series.bandytake the first two slots because they are by far the most common pair, so the pair that co-occurs most often is the most separable. - The charge ramp clamps, it does not wrap. The shipped ramp has five steps, and charges past
its end all take the far end:
charge_color(11) == charge_color(5). The previous 10-colour cycle renderedz=1andz=11in identical colours, which is the one failure an ordinal encoding must not have.charge <= 0— singletons (-1) and decharged peaks (0) — is neutral grey: absence of identity, not another category. - Dark mode is not an inversion. The dark charge ramp runs dark → light so it stays legible against the dark surface, and the sequential scale is reversed to match.
Functions¶
| Function | Signature | Returns |
|---|---|---|
set_plot_theme |
(mode: ThemeMode) -> None |
Sets the default mode for every subsequent plot. ValueError on anything but "light" / "dark" |
resolve_mode |
(theme: ThemeMode \| None = None) -> ThemeMode |
The effective mode — the argument if given, otherwise the global default |
set_palette |
(*, categorical=None, charge_ramp=None, sequential=None) -> None |
Replaces a palette wholesale (see below) |
ion_color |
(ion_type: str, theme=None) -> str |
Hex colour for a fragment series; neutral for anything outside the eight slots |
charge_color |
(charge: int, theme=None) -> str |
Hex colour from the ordinal ramp; clamped at the end, neutral for charge <= 0 |
ion_dash |
(ion_type: str) -> str |
Plotly dash pattern for a series — the texture channel used by texture=True. Mode-independent, so it takes no theme |
sequential_scale |
(theme=None) -> list[list] |
Plotly colourscale for continuous magnitude — [[stop, hex], …], five stops |
surface |
(theme=None) -> str |
Chart surface (paper and plot background) |
text_color |
(level: Literal["primary","secondary","muted"] = "secondary", theme=None) -> str |
Ink. Labels never wear the series colour — identity comes from the mark |
unmatched_color |
(theme=None) -> str |
Colour for peaks carrying no annotation |
marker_outline |
(theme=None) -> str |
Hairline outline for filled marks such as mass-error bubbles; flips with the mode so bubbles stay separated on a dark surface |
neutral_color |
(theme=None) -> str |
Colour for singletons and any category past the eighth slot |
template |
(theme=None) -> go.layout.Template |
The plotly template: recessive chrome, horizontal gridlines only, m/z crosshair, autosize |
apply |
(fig: go.Figure, theme=None) -> go.Figure |
Applies that template to an existing figure in place and returns it |
ThemeMode is the type alias for the mode: Literal["light", "dark"].
Note the naming: inside theme the mode argument is called theme (ion_color("b", theme="dark")),
while the plotting functions call the same thing theme_mode — there, theme would shadow the
module.
import plotly.graph_objects as go
from spxtacular import theme
theme.set_plot_theme("dark") # global default for every subsequent figure
theme.ion_color("b") # '#3987e5' (dark-mode slot 0)
theme.ion_color("by") # neutral — internal fragments get no hue of their own
theme.ion_color("y", theme="light") # '#eb6834' — one-off override, global default untouched
theme.charge_color(11) == theme.charge_color(5) # True — the ramp clamps
theme.charge_color(-1) == theme.neutral_color() # True — singletons are not a category
fig = theme.apply(go.Figure()) # borrow the template for your own figure
theme.set_plot_theme("light")
set_palette¶
theme.set_palette(
*,
categorical: dict[ThemeMode, list[str]] | None = None, # >= 8 hues per mode
charge_ramp: dict[ThemeMode, list[str]] | None = None,
sequential: dict[ThemeMode, list[list]] | None = None,
) -> None
Each argument takes a {"light": [...], "dark": [...]} mapping and replaces that palette in both
modes. categorical and charge_ramp take lists of hex strings; sequential takes a plotly
colourscale, [[0.0, "#…"], …, [1.0, "#…"]]. ValueError is raised when a mapping is missing a
mode, or when a categorical palette has fewer entries than there are ion slots (8).
Substituted palettes are not validated for colour-vision deficiency. The shipped palettes were checked with a CVD validator (protanopia and deuteranopia, Machado-Oliveira-Fernandes at severity 1.0) against both surfaces. A palette you pass to
set_paletteis not checked — the only validation is the structural one above (both modes present, at least 8 categorical hues). Validate your own hues before relying on them, or you lose the property the defaults were chosen for. Categorical hues want a fixed order with adjacent pairs kept far apart; a charge ramp wants a single hue with monotone lightness.
from spxtacular import theme
theme.set_palette(
categorical={
"light": ["#2a78d6", "#eb6834", "#1baf7a", "#eda100",
"#e87ba4", "#008300", "#4a3aa7", "#e34948"],
"dark": ["#3987e5", "#d95926", "#199e70", "#c98500",
"#d55181", "#008300", "#9085e9", "#e66767"],
},
charge_ramp={
"light": ["#86b6ef", "#5598e7", "#2a78d6", "#1c5cab", "#104281"],
"dark": ["#184f95", "#256abf", "#3987e5", "#6da7ec", "#9ec5f4"],
},
)
Utilities¶
da_to_ppm(delta: float, mz: float) -> float # delta / mz * 1e6
ppm_to_da(delta_ppm: float, mz: float) -> float # delta_ppm * mz / 1e6
Convert a mass difference between Dalton and ppm at a given reference mz. Both take the
difference first and the reference m/z second.
from spxtacular import da_to_ppm, ppm_to_da
da_to_ppm(0.01, 500.0) # 20.0 ppm
ppm_to_da(20.0, 500.0) # 0.01 Da
Errors¶
Every input the library rejects raises SpxtacularError: an unknown enum member, a tolerance unit
other than "da" or "ppm", a polarity that is not lowercase "positive" or "negative", an
unknown style or backend, an unsupported figure suffix, a malformed mzSpecLib or mzPAF document.
Because it subclasses ValueError, except ValueError already catches it.
Matching and scoring¶
Full documentation: Fragment matching and scoring
match_fragments¶
match_fragments(
spectrum: Spectrum,
fragments,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
is_monoisotopic: bool = True,
) -> list[MatchedFragment]
When fragments is a dict[tuple[IonType, int], list[float]] (the output of
peptacular.ProFormaAnnotation.fast_fragment), is_monoisotopic is forwarded
to the Fragment constructor; otherwise it has no effect. Returns a list sorted
by ascending peak_index.
Method form:
def match_fragments(
self,
fragments,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
is_monoisotopic: bool = True,
) -> list[MatchedFragment]
MatchedFragment¶
One fragment-to-peak match. Frozen, slotted and keyword-only; built by match_fragments, not by
hand.
MatchedFragment(
*,
fragment: Fragment, # the matched peptacular Fragment
peak_index: int, # index into spectrum.mz / spectrum.intensity
peak_mz: float,
peak_intensity: float,
intensity_pct: float, # peak_intensity / total intensity * 100
ppm_error: float, # signed: (peak_mz - theoretical_mz) / theoretical_mz * 1e6
da_error: float, # signed: peak_mz - theoretical_mz
)
Field descriptions: Matching and scoring — match_fragments().
score¶
score(
spectrum: Spectrum,
fragments,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
predicted_intensities: Sequence[float] | None = None,
) -> dict[str, float]
Returns a dict of PSM metrics: hyperscore, probability_score, total_matched_intensity, matched_fraction, intensity_fraction, mean_ppm_error, spectral_angle, longest_run. When predicted_intensities is supplied, it must contain one value per fragment in the same order and enables the literature spectral-angle metric.
Method form:
def score(
self,
fragments,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
predicted_intensities: Sequence[float] | None = None,
) -> dict[str, float]
fragmentation_preset_name¶
fragmentation_preset_name(activation: ActivationType | str | None) -> str | None
The peptacular fragmentation preset name for an activation method: a key of peptacular.FRAGMENTATION_PRESETS, or None when there is no sensible preset.
activation may be an ActivationType, a member name in any case, or a PSI-MS
dissociation-method accession (what a reader hands over before MsnSpectrum normalises it).
| Activation method | Preset | Why |
|---|---|---|
CID, HCD, ETD, ECD, EAD, ETHCD, UVPD |
cid, hcd, etd, ecd, ead, ethcd, uvpd |
The preset is named for the method |
ETCID |
ethcd |
Electron transfer with supplemental collisional activation adds the same b and y ions to c and z.; the activation energy differs, the series do not |
PQD, SID, IRMPD, BIRD, SORI |
cid |
Collisional or slow-heating activation: b and y, as in CID |
PASEF |
hcd |
Bruker PASEF fragments by beam-type CID |
NETD, PD, anything else, None |
None |
NETD cleaves to a and x ions, which no preset covers; PD names neither a wavelength nor a series; a vendor string that names no member is unknown, not guessed |
A preset is a default for the series a method usually gives, not a measurement about one
spectrum: the real series depend on the instrument, the energy and the peptide. The ion series,
the neutral losses and the literature behind each preset belong to peptacular, which owns
FRAGMENTATION_PRESETS; this function only picks the name.
localize¶
localize(
spectrum: Spectrum,
peptide: str | ProFormaAnnotation,
*,
ion_types: Sequence[IonTypeLike] | Literal["auto"] = ("b", "y"),
charges: Sequence[int] = (1,),
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_depths: Sequence[int] = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
window: float = 100.0,
max_isomers: int | None = 10_000,
) -> LocalizationResult
PTM site localization by Ascore (Beausoleil et al. 2006). The candidate placements come from peptide's ProForma ambiguity (a #label group, a range, or an unknown position), through peptacular's localization_isomers. See the PTM site localization guide for the method and its validation.
| Parameter | Meaning |
|---|---|
spectrum |
A centroided spectrum in m/z. A decharged or profile spectrum raises |
peptide |
ProForma string or peptacular annotation whose modification positions are ambiguous; one candidate is allowed and gives no AScore |
ion_types, charges |
Fragment ions to generate, as for match_fragments. Full-length ions are dropped: they are the same mass for every placement. ion_types="auto" takes the series from the fragmentation preset for the spectrum's own activation_type (see fragmentation_preset_name); charges is never taken from the preset, and no neutral losses are generated either way |
tolerance, tolerance_unit |
Match tolerance, which also sets the random-match probability depth * 2 * tolerance_in_da / window |
peak_depths |
Peak depths to score. The paper's ten by default, and only that set uses the paper's weights; any other set is weighted uniformly |
window |
Width in Da of the peak-depth window (the paper's 100 Da) |
max_isomers |
Passed to peptacular; more candidates than this raises |
LocalizationResult (frozen dataclass, to_dict() / from_dict() at schema_version 1):
| Field | Type | Meaning |
|---|---|---|
isomers |
tuple[str, ...] |
Every candidate, in peptacular's fixed order |
best, runner_up |
str, str \| None |
Top and second candidate by peptide score |
ascore |
float \| None |
Best against runner-up in -10 log10 P; None with one candidate, 0.0 with no site-determining evidence |
peptide_scores |
tuple[float, ...] |
Weighted peptide score per candidate, in isomers order |
peak_depth |
int |
The depth the AScore was computed at |
site_determining |
tuple[tuple[int, int], ...] |
(matched, available) per candidate at peak_depth, against the best other candidate |
provenance |
LocalizationProvenance |
Every argument above, plus method and schema_version |
is_ambiguous(cut=ASCORE_CONFIDENT_CUT) is True when ascore is below cut; ASCORE_CONFIDENT_CUT is the paper's 19, and ASCORE_PEAK_DEPTHS is its ten depths.
recalibrate¶
recalibrate(
spectrum: Spectrum,
matches: Sequence[MatchedFragment],
*,
model: Literal["offset", "linear"] = "offset",
estimator: Literal["median", "least_squares"] = "median",
min_matches: int = 8,
min_mz_span: float = 200.0,
max_abs_ppm: float = 50.0,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
inplace: bool = False,
) -> Spectrum
Corrects a spectrum's m/z axis from the signed ppm errors its matched fragments already carry, and applies the fit to every peak as mz / (1 + ppm(mz) * 1e-6). One pass: there is no refit-and-rematch loop. See the m/z recalibration guide.
| Parameter | Meaning |
|---|---|
spectrum |
The spectrum the matches came from, still in m/z. A decharged spectrum raises |
matches |
Matched fragments from match_fragments |
model |
"offset" fits ppm = a; "linear" fits ppm = a + b * mz, by least squares |
estimator |
"median" (the default) takes the median signed error; "least_squares" takes the mean. model="linear" requires "least_squares" |
min_matches |
Minimum matched fragments, and minimum distinct matched peaks |
min_mz_span |
Minimum matched m/z span for model="linear" only |
max_abs_ppm |
Largest correction allowed anywhere in the spectrum's m/z range |
tolerance, tolerance_unit |
The matching tolerance the matches came from; recorded in the provenance, it does not change the fit |
inplace |
Modify and return spectrum instead of a new one |
CalibrationProvenance (frozen dataclass, to_dict() / from_dict() at schema_version 1), on the returned spectrum's calibration:
| Field | Type | Meaning |
|---|---|---|
model, estimator |
str |
As passed |
offset_ppm |
float |
The fitted intercept, in ppm |
slope_ppm_per_mz |
float \| None |
The fitted slope in ppm per Th; None for model="offset" |
n_matches, n_unique_peaks |
int |
Matched fragments, and the distinct peaks they occupy |
mz_span |
tuple[float, float] |
(min, max) observed m/z of the matches |
residual_ppm_sd, residual_ppm_mad |
float |
Spread left after the correction: sample SD, and median absolute deviation |
tolerance, tolerance_unit |
float, str |
The matching tolerance, as passed |
previous |
CalibrationProvenance \| None |
The spectrum's earlier record, so a second recalibrate() keeps the total auditable |
correction_ppm(mz) returns the correction this record applies at a given m/z.
Spectrum similarity¶
cosine(
query: Spectrum,
reference: Spectrum,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
transform: Literal["sqrt", "linear", "log"] = "sqrt",
) -> float
modified_cosine(
query: Spectrum,
reference: Spectrum,
query_precursor_mz: float,
reference_precursor_mz: float,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
transform: Literal["sqrt", "linear", "log"] = "sqrt",
) -> float
entropy_similarity(
query: Spectrum,
reference: Spectrum,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
) -> float
All three return values in [0, 1], accept unsorted spectra, and use one-to-one peak matching.
modified_cosine() also considers the precursor-mass displacement. Full documentation:
Spectrum-to-spectrum similarity.
Isobaric reporter ions¶
Full documentation: Isobaric reporter ions
extract_reporter_ions(
spectrum: Spectrum,
plex: str | IsobaricTagInfo, # "TMT10", "TMTpro18", "iTRAQ4", ...
*,
tolerance: float = 20.0,
tolerance_unit: Literal["da", "ppm"] = "ppm",
impurities: ImpurityTable | pd.DataFrame | NDArray | None = None,
normalize: Literal["sum", "max"] | None = None,
) -> ReporterIons # also Spectrum.reporter_ions(plex, ...)
reporter_ion_table(
spectra: Iterable[Spectrum] | Reader,
plex: str | IsobaricTagInfo,
*,
tolerance: float = 20.0,
tolerance_unit: Literal["da", "ppm"] = "ppm",
impurities: ImpurityTable | pd.DataFrame | NDArray | None = None,
normalize: Literal["sum", "max"] | None = None,
ms_level: int | None = None,
include_errors: bool = False,
) -> pd.DataFrame
isotope_correction_matrix(plex, impurities) -> NDArray # observed = M @ true
correct_isotope_impurities(intensities, correction, *, plex=None) -> NDArray
ReporterIons (frozen, read-only arrays in channel order): plex, channels, reporter_mz,
intensity, raw_intensity, observed_mz, corrected, normalize, and the properties
found, mz_error (Da), ppm_error; ions["127N"] gives one channel; to_dict().
The most intense peak in each window is used; a missing channel is intensity 0.0 and
observed_mz NaN. A bad plex, unit, tolerance (overlapping windows) or impurity table, a
decharged spectrum, or NaN/inf intensities raise SpxtacularError. Numeric impurity shifts
are 13C counts; label 15N impurities "-15N". See Scoring.
Diagnostic ions¶
find_diagnostic_ions(
spectrum: Spectrum,
ions: Sequence[str] | None = None, # mzPAF names: "r[TMT126]", "IY"; None = DIAGNOSTIC_IONS
*,
tolerance: float = 20.0,
tolerance_unit: Literal["da", "ppm"] = "ppm",
) -> DiagnosticIons
DIAGNOSTIC_IONS is 94 names: r[<name>] for the 71 reference molecules in tacular's
REFMOL_LOOKUP, then I<aa> for the 23 residues with a positive monoisotopic mass. Glycan
oxonium ions ("r[HexNAc]") are not in it; pass them in ions. m/z comes from
paftacular.parse(name).mz().
DiagnosticIons (frozen, read-only arrays in ions order): ions, ion_mz, intensity,
observed_mz, found, and present(), the names found. The most intense peak in each window
is used; a missing ion is intensity 0.0, observed_mz NaN and found False. Names that share an
m/z all report, and overlapping windows do not raise. An empty ions, a name that does not
resolve, a bad unit or tolerance, a decharged spectrum, or NaN/inf intensities raise
SpxtacularError.
Plot table API¶
Provides an intermediate pandas.DataFrame that holds all data and visual properties for a spectrum
plot. Users can freely modify the DataFrame before passing it to plot_from_table. pandas is a
required dependency, so this API is always available.
Worked examples: Spectrum guide — Figures
Table schema¶
Both builders return the same columns, in this order:
mz, intensity, intensity_abs, charge, score, im,
color, linewidth, opacity, dash, series,
label, label_size, label_color, label_angle,
hover
| Column | dtype | Read by plot_from_table? |
Meaning |
|---|---|---|---|
mz |
float64 |
yes | Peak m/z |
intensity |
float64 |
yes | The plotted value — relative-scaled (base peak = 100) unless intensity_scale="absolute", then transformed if intensity_transform was given |
intensity_abs |
float64 |
no | The true intensity, always unscaled. This is what the tooltips report and what table_view(max_rows=…) ranks by |
charge |
Int64 (nullable; pd.NA when the spectrum has no charge array) |
no | Charge state |
score |
float64 (NaN when absent) |
no | iso_score |
im |
float64 (NaN when absent) |
no | Ion mobility |
color |
str |
yes | Hex colour, from theme |
linewidth |
float |
yes, from the first row of each group | Relative stick weight, matched heavier than unmatched; the style scales it |
opacity |
float |
yes, from the first row of each group | Matched peaks opaque, unmatched dimmer |
dash |
str |
yes, from the first row of each group (only when not "solid") |
Texture channel — set per ion series when texture=True |
series |
str |
yes | Trace name and grouping key |
label |
str |
yes | Direct label; "" for peaks whose label was capped or collided away |
label_size |
float64 |
yes | Label size in pt; NaN (default) uses the style's label size |
label_color |
str |
yes | Label colour |
label_angle |
float64 |
yes | Label rotation in degrees. Defaults to 0 (horizontal); -90 reads bottom-to-top |
hover |
str |
yes | Tooltip text, baked in by the builder — to change a tooltip edit hover itself, not the value behind it |
table.attrs["intensity_label"] carries the y-axis title that matches the scaling applied
("Intensity", "Relative intensity (%)", "√ relative intensity (%)", "log₁₀ …").
plot_from_table reads it, so a rescaled table titles its own axis.
Because intensity and intensity_abs are separate, tooltips are unaffected by rescaling: change
intensity_scale and the axis changes, never the number the reader is told.
series values:
| Table | series values |
|---|---|
build_plot_table with charge data |
"z=1", "z=2", … plus "singleton" (charge == -1) and "decharged" (charge == 0) |
build_plot_table without charge data, or show_charges=False |
"peaks" |
build_annot_plot_table |
the ion type of the matched fragment ("b", "y", …), or "unmatched" |
build_plot_table¶
build_plot_table(
spectrum: Spectrum,
*,
show_charges: bool = True,
show_scores: bool = True,
max_labels: int | None = 60,
theme_mode: Literal["light", "dark"] | None = None,
intensity_scale: Literal["absolute", "relative"] = "relative",
intensity_transform: Literal["sqrt", "log"] | None = None,
) -> pd.DataFrame
| Parameter | Default | Description |
|---|---|---|
show_charges |
True |
Colour peaks by charge state on the ordinal ramp and set series to "z=N" / "singleton" / "decharged" |
show_scores |
True |
Label peaks whose iso_score > 0 with their score |
max_labels |
60 |
Cap on labels kept non-empty, strongest first, after the collision pass |
theme_mode |
None |
"light" / "dark" — decides the hex values written into color and label_color |
intensity_scale |
"relative" |
Scaling written into intensity (intensity_abs is unaffected) |
intensity_transform |
None |
None, "sqrt", or "log" |
Plain spectra have no texture parameter because they have no ion series to distinguish. Their
dash column is always "solid" unless the caller edits it.
Method form:
def plot_table(
self,
*,
show_scores: bool = True,
color: Literal["charge"] | None = "charge",
) -> pd.DataFrame
build_annot_plot_table¶
build_annot_plot_table(
spectrum: Spectrum,
fragments,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
include_sequence: bool = False,
max_labels: int | None = 60,
theme_mode: Literal["light", "dark"] | None = None,
intensity_scale: Literal["absolute", "relative"] = "relative",
intensity_transform: Literal["sqrt", "log"] | None = None,
texture: bool = False,
) -> pd.DataFrame
Same trailing parameters as build_plot_table, and here texture=True does have an effect: each
matched peak's dash is set from theme.ion_dash(ion_type). When one peak matches several ions,
the colour and series are chosen by the fixed ion slot order rather than by input order, so
reordering the fragment list never silently repaints the plot; the label lists every matching ion,
joined by <br>.
Method form:
def annot_plot_table(
self,
fragments,
*,
tolerance: float = 0.02,
tolerance_unit: Literal["da", "ppm"] = "da",
peak_selection: Literal["closest", "largest", "all"] = "closest",
include_sequence: bool = False,
) -> pd.DataFrame
plot_from_table¶
plot_from_table(
table: pd.DataFrame,
*,
title: str | None = None,
theme_mode: Literal["light", "dark"] | None = None,
render: Literal["sticks", "profile"] | None = None,
max_points: int | None = 4000,
backend: Literal["plotly", "matplotlib", "spec"] = "plotly",
style: str | FigureStyle | None = None,
size: SizeLike = None,
absolute_axis: bool = False,
**layout_kwargs,
)
Draws one stick (or profile) mark per unique (series, color) group, a transparent hover layer
(plotly), and one label per row with a non-empty label, placed without overlap. render=None uses
table.attrs["render"], falling back to sticks. Profile rendering applies min/max decimation above
max_points, or draws every sample when it is None.
The required columns are validated up front — a missing one raises
SpxtacularError: plot table is missing required column(s): … immediately, rather than part-way through
rendering or only on data that happens to carry labels:
intensity_abs, dash, and label_angle are not required (a missing label_angle draws
horizontal labels), so a table built by an older version still renders.
Grouping keeps NA keys (dropna=False): a row whose series or color came back NA — easy to
produce with merge / reindex / concat on a hand-edited table — is drawn in the unmatched
colour under the series name "unlabelled" instead of silently vanishing from the figure.
The legend is shown only when the table holds more than one series.
table_view¶
table_view(
table: pd.DataFrame,
*,
max_rows: int | None = None,
annotated_only: bool = False,
) -> str
Renders a plot table as an accessible HTML <table> string — the companion to the figure, not a
replacement for it. It exists because a tooltip should enhance, never gate: label capping
deliberately drops labels off the figure, and hovering is unusable for keyboard and screen-reader
users, so every value needs a non-hover route.
| Parameter | Default | Description |
|---|---|---|
table |
A table from build_plot_table or build_annot_plot_table |
|
max_rows |
None |
Keep only this many most-intense peaks (ranked on intensity_abs); None keeps all |
annotated_only |
False |
Keep only peaks carrying a label — useful beside an annotated spectrum, where unmatched peaks are context rather than results |
Rows are emitted in m/z order. The columns are m/z and Intensity (the true intensity from
intensity_abs), plus z, Score, and Ion mobility when those columns hold any non-NA value,
plus Annotation when any label is present. Label text is HTML-escaped, and the <br> separators
the plot uses between co-matching ions become commas.
import numpy as np
import peptacular as pt
import spxtacular as spx
peptide = "FDSFGDLSSASAIMGNPK"
fragments = pt.fragment(peptide, ion_types=("b", "y"), charges=(1, 2))
# A toy spectrum: one peak per theoretical fragment.
mz = np.sort(np.array([f.mz for f in fragments]))
spectrum = spx.Spectrum(mz=mz, intensity=np.linspace(1e4, 1e5, len(mz)))
table = spx.build_annot_plot_table(spectrum, fragments)
print(table.attrs["intensity_label"]) # Relative intensity (%)
html = spx.table_view(table, max_rows=3, annotated_only=True)
print(html)
# <table><caption>Peak list</caption>…