API Reference

Annotation

class paftacular.annotation.CommonAnnotationParams[source]

Bases: TypedDict

Common parameters shared across all annotation factory methods

adducts: list[Adduct | str] | None
analyte_reference: int | None
charge: int
confidence: float | None
is_auxiliary: bool
isotopes: list[IsotopeSpecification | str | int] | None
mass_error: float | None
mass_error_unit: Literal['da', 'ppm']
neutral_losses: list[NeutralLoss | str] | None
class paftacular.annotation.PafAnnotation(ion_type, *, analyte_reference=None, is_auxiliary=False, neutral_losses=(), isotopes=(), adducts=(), charge=1, mass_error=None, confidence=None, resolved_sequence=None)[source]

Bases: object

Fragment ion annotation following mzPAF specification.

charge is any nonzero integer. A negative charge means a deprotonated (negative mode) ion: without adducts it removes abs(charge) protons, and mz() divides by abs(charge).

Parameters:
adducts: tuple[Adduct, ...]
analyte_reference: int | None
charge: int
comp(*, calculate_sequence=True)[source]

Calculate the elemental composition of the annotated ion including modifications

Return type:

Counter[ElementInfo]

Parameters:

calculate_sequence (bool)

confidence: float | None
formula(*, calculate_sequence=True)[source]

Get the chemical formula string of the annotated ion

Return type:

str

Parameters:

calculate_sequence (bool)

static from_dict(data)[source]

Validate and reconstruct a versioned structured representation.

Return type:

PafAnnotation

Parameters:

data (Mapping[str, object])

get_mass(*, monoisotopic=True, calculate_sequence=True)[source]

Calculate the charged-species mass of the annotated ion including modifications.

Without an embedded or resolved sequence, peptide, internal and precursor ions give only the ion offset plus modifiers. Pass calculate_sequence=False to get that offset even when a sequence is present.

Return type:

float

Parameters:
  • monoisotopic (bool)

  • calculate_sequence (bool)

ion_type: PeptideIon | InternalFragment | ImmoniumIon | ReferenceIon | NamedCompound | ChemicalFormula | SMILESCompound | UnknownIon | PrecursorIon
is_auxiliary: bool
isotopes: tuple[IsotopeSpecification, ...]
static make_formula(formula, **kwargs)[source]

Create a PafAnnotation for a chemical formula

Return type:

PafAnnotation

Parameters:
static make_immonium(amino_acid, *, modification=None, **kwargs)[source]

Create a PafAnnotation for an immonium ion

Return type:

PafAnnotation

Parameters:
static make_internal(start_position, end_position, *, ion_type='by', sequence=None, **kwargs)[source]

Create a PafAnnotation for an internal fragment

Return type:

PafAnnotation

Parameters:
static make_named_compound(name, **kwargs)[source]

Create a PafAnnotation for a named compound

Return type:

PafAnnotation

Parameters:
static make_peptide(ion_type, position, *, sequence=None, **kwargs)[source]

Create a PafAnnotation for a peptide fragment ion

Return type:

PafAnnotation

Parameters:
static make_precursor(**kwargs)[source]

Create a PafAnnotation for the precursor ion

Return type:

PafAnnotation

Parameters:

kwargs (Unpack[CommonAnnotationParams])

static make_reference(name, **kwargs)[source]

Create a PafAnnotation for a reference ion

Return type:

PafAnnotation

Parameters:
static make_smiles(smiles, **kwargs)[source]

Create a PafAnnotation for a SMILES compound

Return type:

PafAnnotation

Parameters:
static make_unknown(*, label=None, **kwargs)[source]

Create a PafAnnotation for an unknown/unannotated ion

Return type:

PafAnnotation

Parameters:
mass_error: MassError | None
mz(*, monoisotopic=True)[source]

Calculate the m/z of the annotated ion.

Peptide, internal and precursor ions need a sequence (embedded or from resolve()). Without one only the ion offset is known, so this raises PaftacularError.

Return type:

float

Parameters:

monoisotopic (bool)

neutral_losses: tuple[NeutralLoss, ...]
static parse(annotation_str)[source]

Parse a single mzPAF annotation string into a FragmentAnnotation object

Return type:

PafAnnotation

Parameters:

annotation_str (str)

property peptacular_ion_type: IonType | None

Map to peptacular IonType if applicable, else None

proforma_formula(*, calculate_sequence=True)[source]

Get the ProForma-style chemical formula string of the annotated ion

Return type:

str

Parameters:

calculate_sequence (bool)

resolve(analytes)[source]

Resolve this peptide, internal, or precursor ion against analyte context.

Return type:

PafAnnotation

Parameters:

analytes (str | Mapping[int, str])

resolved_sequence: str | None
property sequence: str | None

Get the peptide sequence if applicable, else None

serialize(*, include_sequence=True, signed_charge=True)[source]

Serialize the annotation back to mzPAF string format.

A negative charge is written as ^-n by default so the text round trips. mzPAF 1.0.1 section 4.8 says the charge MUST NOT include the minus sign (negative mode is a property of the spectrum), so pass signed_charge=False to write only the magnitude.

Return type:

str

Parameters:
  • include_sequence (bool)

  • signed_charge (bool)

to_dict()[source]

Export the versioned, reversible structured representation.

Return type:

dict

Parser

mzPAF text parsing: parse, parse_multi and iter_parse.

class paftacular.parser.ParseResult(index, text, annotations=(), error=None)[source]

Bases: object

One input record and either its annotations or a structured error.

Parameters:
annotations: tuple[PafAnnotation, ...]
error: PafParseError | None
index: int
property ok: bool
text: str
paftacular.parser.iter_parse(records)[source]

Parse records lazily, retaining one error per failed input record.

Return type:

Iterator[ParseResult]

Parameters:

records (Iterable[str])

paftacular.parser.parse(annotation_str)[source]

Parse exactly one mzPAF annotation.

Raises PafParseError when the text holds zero or several annotations. Use parse_multi() for comma-separated input.

Return type:

PafAnnotation

Parameters:

annotation_str (str)

paftacular.parser.parse_multi(annotation_str)[source]

Parse annotations separated by commas outside labels and sequences.

Returns an empty list for empty or blank input. Raises PafParseError.

Return type:

list[PafAnnotation]

Parameters:

annotation_str (str)

Resolution and Errors

paftacular.resolution.resolve(annotation, analytes)[source]

Attach the fragment sequence selected from a full ProForma analyte.

Mapping keys are mzPAF analyte references. An omitted reference selects 1. The returned annotation retains context in to_dict(), but not in mzPAF text.

Return type:

PafAnnotation

Parameters:

Exceptions raised by paftacular.

Every error caused by user input is a PaftacularError, which is a ValueError.

exception paftacular.errors.PafParseError(text, position, annotation_index, reason)[source]

Bases: PaftacularError

An mzPAF error with zero-based character and annotation positions.

Parameters:
  • text (str)

  • position (int)

  • annotation_index (int)

  • reason (str)

exception paftacular.errors.PafUnknownReferenceError(name, reason=None)[source]

Bases: PaftacularError, KeyError

A reference molecule name that is not in the mzPAF reference list or Unimod.

Raised when calculating an r[...] ion or a -[...] loss. It is a PaftacularError (so a ValueError) and also a KeyError.

Parameters:
  • name (str)

  • reason (str | None)

exception paftacular.errors.PafUnsupportedCalculationError[source]

Bases: PaftacularError

A mass or composition that the annotation does not define.

Raised for ? (unannotated) and _{...} (named compound) ions, which carry no chemistry.

exception paftacular.errors.PaftacularError[source]

Bases: ValueError

Base class for paftacular errors: invalid annotations, components or calculations.

paftacular.errors.reraise_as_paftacular(func)[source]

Re-raise a ValueError from tacular or peptacular as a PaftacularError.

peptacular parses sequences and modifications lazily, so its errors fire inside mass and composition calls, not where the text is first read. Wrap those calls with this.

Return type:

Callable[[ParamSpec(P)], TypeVar(R)]

Parameters:

func (Callable[[P], R])

Structured Interchange

Version 1 interchange data: to_dict() and from_dict().

paftacular.serialization.from_dict(data)[source]

Reject unknown fields and invalid types before constructing components.

Return type:

PafAnnotation

Parameters:

data (Mapping[str, object])

paftacular.serialization.to_dict(annotation)[source]

Return JSON-compatible component data with an explicit schema version.

Return type:

dict

Parameters:

annotation (PafAnnotation)

Annotation Types

class paftacular.comps.Adduct(count, base_formula)[source]

Bases: Serializable, ScalableComposition, MassProvider

Represents a charge-carrier adduct such as +Na or +2H

Parameters:
  • count (int)

  • base_formula (str)

base_formula: str
count: int
property formula: str
static parse(s)[source]

Parse a single adduct string like ‘+H’, ‘+2Na’, ‘-NH4’

Return type:

Adduct

Parameters:

s (str)

property proforma_formula: str
serialize()[source]
Return type:

str

class paftacular.comps.ChemicalFormula(formula)[source]

Bases: Serializable, CompositionProvider, MassProvider

Represents a chemical formula

Example

f{C13H9}/-0.55ppm f{C12H9N}/0.06ppm f{C13H9N}/-2.01ppm f{C13H10N}/-0.11ppm f{C13H11N}/-0.09ppm f{C13H12N}/0.26ppm f{C14H10N}/0.19ppm f{C14H11N}/0.45ppm f{C14H10NO}/0.03ppm

Parameters:

formula (str)

property composition: Counter[ElementInfo]

Get elemental composition

formula: str
static parse(s)[source]

Parse chemical formula string like ‘f{C13H9}’

Return type:

ChemicalFormula

Parameters:

s (str)

property proforma_formula: str
serialize()[source]
Return type:

str

class paftacular.comps.CompositionProvider[source]

Bases: ABC

Base class for objects that can provide composition

abstract property composition: Counter[ElementInfo]

Get elemental composition

get_mass(*, monoisotopic=True)[source]

Calculate mass from composition

Return type:

float

Parameters:

monoisotopic (bool)

class paftacular.comps.ImmoniumIon(amino_acid, *, modification=None)[source]

Bases: Serializable, CompositionProvider, MassProvider

Represents an immonium ion

Parameters:
  • amino_acid (AminoAcid)

  • modification (str | None)

amino_acid: AminoAcid
property composition: Counter[ElementInfo]

Get elemental composition

property formula: str
get_mass(*, monoisotopic=True)[source]

Calculate mass from composition

Return type:

float

Parameters:

monoisotopic (bool)

modification: str | None
static parse(s)[source]

Parse immonium ion string like ‘IK’, ‘IM[Oxidation]’

Return type:

ImmoniumIon

Parameters:

s (str)

serialize()[source]
Return type:

str

class paftacular.comps.InternalFragment(start_position, end_position, *, sequence=None, nterm_ion_type=None, cterm_ion_type=None)[source]

Bases: Serializable, CompositionProvider, MassProvider

Represents an internal fragment ion with optional backbone cleavage specification

Parameters:
  • start_position (int)

  • end_position (int)

  • sequence (str | None)

  • nterm_ion_type (IonSeries | None)

  • cterm_ion_type (IonSeries | None)

property cleavage_correction: str

Encode the actual backbone composition as mzPAF gains and losses.

property composition: Counter[ElementInfo]

Get elemental composition

cterm_ion_type: IonSeries | None
end_position: int
property formula: str
get_mass(*, monoisotopic=True)[source]

Calculate mass from composition

Return type:

float

Parameters:

monoisotopic (bool)

nterm_ion_type: IonSeries | None
static parse(s)[source]

Parse internal fragment string like ‘m5:10’, ‘m5:10{PEPTIDE}’

Return type:

InternalFragment

Parameters:

s (str)

sequence: str | None
serialize(*, include_sequence=True)[source]
Return type:

str

Parameters:

include_sequence (bool)

start_position: int
class paftacular.comps.IsotopeSpecification(count=0, *, element=None, is_average=False)[source]

Bases: Serializable, CompositionProvider, MassProvider

Represents isotope information

Parameters:
  • count (int)

  • element (str | None)

  • is_average (bool)

property composition: Counter[ElementInfo]

Get elemental composition

count: int
element: str | None
get_mass(*, monoisotopic=True)[source]

Calculate mass contribution of isotope specification

Return type:

float

Parameters:

monoisotopic (bool)

is_average: bool
static parse(s)[source]

Parse isotope string like ‘+i’, ‘-2i13C’, ‘+iA’

Return type:

IsotopeSpecification

Parameters:

s (str)

serialize()[source]
Return type:

str

class paftacular.comps.MassError(value, *, unit='da')[source]

Bases: Serializable

Represents mass error with value and unit

Parameters:
  • value (float)

  • unit (Literal['da', 'ppm'])

static parse(s)[source]

Parse mass error string like ‘0.55ppm’ or ‘0.06’

Return type:

MassError

Parameters:

s (str)

serialize()[source]
Return type:

str

unit: Literal['da', 'ppm']
value: float
class paftacular.comps.MassProvider[source]

Bases: ABC

Base class for objects that can provide mass

property average_mass: float
abstractmethod get_mass(*, monoisotopic=True)[source]

Monoisotopic (default) or average mass in Da.

Return type:

float

Parameters:

monoisotopic (bool)

property monoisotopic_mass: float
class paftacular.comps.NamedCompound(name)[source]

Bases: Serializable, CompositionProvider, MassProvider

Represents a named compound.

Example: 0@_{Urocanic Acid}

Parameters:

name (str)

property composition: Counter[ElementInfo]

Get elemental composition

get_mass(*, monoisotopic=True)[source]

Calculate mass from composition

Return type:

float

Parameters:

monoisotopic (bool)

name: str
static parse(s)[source]

Parse named compound string like ‘_{Urocanic Acid}’

Return type:

NamedCompound

Parameters:

s (str)

serialize()[source]
Return type:

str

class paftacular.comps.NeutralLoss(count, *, base_formula=None, base_mass=None, base_reference=None)[source]

Bases: Serializable, ScalableComposition, MassProvider

Represents a neutral loss or gain

Parameters:
  • count (int)

  • base_formula (str | None)

  • base_mass (float | None)

  • base_reference (str | None)

base_formula: str | None
base_mass: float | None
base_reference: str | None
count: int
property formula: str
get_mass(*, monoisotopic=True)[source]

Calculate mass from composition

Return type:

float

Parameters:

monoisotopic (bool)

property loss_type: Literal['mass', 'formula', 'reference']
static parse(loss_str)[source]

Parse a neutral loss string into a NeutralLoss object

Return type:

NeutralLoss

Parameters:

loss_str (str)

property proforma_formula: str
property reference: RefMolInfo | str | None
serialize(*, loss_type=None, monoisotopic=True)[source]
Return type:

str

Parameters:
  • loss_type (Literal['mass', 'formula', 'reference'] | None)

  • monoisotopic (bool)

class paftacular.comps.PeptideIon(series, position, *, sequence=None)[source]

Bases: Serializable, CompositionProvider, MassProvider

Represents a primary peptide fragment ion

Parameters:
  • series (IonSeries)

  • position (int)

  • sequence (str | None)

property composition: Counter[ElementInfo]

Get elemental composition

property formula: str
get_mass(*, monoisotopic=True)[source]

Calculate mass from composition

Return type:

float

Parameters:

monoisotopic (bool)

static parse(s)[source]

Parse peptide ion string like ‘b5’, ‘y10{PEPTIDE}’

Return type:

PeptideIon

Parameters:

s (str)

position: int
sequence: str | None
serialize(*, include_sequence=True)[source]
Return type:

str

Parameters:

include_sequence (bool)

series: IonSeries
class paftacular.comps.PrecursorIon[source]

Bases: Serializable, CompositionProvider, MassProvider

Represents a precursor ion

property composition: Counter[ElementInfo]

Get elemental composition

property formula: str | None
get_mass(*, monoisotopic=True)[source]

Calculate mass from composition

Return type:

float

Parameters:

monoisotopic (bool)

static parse(s)[source]

Parse precursor ion string ‘p’

Return type:

PrecursorIon

Parameters:

s (str)

serialize()[source]
Return type:

str

class paftacular.comps.ReferenceIon(name)[source]

Bases: Serializable, CompositionProvider, MassProvider

Represents a reference ion

Parameters:

name (str)

property composition: Counter[ElementInfo]

Get elemental composition

property formula: str | None
get_mass(*, monoisotopic=True)[source]

Calculate mass from composition

Return type:

float

Parameters:

monoisotopic (bool)

name: str
static parse(s)[source]

Parse reference ion string like ‘r[Phospho]’

Return type:

ReferenceIon

Parameters:

s (str)

property reference: RefMolInfo
serialize()[source]
Return type:

str

class paftacular.comps.SMILESCompound(smiles)[source]

Bases: Serializable, CompositionProvider, MassProvider

Represents a SMILES string

Example

s{CN=C=O}[M+H]/-0.55ppm s{COc(c1)cccc1C#N}[M+H+Na]^2/1.29ppm

Parameters:

smiles (str)

property composition: Counter[ElementInfo][source]

Get elemental composition

property formula: str
static parse(s)[source]

Parse SMILES compound string like ‘s{CN=C=O}’

Return type:

SMILESCompound

Parameters:

s (str)

property proforma_formula: str
serialize()[source]
Return type:

str

smiles: str
class paftacular.comps.ScalableComposition[source]

Bases: CompositionProvider

Mixin for compositions that scale by count and sign

property composition: Counter[ElementInfo]

Get scaled composition

count: int
class paftacular.comps.Serializable[source]

Bases: ABC

Base class for serializable objects

abstractmethod serialize()[source]
Return type:

str

class paftacular.comps.UnknownIon(*, label=None)[source]

Bases: Serializable, CompositionProvider, MassProvider

Represents an unknown/unannotated ion

Parameters:

label (int | None)

property composition: Counter[ElementInfo]

Get elemental composition

get_mass(*, monoisotopic=True)[source]

Calculate mass from composition

Return type:

float

Parameters:

monoisotopic (bool)

label: int | None
static parse(s)[source]

Parse unknown ion string like ‘?’ or ‘?5’

Return type:

UnknownIon

Parameters:

s (str)

serialize()[source]
Return type:

str

paftacular.comps.composition_to_formula_string(comp)[source]

Convert composition to standard chemical formula string

Return type:

str

Parameters:

comp (Counter[ElementInfo])

paftacular.comps.composition_to_proforma_formula_string(comp)[source]

Convert composition to ProForma-style formula string

Return type:

str

Parameters:

comp (Counter[ElementInfo])

paftacular.comps.formula_to_composition(formula)[source]

Convert chemical formula string to elemental composition (a new Counter each call).

Return type:

Counter[ElementInfo]

Parameters:

formula (str)

paftacular.IonType

Type alias for any ion-type component of an annotation: the union of PeptideIon, InternalFragment, ImmoniumIon, ReferenceIon, NamedCompound, ChemicalFormula, SMILESCompound, UnknownIon and PrecursorIon. Also importable from paftacular.comps.

Constants

Enums, grammar regexes and the internal-fragment correction table.

class paftacular.constants.AnnotationName(*values)[source]

Bases: StrEnum

FORMULA = 'formula'
IMMONIUM = 'immonium'
INTERNAL = 'internal'
NAMED_COMPOUND = 'named_compound'
PRECURSOR = 'precursor'
REFERENCE = 'reference'
SERIES = 'series'
SMILES = 'smiles'
UNANNOTATED = 'unannotated'
class paftacular.constants.BackboneCleavageType(*values)[source]

Bases: StrEnum

Types of backbone cleavages for internal fragments

A = 'a'
B = 'b'
C = 'c'
X = 'x'
Y = 'y'
Z = 'z'
class paftacular.constants.InternalSeries(*values)[source]

Bases: StrEnum

Enumeration of internal ion series types

AX = 'ax'
AY = 'ay'
AZ = 'az'
BX = 'bx'
BY = 'by'
BZ = 'bz'
CX = 'cx'
CY = 'cy'
CZ = 'cz'
class paftacular.constants.IonSeries(*values)[source]

Bases: StrEnum

Enumeration of ion series types

A = 'a'
B = 'b'
C = 'c'
D = 'd'
DA = 'da'
DB = 'db'
V = 'v'
W = 'w'
WA = 'wa'
WB = 'wb'
X = 'x'
Y = 'y'
Z = 'z'

Peptacular Conversion

Requires the peptacular extra.

Convert peptacular fragments to PafAnnotation.

paftacular.conversion.to_mzpaf(frag, *, confidence=None, mass_error=None, mass_error_unit='ppm', include_sequence=True)[source]

Convert a peptacular Fragment to a PafAnnotation.

Mass deltas are folded (mass * count) and rounded to 6 decimals like Fragment.to_mzpaf(). A delta that rounds to zero is left out. A negative charge state is kept (serialize() writes ^-n). With include_sequence the fragment’s own sequence is embedded (peptide and internal ions) or stored as the resolved sequence (precursor ions).

Return type:

PafAnnotation

Parameters:
  • frag (Fragment)

  • confidence (float | None)

  • mass_error (float | None)

  • mass_error_unit (Literal['ppm', 'da'])

  • include_sequence (bool)

Utilities

paftacular.util.format_number(value, *, minimum_places=0)[source]

Render a finite number as a decimal that round trips through float.

Return type:

str

Parameters:
  • value (float)

  • minimum_places (int)

paftacular.util.parse_formula(formula)[source]

Parse a chemical formula into element counts, supporting isotopes.

Parameters:

formula (str) – Chemical formula string (e.g., “H2O”, “CO2”, “[13C2]H6”)

Return type:

Counter[str]

Returns:

Counter mapping element symbols to their counts - Regular elements: “H”, “O”, “Ca” - Isotopes: “13C”, “2H” (without brackets)

paftacular.util.to_enum(cls, value, what)[source]

Convert value to the enum cls, raising PaftacularError naming what.

Return type:

TypeVar(E, bound= Enum)

Parameters:
  • cls (type[E])

  • value (object)

  • what (str)

paftacular.util.validate_integer(value, name, *, minimum=0)[source]

Reject booleans, nonintegral types, and values below the minimum.

Return type:

None

Parameters:
  • value (int)

  • name (str)

  • minimum (int)

paftacular.util.validate_number(value)[source]

Require a number representable as a finite float, excluding booleans.

Return type:

None

Parameters:

value (float)