### Install black and pre-commit Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/CONTRIBUTING.md Install the black formatter and pre-commit tool using pip or conda if they are not already installed. ```bash # Using pip pip install black pre-commit # Using conda conda -c conda-forge black pre-commit ``` -------------------------------- ### Install pre-commit hook Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/CONTRIBUTING.md Navigate to your local spectrum_utils repository and activate the pre-commit hook to automatically format code before committing. ```bash pre-commit install ``` -------------------------------- ### Install spectrum_utils with conda Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/install.md Use this command to install spectrum_utils from the bioconda channel. Missing dependencies will be automatically installed. ```bash conda install -c bioconda spectrum_utils ``` -------------------------------- ### Install spectrum_utils with pip Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/install.md Use this command to install spectrum_utils with interactive plotting capabilities. Missing dependencies will be automatically installed. ```bash pip install spectrum_utils[iplot] ``` -------------------------------- ### Example Fragment Annotation Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md A concrete example of a fragment annotation string representing a y4 ion with specific modifications. ```text y4-H2O+2i^2[M+H+Na] ``` -------------------------------- ### Get Theoretical Fragments Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Generates fragment annotations and their theoretical masses for a given proteoform. Supports specifying ion types, isotope limits, charge limits, and neutral losses. ```python get_theoretical_fragments(proteoform, ion_types='by', max_isotope=0, max_charge=1, neutral_losses={'H2O': -18.01, 'NH3': -17.03}) -> List[Tuple[FragmentAnnotation, float]] ``` -------------------------------- ### MsmsSpectrum Constructor Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Instantiate a new MsmsSpectrum consisting of fragment peaks. This is the primary way to create a spectrum object with known peak data. ```APIDOC ## MsmsSpectrum Constructor ### Description Instantiate a new MsmsSpectrum consisting of fragment peaks. ### Method __init__ ### Parameters * **identifier** (str) - Required - Spectrum identifier. It is recommended to use a unique and interpretable identifier, such as a Universal Spectrum Identifier (USI). * **precursor_mz** (float) - Required - Precursor ion m/z. * **precursor_charge** (int) - Required - Precursor ion charge. * **mz** (array_like) - Required - M/z values of the fragment peaks. * **intensity** (array_like) - Required - Intensities of the corresponding fragment peaks in mz. * **retention_time** (float) - Optional - Retention time at which the spectrum was acquired (the default is np.nan, which indicates that retention time is unspecified/unknown). ``` -------------------------------- ### Create a Mirror Plot Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/plotting.md Generates a mirror plot to visualize two matching spectra. Requires importing matplotlib.pyplot, spectrum_utils.plot, and spectrum_utils.spectrum. Spectra are loaded using MsmsSpectrum.from_usi and annotated with peptide information before plotting. ```python import matplotlib.pyplot as plt import spectrum_utils.plot as sup import spectrum_utils.spectrum as sus peptide = "DLTDYLM[Oxidation]K" usi_top = "mzspec:MSV000079960:DY_HS_Exp7-Ad1:scan:30372" spectrum_top = sus.MsmsSpectrum.from_usi(usi_top) spectrum_top.annotate_proforma(peptide, 0.5, "Da", ion_types="aby") usi_bottom = "mzspec:MSV000080679:j11962_C1orf144:scan:10671" spectrum_bottom = sus.MsmsSpectrum.from_usi(usi_bottom) spectrum_bottom.annotate_proforma(peptide, 0.5, "Da", ion_types="aby") fig, ax = plt.subplots(figsize=(12, 6)) sup.mirror(spectrum_top, spectrum_bottom, ax=ax) plt.savefig("mirror.png", dpi=300, bbox_inches="tight", transparent=True) plt.close() ``` -------------------------------- ### Extending Default Annotation with functools.partial Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/plotting.md Demonstrates how to extend the default ion annotation to include additional ion types like 'a', 'b', 'y', 'I', and 'm' using functools.partial. ```python import functools import spectrum_utils.plot spectrum_utils.plot.spectrum(..., annot_fmt=functools.partial(ion_types="abyIm")) ``` -------------------------------- ### Create a new branch for changes Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/CONTRIBUTING.md Before making changes, create a new branch with a descriptive name using git checkout -b. ```bash git checkout -b fix_x ``` -------------------------------- ### Load, Process, and Plot Spectrum Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/quickstart.md Loads a spectrum from a USI, applies various processing steps (mass range restriction, precursor removal, intensity filtering, scaling, and annotation), and then plots the processed spectrum. It's recommended to copy the spectrum object before processing if the original data is needed. ```python 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. 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() ``` -------------------------------- ### Annotating with PSI Peak Interpretation Specification Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/plotting.md Uses the `str` function as the `annot_fmt` to generate peak labels that conform to the PSI peak interpretation specification. ```python spectrum_utils.plot.spectrum(..., annot_fmt=str) ``` -------------------------------- ### Plotting Runtimes with Seaborn and Matplotlib Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/runtime.md Generates a box plot to visualize and compare the processing times of spectrum_utils, pymzML, and pyOpenMS. The y-axis is set to a logarithmic scale for better visualization of varied runtimes. Requires libraries like time, matplotlib.pyplot, and seaborn. ```python runtimes_pymzml = time_pymzml(mgf_filename) fig, ax = plt.subplots() sns.boxplot( data=[runtimes_spectrum_utils, runtimes_pymzml, runtimes_pyopenms], flierprops={"markersize": 2}, ax=ax, ) ax.set_yscale("log") ax.xaxis.set_ticklabels(("spectrum_utils", "pymzML", "pyOpenMS")) ax.set_ylabel("Processing time per spectrum (s)") sns.despine() plt.savefig("runtime.png", bbox_inches="tight", dpi=300, transparent=True) plt.close() ``` -------------------------------- ### Interactive Mirror Plot of Two Spectra Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/plotting.md Creates an interactive mirror plot comparing two mass spectra. This function requires two `MsmsSpectrum` objects as input and saves the resulting chart as a JSON file. Ensure Vega and Vega-Lite JavaScript libraries are included. ```python import spectrum_utils.iplot as sup import spectrum_utils.spectrum as sus peptide = "DLTDYLM[Oxidation]K" usi_top = "mzspec:MSV000079960:DY_HS_Exp7-Ad1:scan:30372" spectrum_top = sus.MsmsSpectrum.from_usi(usi_top) spectrum_top.annotate_proforma(peptide, 0.5, "Da", ion_types="aby") usi_bottom = "mzspec:MSV000080679:j11962_C1orf144:scan:10671" spectrum_bottom = sus.MsmsSpectrum.from_usi(usi_bottom) spectrum_bottom.annotate_proforma(peptide, 0.5, "Da", ion_types="aby") chart = sup.mirror(spectrum_top, spectrum_bottom) chart.properties(width=640, height=400).save("iplot_mirror.json") ``` -------------------------------- ### MsmsSpectrum.from_usi Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Construct a spectrum from a public resource specified by its Universal Spectrum Identifier (USI). This method allows for the creation of spectrum objects by fetching data from external repositories. ```APIDOC ## MsmsSpectrum.from_usi ### Description Construct a spectrum from a public resource specified by its Universal Spectrum Identifier (USI). ### Method from_usi ### Parameters * **usi** (str) - Required - The USI from which to generate the spectrum. * **backend** (str) - Optional - PROXI host backend (default: ‘aggregator’). * **timeout** (float | None) - Optional - Timeout in seconds for network requests (default: None, uses pyteomics default). * **kwargs** - Optional - Extra arguments to construct the spectrum that might be missing from the PROXI response (e.g. precursor_mz or precursor_charge) and the PROXI backend. ### Returns [MsmsSpectrum](#spectrum_utils.spectrum.MsmsSpectrum) - The spectrum corresponding to the given USI. ### Raises **ValueError** - If the PROXI response does not contain information about the precursor m/z or precursor charge. Explicit precursor m/z and precursor charge values can be provided using the precursor_mz and precursor_charge keyword arguments respectively. ``` -------------------------------- ### Benchmarking spectrum_utils Spectrum Processing Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/runtime.md Measures the time taken to process spectra using the spectrum_utils library. It applies a series of standard processing steps including setting the m/z range, removing precursor peaks, filtering noise, and scaling intensities. ```python import time import matplotlib.pyplot as plt import numpy as np import pyopenms import pyteomics.mgf import seaborn as sns import spectrum_utils.spectrum as sus from pymzml.spec import Spectrum min_peaks = 10 min_mz, max_mz = 100, 1400 fragment_tol_mass, fragment_tol_mode = 0.02, "Da" min_intensity = 0.05 max_num_peaks = 150 def time_spectrum_utils(mgf_filename): runtimes = [] for spec_dict in pyteomics.mgf.read(mgf_filename): # Omit invalid spectra. if ( len(spec_dict["m/z array"]) < min_peaks or "charge" not in spec_dict["params"] ): continue spectrum = sus.MsmsSpectrum( spec_dict["params"]["title"], spec_dict["params"]["pepmass"][0], spec_dict["params"]["charge"][0], spec_dict["m/z array"], spec_dict["intensity array"], float(spec_dict["params"]["rtinseconds"]), )._inner start_time = time.time() spectrum.set_mz_range(min_mz, max_mz) spectrum.remove_precursor_peak(fragment_tol_mass, fragment_tol_mode) spectrum.filter_intensity(min_intensity, max_num_peaks) spectrum.scale_intensity("root", 1) runtimes.append(time.time() - start_time) return runtimes def time_pymzml(mgf_filename): runtimes = [] for spec_dict in pyteomics.mgf.read(mgf_filename): # Omit invalid spectra. if ( len(spec_dict["m/z array"]) < min_peaks or "charge" not in spec_dict["params"] ): continue spec = Spectrum() spec.set_peaks( [*zip(spec_dict["m/z array"], spec_dict["intensity array"])], "raw" ) start_time = time.time() spec.reduce("raw", (min_mz, max_mz)) spec.remove_precursor_peak() spec.remove_noise(noise_level=min_intensity) spec /= np.amax(spec.i) spec.i = np.sqrt(spec.i) runtimes.append(time.time() - start_time) return runtimes def time_pyopenms(mgf_filename): experiment = pyopenms.MSExperiment() pyopenms.MascotGenericFile().load(mgf_filename, experiment) runtimes = [] for spectrum in experiment: # Omit invalid spectra. if ( len(spectrum.get_peaks()[0]) < min_peaks or spectrum.getPrecursors()[0].getCharge() == 0 ): continue start_time = time.time() # Set the m/z range. filtered_mz, filtered_intensity = [], [] for mz, intensity in zip(*spectrum.get_peaks()): if min_mz <= mz <= max_mz: filtered_mz.append(mz) filtered_intensity.append(intensity) spectrum.set_peaks((filtered_mz, filtered_intensity)) # Remove the precursor peak. parent_peak_mower = pyopenms.ParentPeakMower() parent_peak_mower_params = parent_peak_mower.getDefaults() parent_peak_mower_params.setValue( b"window_size", fragment_tol_mass, b"" ) parent_peak_mower.setParameters(parent_peak_mower_params) parent_peak_mower.filterSpectrum(spectrum) # Filter by base peak intensity percentage. pyopenms.Normalizer().filterSpectrum(spectrum) threshold_mower = pyopenms.ThresholdMower() threshold_mower_params = threshold_mower.getDefaults() threshold_mower_params.setValue(b"threshold", min_intensity, b"") threshold_mower.setParameters(threshold_mower_params) threshold_mower.filterSpectrum(spectrum) # Restrict to the most intense peaks. n_largest = pyopenms.NLargest() n_largest_params = n_largest.getDefaults() n_largest_params.setValue(b"n", max_num_peaks, b"") n_largest.setParameters(n_largest_params) n_largest.filterSpectrum(spectrum) # Scale the peak intensities by their square root and normalize. pyopenms.SqrtMower().filterSpectrum(spectrum) pyopenms.Normalizer().filterSpectrum(spectrum) runtimes.append(time.time() - start_time) return runtimes mgf_filename = "iPRG2012.mgf" runtimes_spectrum_utils = time_spectrum_utils(mgf_filename) runtimes_pyopenms = time_pyopenms(mgf_filename) ``` -------------------------------- ### spectrum_utils.proforma.clear_cache Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Clears downloaded resources from the cache. If no resource IDs are provided, all known files will be removed. ```APIDOC ## spectrum_utils.proforma.clear_cache ### Description Clears the downloaded resources from the cache. ### Parameters * **resource_ids** (*Optional* *[**Sequence* *[**str* *]* *]*) – Identifiers of the resources to remove from the cache. If None, all known files will be removed. ### Returns None ``` -------------------------------- ### spectrum_utils.fragment_annotation.get_theoretical_fragments Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Generates fragment annotations and their theoretical masses for a given proteoform. It allows specifying ion types, isotope limits, charge limits, and neutral losses. ```APIDOC ## spectrum_utils.fragment_annotation.get_theoretical_fragments ### Description Get fragment annotations with their theoretical masses for the given sequence. ### Parameters * **proteoform** ([*proforma.Proteoform*](#spectrum_utils.proforma.Proteoform)) – The proteoform for which the fragment annotations will be generated. * **ion_types** (*str*) – The ion types to generate. Can be any combination of ‘a’, ‘b’, ‘c’, ‘x’, ‘y’, and ‘z’ for peptide fragments, ‘I’ for immonium ions, ‘m’ for internal fragment ions, ‘p’ for the precursor ion, and ‘r’ for reporter ions. The default is ‘by’, which means that b and y peptide ions will be generated. * **max_isotope** (*int*) – The maximum isotope to consider (the default is 0 to only generate the monoisotopic peaks). * **max_charge** (*int*) – All fragments up to and including the given charge will be generated (the default is 1 to only generate singly-charged fragments). * **neutral_losses** (*Optional* *[**Dict* *[**Optional* *[**str* *]* *,* *float* *]* *]*) – A dictionary with neutral loss names and (negative) mass differences to be considered. ### Returns All possible fragment annotations and their theoretical m/z in ascending m/z order. ### Return type List[Tuple[[FragmentAnnotation](#spectrum_utils.fragment_annotation.FragmentAnnotation), float]] ``` -------------------------------- ### Annotate Spectrum with Neutral Losses (NH3, H2O) Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/annotating.md Annotates a spectrum considering peptide fragments with optional ammonia (NH3) or water (H2O) neutral losses. This can increase the number of explained peaks. The 'neutral_losses' parameter takes a dictionary of loss labels and their mass differences. ```python import matplotlib.pyplot as plt import spectrum_utils.plot as sup import spectrum_utils.spectrum as sus usi = "mzspec:PXD014834:TCGA-AA-3518-01A-11_W_VU_20120915_A0218_3F_R_FR01:scan:8370" peptide = "WNQLQAFWGTGK" spectrum = sus.MsmsSpectrum.from_usi(usi) spectrum.annotate_proforma( peptide, fragment_tol_mass=0.05, fragment_tol_mode="Da", ion_types="aby", neutral_losses={"NH3": -17.026549, "H2O": -18.010565}, ) fig, ax = plt.subplots(figsize=(12, 6)) sup.spectrum(spectrum, grid=False, ax=ax) ax.set_title(peptide, fontdict={"fontsize": "xx-large"}) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) plt.savefig("neutral_losses_1.png", dpi=300, bbox_inches="tight", transparent=True) plt.close() ``` -------------------------------- ### Annotate Spectrum by Delta Mass Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/annotating.md Annotates a spectrum using a ProForma string where modifications are specified by their delta mass. Requires importing spectrum_utils and matplotlib. ```python 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:MSV000082283:f07074:scan:5475" spectrum = sus.MsmsSpectrum.from_usi(usi) # Annotate the spectrum with its ProForma string. peptide = "EM[+15.9949]EVEES[+79.9663]PEK" spectrum = spectrum.annotate_proforma(peptide, 10, "ppm") # Plot the spectrum. fig, ax = plt.subplots(figsize=(12, 6)) sup.spectrum(spectrum, grid=False, ax=ax) ax.set_title(peptide, fontdict={"fontsize": "xx-large"}) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) plt.savefig("proforma_ex3.png", bbox_inches="tight", dpi=300, transparent=True) plt.close() ``` -------------------------------- ### Custom Peak Labeling with Charge and Neutral Loss Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/plotting.md Implements a custom annotation function to display charge state with '+' symbols, neutral loss of ammonia with '*', and neutral loss of water with 'o', similar to the Lorikeet viewer. ```python import matplotlib.pyplot as plt import spectrum_utils.plot as sup import spectrum_utils.spectrum as sus def annotate_ion_type(annotation, ion_types="aby"): if annotation.ion_type[0] in ion_types: if abs(annotation.isotope) == 1: iso = "+i" if annotation.isotope > 0 else "-i" elif annotation.isotope != 0: iso = f"{annotation.isotope:+}i" else: iso = "" nl = {"-NH3": "*", "-H2O": "o"}.get(annotation.neutral_loss, "") return f"{annotation.ion_type}{iso}{'+' * annotation.charge}{nl}" else: return "" usi = "mzspec:PXD014834:TCGA-AA-3518-01A-11_W_VU_20120915_A0218_3F_R_FR01:scan:8370" peptide = "WNQLQAFWGTGK" spectrum = sus.MsmsSpectrum.from_usi(usi) spectrum.annotate_proforma( peptide, fragment_tol_mass=0.05, fragment_tol_mode="Da", ion_types="aby", max_ion_charge=2, neutral_losses={"NH3": -17.026549, "H2O": -18.010565}, ) fig, ax = plt.subplots(figsize=(12, 6)) sup.spectrum(spectrum, annot_fmt=annotate_ion_type, grid=False, ax=ax) ax.set_title(peptide, fontdict={"fontsize": "xx-large"}) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) plt.savefig("annot_fmt.png", dpi=300, bbox_inches="tight", transparent=True) plt.close() ``` -------------------------------- ### Interactive Plot of an Individual Spectrum Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/plotting.md Generates an interactive plot for a single mass spectrum. Ensure the necessary Vega and Vega-Lite JavaScript libraries are included. The resulting chart is saved as a JSON file. ```python import spectrum_utils.iplot as sup import spectrum_utils.spectrum as sus usi = "mzspec:PXD004732:01650b_BC2-TUM_first_pool_53_01_01-3xHCD-1h-R2:scan:41840" 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") ``` -------------------------------- ### spectrum_utils.plot.mirror Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Creates a mirror plot of two MS/MS spectra, displaying one spectrum above the other. ```APIDOC ## spectrum_utils.plot.mirror(spec_top: MsmsSpectrum, spec_bottom: MsmsSpectrum, spectrum_kws: Dict | None = None, ax: matplotlib.pyplot.Axes | None = None) -> matplotlib.pyplot.Axes ### Description Mirror plot two MS/MS spectra. ### Parameters * **spec_top** (MsmsSpectrum) – The spectrum to be plotted on the top. * **spec_bottom** (MsmsSpectrum) – The spectrum to be plotted on the bottom. * **spectrum_kws** (Optional[Dict], optional) – Keyword arguments for plot.spectrum. * **ax** (Optional[plt.Axes], optional) – Axes instance on which to plot the spectrum. If None the current Axes instance is used. ### Returns The matplotlib Axes instance on which the spectra are plotted. ### Return type plt.Axes ``` -------------------------------- ### Create a Mass Error Plot Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/plotting.md Visualizes the mass differences between observed and theoretical masses of fragment ions. The plot uses bubble size for intensity, x-axis for observed m/z, and y-axis for mass error. Requires importing matplotlib.pyplot, spectrum_utils.plot, and spectrum_utils.spectrum. ```python import matplotlib.pyplot as plt import spectrum_utils.plot as sup import spectrum_utils.spectrum as sus usi = "mzspec:PXD022531:j12541_C5orf38:scan:12368" peptide = "VAATLEILTLK/2" spectrum = sus.MsmsSpectrum.from_usi(usi) spectrum.annotate_proforma( peptide, fragment_tol_mass=0.05, fragment_tol_mode="Da", ion_types="aby", max_ion_charge=2, neutral_losses={"NH3": -17.026549, "H2O": -18.010565}, ) fig, ax = plt.subplots(figsize=(10.5, 3)) sup.mass_errors(spectrum, plot_unknown=False, ax=ax) plt.savefig("mass_errors.png", dpi=300, bbox_inches="tight", transparent=True) plt.close() ``` -------------------------------- ### Annotate Spectrum by Modification Name Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/annotating.md Annotates a spectrum using a ProForma string where modifications are specified by their names. Requires importing spectrum_utils and matplotlib. ```python 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:MSV000082283:f07074:scan:5475" spectrum = sus.MsmsSpectrum.from_usi(usi) # Annotate the spectrum with its ProForma string. peptide = "EM[Oxidation]EVEES[Phospho]PEK" spectrum = spectrum.annotate_proforma(peptide, 10, "ppm") # Plot the spectrum. fig, ax = plt.subplots(figsize=(12, 6)) sup.spectrum(spectrum, grid=False, ax=ax) ax.set_title(peptide, fontdict={"fontsize": "xx-large"}) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) plt.savefig("proforma_ex1.png", bbox_inches="tight", dpi=300, transparent=True) plt.close() ``` -------------------------------- ### Annotate Spectrum with Multiple Ion Types Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/annotating.md Annotates a spectrum with a combination of peptide fragments (a, b, y), immonium ions, and internal fragment ions. Ensure the 'ion_types' parameter correctly specifies the desired fragments. ```python import matplotlib.pyplot as plt import spectrum_utils.plot as sup import spectrum_utils.spectrum as sus usi = "mzspec:PXD000561:Adult_Frontalcortex_bRP_Elite_85_f09:scan:17555" peptide = "VLHPLEGAVVIIFK" spectrum = sus.MsmsSpectrum.from_usi(usi) spectrum.annotate_proforma(peptide, 10, "ppm", ion_types="abyIm") fig, ax = plt.subplots(figsize=(12, 6)) sup.spectrum(spectrum, grid=False, ax=ax) ax.set_title(peptide, fontdict={"fontsize": "xx-large"}) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) plt.savefig("ion_types.png", dpi=300, bbox_inches="tight", transparent=True) plt.close() ``` -------------------------------- ### Annotate Spectrum by CV Accession Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/annotating.md Annotates a spectrum using a ProForma string where modifications are specified by their CV accession numbers. Requires importing spectrum_utils and matplotlib. ```python 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:MSV000082283:f07074:scan:5475" spectrum = sus.MsmsSpectrum.from_usi(usi) # Annotate the spectrum with its ProForma string. peptide = "EM[MOD:00719]EVEES[MOD:00046]PEK" spectrum = spectrum.annotate_proforma(peptide, 10, "ppm") # Plot the spectrum. fig, ax = plt.subplots(figsize=(12, 6)) sup.spectrum(spectrum, grid=False, ax=ax) ax.set_title(peptide, fontdict={"fontsize": "xx-large"}) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) plt.savefig("proforma_ex2.png", bbox_inches="tight", dpi=300, transparent=True) plt.close() ``` -------------------------------- ### spectrum_utils.plot.spectrum Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Plots an MS/MS spectrum with options for coloring ions, custom annotations, intensity mirroring, and grid display. It returns the Axes instance used for plotting. ```APIDOC ## spectrum_utils.plot.spectrum ### Description Plots an MS/MS spectrum. Allows customization of ion coloring, annotation formatting, intensity mirroring, and grid display. Can plot on a specified Axes instance or the current one. ### Method Signature spectrum(spec: MsmsSpectrum, *, color_ions: bool = True, annot_fmt: Callable | None = functools.partial(annotate_ion_type, ion_types='by'), annot_kws: Dict | None = None, mirror_intensity: bool = False, grid: bool | str = True, ax: plt.Axes | None = None) -> plt.Axes ### Parameters #### Positional Parameters - **spec** (MsmsSpectrum) - The spectrum to be plotted. #### Keyword Parameters - **color_ions** (bool, optional) - Flag indicating whether or not to color annotated fragment ions. Defaults to True. - **annot_fmt** (Callable | None, optional) - Function to format the peak annotations. Defaults to a partial function that annotates 'b' and 'y' ion types. - **annot_kws** (Dict | None, optional) - Keyword arguments for ax.text to customize peak annotations. - **mirror_intensity** (bool, optional) - Flag indicating whether to flip the intensity axis or not. Defaults to False. - **grid** (bool | str, optional) - Draw grid lines or not. Either a boolean to enable/disable both major and minor grid lines or ‘major’/’minor’ to enable major or minor grid lines respectively. Defaults to True. - **ax** (plt.Axes | None, optional) - Axes instance on which to plot the spectrum. If None the current Axes instance is used. ### Returns - **plt.Axes** - The matplotlib Axes instance on which the spectrum is plotted. ### Return Type plt.Axes ``` -------------------------------- ### Fragment Annotation Structure Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Illustrates the general format for fragment ion annotations, including analyte number, ion type, neutral loss, isotope, charge, adduct, and m/z delta. This format is derived from the PSI peak interpretation specification. ```text (analyte_number)[ion_type](neutral_loss)(isotope)(charge)(adduct)(mz_delta) ``` -------------------------------- ### Create a Facet Plot Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/plotting.md Combines mirror plot and mass error plot functionalities into a single figure. This function requires importing matplotlib.pyplot, spectrum_utils.plot, and spectrum_utils.spectrum. It takes top and bottom spectra, along with annotation settings, to generate the combined plot. ```python import matplotlib.pyplot as plt import spectrum_utils.plot as sup import spectrum_utils.spectrum as sus peptide = "VAATLEILTLK/2" annotation_settings = { "fragment_tol_mass": 0.05, "fragment_tol_mode": "Da", "ion_types": "aby", "max_ion_charge": 2, "neutral_losses": {"NH3": -17.026549, "H2O": -18.010565}, } usi_top = "mzspec:PXD022531:j12541_C5orf38:scan:12368" spectrum_top = sus.MsmsSpectrum.from_usi(usi_top) spectrum_top.annotate_proforma(peptide, **annotation_settings) usi_bottom = "mzspec:PXD022531:b11156_PRAMEF17:scan:22140" spectrum_bottom = sus.MsmsSpectrum.from_usi(usi_bottom) spectrum_bottom.annotate_proforma(peptide, **annotation_settings) fig = sup.facet( spec_top=spectrum_top, spec_mass_errors=spectrum_top, spec_bottom=spectrum_bottom, mass_errors_kws={"plot_unknown": False}, height=7, width=10.5, ) plt.savefig("facet.png", dpi=300, bbox_inches="tight", transparent=True) plt.close() ``` -------------------------------- ### Annotate Spectrum Without Neutral Losses Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/annotating.md Annotates a spectrum considering only canonical peptide fragments without any neutral losses. This serves as a baseline to demonstrate the impact of considering neutral losses. ```python import matplotlib.pyplot as plt import spectrum_utils.plot as sup import spectrum_utils.spectrum as sus usi = "mzspec:PXD014834:TCGA-AA-3518-01A-11_W_VU_20120915_A0218_3F_R_FR01:scan:8370" peptide = "WNQLQAFWGTGK" spectrum = sus.MsmsSpectrum.from_usi(usi) spectrum.annotate_proforma( peptide, fragment_tol_mass=0.05, fragment_tol_mode="Da", ion_types="aby", ) fig, ax = plt.subplots(figsize=(12, 6)) sup.spectrum(spectrum, grid=False, ax=ax) ax.set_title(peptide, fontdict={"fontsize": "xx-large"}) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) plt.savefig("neutral_losses_2.png", dpi=300, bbox_inches="tight", transparent=True) plt.close() ``` -------------------------------- ### Annotate Proteoforms from Parsed ProForma Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Assigns fragment ion labels to spectrum peaks using a pre-parsed ProForma string. Useful when the same parsed sequence is used multiple times for efficiency. ```python >>> proforma_sequence = "MYPEPTIDEK/2" >>> spectrum.annotate_proforma(proforma_sequence, ...) ``` ```python >>> parsed_proforma = proforma.parse(proforma_sequence) >>> spectrum._annotate_proteoforms(parsed_proforma, proforma_sequence, ...) ``` -------------------------------- ### spectrum_utils.plot.facet Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Generates a faceted plot that can display a spectrum, optionally its mass errors, and a mirror spectrum in a single figure. ```APIDOC ## spectrum_utils.plot.facet(spec_top: MsmsSpectrum, spec_mass_errors: MsmsSpectrum | None = None, spec_bottom: MsmsSpectrum | None = None, spectrum_kws: Mapping[str, Any] | None = None, mass_errors_kws: Mapping[str, Any] | None = None, height: float | None = None, width: float | None = None) -> matplotlib.pyplot.Figure ### Description Plot a spectrum, and optionally mass errors, and a mirror spectrum. ### Parameters * **spec_top** (MsmsSpectrum) – The spectrum to be plotted on the top. * **spec_mass_errors** (Optional[List[MsmsSpectrum]], optional) – The spectrum for which mass errors are to be plotted in the middle. * **spec_bottom** (Optional[List[MsmsSpectrum]], optional) – The spectrum to be plotted on the bottom. * **spectrum_kws** (Optional[Mapping[str, Any]], optional) – Keyword arguments for plot.spectrum for the top and bottom spectra. * **mass_errors_kws** (Optional[Mapping[str, Any]], optional) – Keyword arguments for plot.mass_errors. * **height** (Optional[float], optional) – The height of the figure in inches. * **width** (Optional[float], optional) – The width of the figure in inches. ### Returns The matplotlib Figure instance on which the spectra and mass errors are plotted. ### Return type plt.Figure ``` -------------------------------- ### Customize Peak Colors in Spectrum Plotting Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/plotting.md Allows modification of the default peak colors used in spectrum visualizations. To change a color, access the `colors` dictionary within the `spectrum_utils.plot` module and assign a new color value to the desired ion type key. ```python import spectrum_utils.plot as sup sup.colors["y"] = "#FF1493" ``` -------------------------------- ### spectrum_utils.utils.mass_diff Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Calculates the mass difference(s) between two m/z values, either in Daltons or parts per million (ppm). ```APIDOC ## spectrum_utils.utils.mass_diff(mz1, mz2, mode_is_da) ### Description Calculate the mass difference(s). ### Parameters * **mz1** – First m/z value(s). * **mz2** – Second m/z value(s). * **mode_is_da** (bool) – Mass difference in Dalton (True) or in ppm (False). ### Return type The mass difference(s) between the given m/z values. ``` -------------------------------- ### spectrum_utils.proforma.parse Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Parses a ProForma-encoded string into a list of proteoform objects. It interprets the ProForma language, localizes modifications to residue positions, and translates them into Python objects. ```APIDOC ## spectrum_utils.proforma.parse ### Description Parses a ProForma-encoded string into a list of proteoform objects. It interprets the ProForma language, localizes modifications to residue positions, and translates them into Python objects. ### Parameters #### Path Parameters - **proforma** (str) - Required - The ProForma string. ### Returns - **List[[Proteoform](#spectrum_utils.proforma.Proteoform)]** - A list of proteoforms with their modifications (and additional) information specified by the ProForma string. ### Raises - **URLError** - If a controlled vocabulary could not be retrieved from its online resource. - **KeyError** - If a term was not found in its controlled vocabulary. - **NotImplementedError** - Mass calculation using a molecular formula that contains isotopes (not supported by Pyteomics mass calculation). - **ValueError** - If no mass was specified for a GNO term or its parent terms. ``` -------------------------------- ### spectrum_utils.fragment_annotation.FragmentAnnotation Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Represents an individual fragment ion annotation, following the PSI peak interpretation specification. It includes details like ion type, neutral loss, isotope, charge, adduct, and m/z delta. ```APIDOC ## spectrum_utils.fragment_annotation.FragmentAnnotation ### Description Represents an individual fragment ion annotation, following the PSI peak interpretation specification. It includes details like ion type, neutral loss, isotope, charge, adduct, and m/z delta. ### Parameters #### ion_type (*str*) – Specifies the basic type of ion being described. Possible prefixes are: "?": unknown ion, "a", "b", "c", "x", "y", "z": corresponding peptide fragments, "I": immonium ion, "m": internal fragment ion, "_": named compound, "p": precursor ion, "r": reporter ion (isobaric label), "f": chemical formula. #### neutral_loss (*Optional* *[**str* *]*) – A string of neutral loss(es), described by their molecular formula. The default is no neutral loss. Note that the neutral loss string must include the sign (typically "-" for a neutral loss). #### isotope (*int*) – The isotope number above or below the monoisotope. The default is the monoisotopic peak (0). #### charge (*Optional* *[**int* *]*) – The charge of the fragment. The default is an unknown charge (only valid for unknown ions). #### adduct (*Optional* *[**str* *]*) – The adduct that ionized the fragment. The default is a hydrogen adduct matching the charge ([M+xH]). #### mz_delta (*Optional* *[**Tuple* *[**float* *,* *str* *]* *]*) – The m/z delta representing the observed m/z minus the theoretical m/z and its unit ("Da" or "ppm"). ``` -------------------------------- ### Default Ion Annotation Function Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/plotting.md This function defines the default behavior for annotating singly-charged b and y peptide ions, excluding those with neutral loss or isotopes. ```python def annotate_ion_type(annotation, ion_types="by"): if ( annotation.ion_type[0] in ion_types and annotation.neutral_loss is None and annotation.isotope == 0 and annotation.charge == 1 ): return annotation.ion_type else: return "" ``` -------------------------------- ### Scale Spectrum Intensity Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Scales peak intensities using root, log, or rank transformations. Can also scale relative to the most intense peak. ```python spectrum.scale_intensity(scaling='root', degree=3) spectrum.scale_intensity(scaling='log', base=10) spectrum.scale_intensity(scaling='rank', max_rank=100) spectrum.scale_intensity(max_intensity=1000.0) ``` -------------------------------- ### spectrum_utils.plot._annotate_ion Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Annotates a specific fragment peak on a given Axes instance. It handles positioning, coloring, and formatting of the annotation based on provided parameters. ```APIDOC ## spectrum_utils.plot._annotate_ion ### Description Annotates a specific fragment peak on a given Axes instance. It handles positioning, coloring, and formatting of the annotation based on provided parameters. ### Method Signature _annotate_ion(mz: float, intensity: float, annotation: FragmentAnnotation | None, color_ions: bool, annot_fmt: Callable | None, annot_kws: Dict[str, object], ax: matplotlib.pyplot.Axes) -> Tuple[str, int] ### Parameters #### Positional Parameters - **mz** (float) - The peak’s m/z value (position of the annotation on the x axis). - **intensity** (float) - The peak’s intensity (position of the annotation on the y axis). - **annotation** (FragmentAnnotation | None) - The annotation that will be plotted. - **color_ions** (bool) - Flag whether to color the peak annotation or not. - **annot_fmt** (Callable | None) - Function to format the peak annotations. If None, no peaks are annotated. - **annot_kws** (Dict[str, object]) - Keyword arguments for ax.text to customize peak annotations. - **ax** (matplotlib.pyplot.Axes) - Axes instance on which to plot the annotation. ### Returns A tuple containing the annotation's color as a hex string and its zorder. ### Return Type Tuple[str, int] ``` -------------------------------- ### scale_intensity Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Scales the intensity of fragment peaks in an MS/MS spectrum. Supports root, log, and rank transformations, as well as scaling relative to the most intense peak. ```APIDOC ## scale_intensity ### Description Scales the intensity of fragment peaks in an MS/MS spectrum. Supports root, log, and rank transformations, as well as scaling relative to the most intense peak. ### Method ```python scale_intensity(scaling: str | None = None, max_intensity: float | None = None, *, degree: int = 2, base: int = 2, max_rank: int | None = None) ``` ### Parameters #### Keyword Arguments - **scaling** (str | None) - Optional - Method to scale the peak intensities. Potential options are: 'root', 'log', 'rank'. - **max_intensity** (float | None) - Optional - Intensity of the most intense peak relative to which the peaks will be scaled. - **degree** (int) - The degree of the root transformation (default is 2). - **base** (int) - The base of the log transformation (default is 2). - **max_rank** (int | None) - Optional - The maximum rank of the rank transformation (default is None, which uses the number of peaks in the spectrum as maximum rank). max_rank should be greater than or equal to the number of peaks in the spectrum. ### Return type [MsmsSpectrum](#spectrum_utils.spectrum.MsmsSpectrum) ``` -------------------------------- ### round Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Rounds the m/z values of fragment peaks to a specified number of decimal places and combines intensities of peaks with the same m/z after rounding. ```APIDOC ## round(decimals: int = 0, combine: str = 'sum') ### Description Round the m/z values of the fragment peaks to the given number of decimals. Intensities of peaks that have the same m/z value after rounding will be combined using the specified strategy. Note: This peak manipulation will reset any ProForma annotations that were applied previously. ### Parameters #### Parameters * **decimals** (*int*, *optional*) – Number of decimal places to round the mz to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point. * **combine** (*{'sum'*, *'max'}*) – Method used to combine intensities from merged fragment peaks. `sum` specifies that the intensities of the merged fragment peaks will be summed, `max` specifies that the maximum intensity of the fragment peaks that are merged is used (the default is `sum`). ### Return type [MsmsSpectrum] ``` -------------------------------- ### spectrum_utils.plot.mass_errors Source: https://github.com/bittremieuxlab/spectrum_utils/blob/main/docs/src/api.md Plots a mass error bubble plot for a given spectrum, showing the error between observed and theoretical mass against m/z. The size of the bubble is proportional to the peak intensity. ```APIDOC ## spectrum_utils.plot.mass_errors(spec: MsmsSpectrum, *, unit: str | None = None, plot_unknown: bool = True, color_ions: bool = True, grid: bool | str = True, ax: matplotlib.pyplot.Axes | None = None) -> matplotlib.pyplot.Axes ### Description Plot mass error bubble plot for a given spectrum. A mass error bubble plot shows the error between observed and theoretical mass (y-axis) in function of the m/z (x-axis) for each peak in the spectrum. The size of the bubble is proportional to the intensity of the peak. ### Parameters * **spec** (MsmsSpectrum) – The spectrum with mass errors to be plotted. * **unit** (str, optional) – The unit of the mass errors, either ‘ppm’, ‘Da’, or None. If None, the unit that was used for spectrum annotation is used. The default is None. * **plot_unknown** (bool, optional) – Flag indicating whether or not to plot mass errors for unknown peaks. * **color_ions** (bool, optional) – Flag indicating whether or not to color dots for annotated fragment ions. The default is True. * **grid** (Union[bool, str], optional) – Draw grid lines or not. Either a boolean to enable/disable both major and minor grid lines or ‘major’/’minor’ to enable major or minor grid lines respectively. * **ax** (Optional[plt.Axes], optional) – Axes instance on which to plot the mass errors. If None the current Axes instance is used. ### Returns The matplotlib Axes instance on which the mass errors are plotted. ### Return type plt.Axes ```