spectrum_utils

repository·main·Indexed 41 days ago

https://github.com/bittremieuxlab/spectrum_utils

A Python package for efficient mass spectrometry data processing and visualization. It supports spectrum loading via Universal Spectrum Identifier (USI), fragment annotation using the ProForma 2.0 specification, and the generation of publication-quality static or interactive plots, including mirror and mass error plots.

Tokens
5K
Snippets
17
Records
25
Agent score
45%

What's inside spectrum_utils

  1. Overview of spectrum_utils features

    main

    spectrum_utils is a Python package designed for efficient mass spectrometry data processing and visualization. Its core capabilities include:

    • Spectrum Loading: Load spectra from online proteomics and metabolomics resources using the Universal Spectrum Identifier (USI) mechanism.
    • Spectrum Processing: Perform optimized operations such as precursor and noise peak removal, intensity filtering, and intensity scaling.
    • Annotation: Annotate observed spectrum fragments using the ProForma 2.0 specification for (modified) peptidoforms.
    • Visualization: Generate publication-quality, fully customizable static plots and interactive spectrum plots.
  2. About spectrum_utils

    main

    spectrum_utils is a Python package designed for efficient mass spectrometry data processing and visualization. It provides tools for:

    • Spectrum Loading: Fetching data from online proteomics and metabolomics resources using the Universal Spectrum Identifier (USI) mechanism.
    • Spectrum Processing: Performing optimized operations such as precursor and noise peak removal, intensity filtering, and intensity scaling.
    • Annotation: Annotating observed spectrum fragments using the ProForma 2.0 specification for (modified) peptidoforms.
    • Visualization: Generating publication-quality, fully customizable, and interactive spectrum plots.
  3. Specify different modification formats in ProForma

    main

    The annotate_proforma method supports several ways to define modifications within the ProForma string:

    1. By Name: Use the modification name directly, e.g., EM[Oxidation]EVEES[Phospho]PEK.
    2. By CV Accession: Use the Controlled Vocabulary accession, e.g., EM[MOD:00719]EVEES[MOD:00046]PEK.
    3. By Delta Mass: Use the mass difference in brackets, e.g., EM[+15.9949]EVEES[+79.9663]PEK.
    # Example: Using delta masses
    peptide = "EM[+15.9949]EVEES[+79.9663]PEK"
    spectrum = spectrum.annotate_proforma(peptide, 10, "ppm")
  4. Quickstart: Process and visualize MS/MS spectra

    main

    You can use spectrum_utils to load, process, and visualize mass spectrometry spectra. The library supports a fluent API where processing steps can be chained together.

    Key Workflow Steps:

    1. Load: Retrieve a spectrum using its Universal Spectrum Identifier (USI) via sus.MsmsSpectrum.from_usi(usi).
    2. Process: Apply transformations such as setting mass ranges, removing precursor peaks, filtering intensity, scaling, and annotating peptide fragments.
    3. Visualize: Plot the resulting spectrum using sup.spectrum(spectrum, ...).

    Important Note on Idempotency: Many processing steps modify the peak m/z and intensity values. These operations are not idempotent. If you need to preserve the original raw peak values, create a copy of the MsmsSpectrum object before starting the processing chain.

    import matplotlib.pyplot as plt
    import spectrum_utils.plot as sup
    import spectrum_utils.spectrum as sus
    
    # Retrieve the spectrum by its USI.
    usi = "mzspec:PXD004732:01650b_BC2-TUM_first_pool_53_01_01-3xHCD-1h-R2:scan:41840"
    peptide = "WNQLQAFWGTGK"
    spectrum = sus.MsmsSpectrum.from_usi(usi)
    
    # Process the spectrum using method chaining.
    fragment_tol_mass, fragment_tol_mode = 10, "ppm"
    spectrum = (
        spectrum.set_mz_range(min_mz=100, max_mz=1400)
        .remove_precursor_peak(fragment_tol_mass, fragment_tol_mode)
        .filter_intensity(min_intensity=0.05, max_num_peaks=50)
        .scale_intensity("root")
        .annotate_proforma(
            peptide, fragment_tol_mass, fragment_tol_mode, ion_types="aby"
        )
    )
    
    # Plot the spectrum.
    fig, ax = plt.subplots(figsize=(12, 6))
    sup.spectrum(spectrum, grid=False, ax=ax)
    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)
    plt.savefig("quickstart.png", bbox_inches="tight", dpi=300, transparent=True)
    plt.close()
  5. Customize peak annotations with `annot_fmt`

    main

    By default, singly-charged b and y peptide fragment ions are annotated. To change which peaks are labeled or how they are formatted, provide a callable to the annot_fmt argument in spectrum_utils.plot.spectrum.

    Common patterns:

    1. Include specific ion types: Use functools.partial to pass additional ion_types to a custom formatter.
    2. Full PSI information: Pass the built-in str function to use the full PSI peak interpretation specification for labels.
    3. Custom logic: Implement a function that accepts an annotation object and returns a string (or empty string if no label is desired).
    import functools
    import spectrum_utils.plot
    
    # Annotate additional ion types (e.g., 'abyIm')
    spectrum_utils.plot.spectrum(..., annot_fmt=functools.partial(ion_types="abyIm"))
    
    # Use full PSI string representation
    spectrum_utils.plot.spectrum(..., annot_fmt=str)
  6. Use interactive plotting with `spectrum_utils.iplot`

    main

    The spectrum_utils.iplot module provides interactive versions of the standard plotting functions. It is a drop-in replacement for spectrum_utils.plot; you only need to change the import statement.

    These functions return objects compatible with Vega-Altair, which can be saved as JSON and embedded in web pages using Vega-Embed.

    import spectrum_utils.iplot as sup
    import spectrum_utils.spectrum as sus
    
    # Interactive spectrum plot
    spectrum = sus.MsmsSpectrum.from_usi(usi)
    spectrum.annotate_proforma("WNQLQAFWGTGK", 10, "ppm", ion_types="aby")
    
    chart = sup.spectrum(spectrum)
    chart.properties(width=640, height=400).save("iplot_spectrum.json")
    
    # Interactive mirror plot
    chart_mirror = sup.mirror(spectrum_top, spectrum_bottom)
    chart_mirror.properties(width=640, height=400).save("iplot_mirror.json")
  7. Customize spectrum_utils installation with optional extras

    main

    To minimize the number of third-party dependencies installed, you can use modular installation by specifying specific dependency sets via pip.

    Available extras:

    • iplot: Enables interactive spectrum plotting using Vega-Altair.
    • dev: Includes developer dependencies for automatic linting and testing.
    • docs: Includes dependencies required to generate documentation pages.

    Note: The standard pip install spectrum_utils command installs all optional extensions except for dev and docs.

    pip install spectrum_utils[iplot]
  8. Install spectrum_utils via pip or conda

    main

    You can install spectrum_utils using either pip or conda. By default, these commands install all optional extensions (excluding developer and documentation dependencies).

    Requirements:

    • Python version 3.8 or higher.

    Installation Commands:

    Using pip:

    pip install spectrum_utils[iplot]

    Using conda:

    conda install -c bioconda spectrum_utils
  9. Customize peak colors in `spectrum_utils.plot`

    main

    Peaks are colored by default based on their ion type (e.g., "b" for b-ions, "y" for y-ions). You can overwrite these colors by modifying the spectrum_utils.plot.colors dictionary.

    import spectrum_utils.plot as sup
    
    # Change the color for y peptide fragments
    sup.colors["y"] = "#FF1493"
  10. Process an MsmsSpectrum object

    main

    The MsmsSpectrum object supports several high-level processing methods that can be chained.

    Available Processing Methods:

    • set_mz_range(min_mz, max_mz): Restricts the mass range to filter out irrelevant peaks.
    • remove_precursor_peak(fragment_tol_mass, fragment_tol_mode): Removes the precursor peak based on a tolerance.
    • filter_intensity(min_intensity, max_num_peaks): Removes low-intensity noise by retaining peaks at or above a certain percentage of the base peak intensity and limiting the total number of peaks.
    • scale_intensity(method): Scales peak intensities (e.g., using "root" to de-emphasize overly intense peaks).
    • annotate_proforma(peptide, fragment_tol_mass, fragment_tol_mode, ion_types): Annotates peaks corresponding to peptide fragments (e.g., a, b, or y ions) based on a ProForma 2.0 peptide string.