コード例 #1
0
    def plot_prediction(
        self,
        peptide,
        modifications,
        charge,
        prediction=None,
        ax=None,
        filename=None,
    ):
        """
        Plot MS²PIP-predicted spectrum with spectrum_utils.

        Parameters
        ----------
        peptide: string
            Unmodified peptide sequence. Only canonical amino acids are allowed, and
            peptide sequence should be of length [3, 100].
        modifications: string
            MS²PIP style-formatted modification string (e.g. `0|Acetyl|5|Oxidation`).
            See MS²PIP README.md for more info.
        charge: int
            Peptide precursor charge.
        prediction: tuple or None (default: None)
            Tuple with `ms2pip.single_prediction.SinglePrediction.predict()` output.
        ax: matplotlib.axes.Axes or None (default: None)
            Figure ax to plot onto.
        filename: str or None (default: None)
            Filename to save plot to. File extension defines the format. Figure will
            not be saved if None.

        """
        if not prediction:
            prediction = self.predict(peptide, modifications, charge)
        mz, intensity, annotation = prediction

        identifier = f"{peptide}/{charge}/{modifications}"
        precursor_mz = self.mod_info.calc_precursor_mz(peptide, modifications,
                                                       charge)
        mod_dict = self._modifications_to_dict(modifications)
        sus_annotation = self._get_sus_annotation(mz, annotation)

        spectrum = sus.MsmsSpectrum(
            identifier,
            precursor_mz,
            charge,
            mz,
            intensity,
            annotation=sus_annotation,
            retention_time=None,
            peptide=peptide,
            modifications=mod_dict,
        )

        if not ax:
            ax = plt.gca()
        sup.spectrum(spectrum, ax=ax)
        ax.set_title("MS²PIP prediction for " + identifier)
        if filename:
            plt.savefig(filename)
コード例 #2
0
def _generate_figure(usi: str, extension: str, **kwargs) -> io.BytesIO:
    fig, ax = plt.subplots(figsize=(kwargs['width'], kwargs['height']))

    kwargs['annotate_peaks'] = kwargs['annotate_peaks'][0]
    spectrum = _prepare_spectrum(usi, **kwargs)
    sup.spectrum(
        spectrum,
        annotate_ions=kwargs['annotate_peaks'],
        annot_kws={
            'rotation': kwargs['annotation_rotation'],
            'clip_on': True
        },
        grid=kwargs['grid'],
        ax=ax,
    )

    ax.set_xlim(kwargs['mz_min'], kwargs['mz_max'])
    ax.set_ylim(0, kwargs['max_intensity'])

    if not kwargs['grid']:
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.yaxis.set_ticks_position('left')
        ax.xaxis.set_ticks_position('bottom')

    title = ax.text(0.5,
                    1.06,
                    usi,
                    horizontalalignment='center',
                    verticalalignment='bottom',
                    fontsize='x-large',
                    fontweight='bold',
                    transform=ax.transAxes)
    title.set_url(f'{USI_SERVER}spectrum/?usi={usi}')
    subtitle = (f'Precursor m/z: '
                f'{spectrum.precursor_mz:.{kwargs["annotate_precision"]}f} '
                if spectrum.precursor_mz > 0 else '')
    subtitle += f'Charge: {spectrum.precursor_charge}'
    subtitle = ax.text(0.5,
                       1.02,
                       subtitle,
                       horizontalalignment='center',
                       verticalalignment='bottom',
                       fontsize='large',
                       transform=ax.transAxes)
    subtitle.set_url(f'{USI_SERVER}spectrum/?usi={usi}')

    buf = io.BytesIO()
    plt.savefig(buf, bbox_inches='tight', format=extension)
    buf.seek(0)
    fig.clear()
    plt.close(fig)
    gc.collect()

    return buf
コード例 #3
0
def plot_spectra(mzml_id, peptide, scan_id, mzml_dir, spec_pic_dir, psm_id):
    mzml_file = str(
        subprocess.check_output("find {} -name {}.mzML".format(
            mzml_dir, mzml_id),
                                shell=True))
    mzml_file = mzml_file.replace("b'", "").replace("\\n'", "")
    with mzml.read(mzml_file) as reader:
        # auxiliary.print_tree(next(reader))
        for scan in reader:
            if not scan["index"] == int(scan_id) - 1:
                continue
            if "precursorList" not in scan.keys():
                print("no precursor list")
                return
            mz = scan['m/z array']
            intensity = scan['intensity array']
            identifier = scan['index']
            retention_time = float(
                scan['scanList']['scan'][0]["scan start time"]) * 60.0
            precursor_mz = scan["precursorList"]["precursor"][0][
                "selectedIonList"]["selectedIon"][0]["selected ion m/z"]
            precursor_charge = int(
                scan["precursorList"]["precursor"][0]["selectedIonList"]
                ["selectedIon"][0]["charge state"])
            spec = spectrum.MsmsSpectrum(identifier,
                                         precursor_mz,
                                         precursor_charge,
                                         mz,
                                         intensity,
                                         retention_time=retention_time,
                                         peptide=peptide)
            min_mz, max_mz = 100, 1400
            fragment_tol_mass, fragment_tol_mode = 10, 'ppm'
            min_intensity, max_num_peaks = 0.05, 150
            scaling = 'root'
            ion_types = 'aby'
            spec = spec.set_mz_range(min_mz, max_mz)
            spec = spec.remove_precursor_peak(fragment_tol_mass,
                                              fragment_tol_mode)
            spec = spec.filter_intensity(min_intensity, max_num_peaks)
            spec = spec.scale_intensity(scaling)
            # spec = spec.annotate_peaks(fragment_tol_mass, fragment_tol_mode, ion_types)
            spec = spec.annotate_peptide_fragments(fragment_tol_mass,
                                                   fragment_tol_mode,
                                                   ion_types)
            plt.figure()
            plot.spectrum(spec, grid=False)
            mzml_id = os.path.splitext(os.path.split(mzml_file)[1])[0]
            plt.savefig("{}/{}_{}.svg".format(spec_pic_dir, mzml_id, psm_id),
                        bbox_inches='tight')
            plt.close()
            print("print")
            return
        else:
            print("Scan not found")
コード例 #4
0
ファイル: spectra_plot.py プロジェクト: xuel12/prosit
def singleplot(feature, file):
    # Read the spectrum from an MGF file using Pyteomics.
    spectrum_dict = mgf.get_spectrum(file, feature)
    # modifications = {8: 15.994915}
    modifications = {}

    identifier = spectrum_dict['params']['title']
    precursor_mz = spectrum_dict['params']['pepmass'][0]
    precursor_charge = spectrum_dict['params']['charge'][0]
    mz = spectrum_dict['m/z array']
    intensity = spectrum_dict['intensity array']
    retention_time = float(spectrum_dict['params']['rtinseconds'])
    peptide = spectrum_dict['params']['seq']

    # # if sorted mz is desired
    # pair = np.vstack([spectrum_dict['m/z array'], spectrum_dict['intensity array']]).T
    # sorted_pair = pair[np.argsort(pair[:, 0])]
    # mz, intensity = [sorted_pair[:,0], sorted_pair[:,1]]

    # Create the MS/MS spectrum.
    spectrum = sus.MsmsSpectrum(identifier, precursor_mz, precursor_charge, mz, intensity, \
                                retention_time=retention_time, peptide=peptide, \
                                modifications=modifications)

    # Process the MS/MS spectrum.
    fragment_tol_mass = 0.5
    fragment_tol_mode = 'Da'
    min_mz = 100
    min_intensity = 0.05
    spectrum = (
        spectrum.set_mz_range(min_mz=min_mz,
                              max_mz=1400).remove_precursor_peak(
                                  fragment_tol_mass,
                                  fragment_tol_mode).filter_intensity(
                                      min_intensity=min_intensity,
                                      max_num_peaks=50)
        # .scale_intensity('root')
        .annotate_peptide_fragments(fragment_tol_mass,
                                    fragment_tol_mode,
                                    ion_types='aby'))
    # # label the mz for all peaks
    # annotate_fragment_mz = sorted_pair[(sorted_pair[:,0]>min_mz) & (sorted_pair[:,1]>min_intensity), 0]
    # for fragment_mz in annotate_fragment_mz:
    #     spectrum.annotate_mz_fragment(fragment_mz, 1, fragment_tol_mass, fragment_tol_mode)

    # Plot the MS/MS spectrum.
    fig, ax = plt.subplots(figsize=(12, 6))
    plt.title(identifier)
    sup.spectrum(spectrum, ax=ax)
    plt.show()
    plt.close()
コード例 #5
0
def generate_graph(file_path: str):
    annotate_mz = []
    file_name = os.path.basename(file_path[:-4])

    print("kai3")
    mz, intensity = read_file(f"{file_path}")
    spectrum = sus.MsmsSpectrum(
        file_name,
        1.0,
        1,
        mz,
        intensity,
    )
    annotate_mz = set([
        int(m) for i, m in zip(spectrum.intensity, spectrum.mz)
        if i / spectrum.intensity.max() >= 0.10
    ])
    smplfy_new_lst = []
    for i in annotate_mz:
        if smplfy_new_lst == [] or abs(smplfy_new_lst[-1] - i) > 3:
            smplfy_new_lst.append(i)

    print(smplfy_new_lst)
    for ano_mz in smplfy_new_lst:
        spectrum.annotate_mz_fragment(
            ano_mz,
            1,
            3,
            "Da",
        )
    print("kai4")

    fig, ax = plt.subplots(figsize=(12, 6))
    save_path = os.path.join(os.path.dirname(file_path), "graph")
    try:
        os.makedirs(save_path)
    except:
        pass
    sup.spectrum(spectrum, ax=ax)
    fig.savefig(os.path.join(save_path, f"{file_name}.png"), dpi=600)
    plt.close()
コード例 #6
0
def show_spectrum(spectrum_dict, xlim=None):

    identifier = spectrum_dict['title']
    precursor_mz = spectrum_dict['pepmass'][0]
    precursor_charge = spectrum_dict['charge'][0]
    mz = spectrum_dict['m/z']
    intensity = spectrum_dict['intensity']

    # Create the MS/MS spectrum.
    spectrum = sus.MsmsSpectrum(identifier, precursor_mz, precursor_charge, mz,
                                intensity)
    spectrum.filter_intensity(0.01)
    spectrum.scale_intensity('root')

    fig, ax = plt.subplots(figsize=(12, 6))
    sup.spectrum(spectrum, ax=ax)

    if xlim is not None:
        plt.xlim(right=xlim)
    plt.show()
    plt.close()
コード例 #7
0
    from spectrum_utils.spectrum import MsmsSpectrum
    import spectrum_utils.plot as plot
    import matplotlib.pyplot as plt

    spectrum_stream = repo_spectrum.get_stream(include_null=False, limit=100)
    count = 0
    for spectrum in spectrum_stream:
        # print(spectrum.spec_id)
        peaks_nr = spectrum.peaks_cut_noise(mod='dynamic')
        if peaks_nr.shape[1]:
            temp = MsmsSpectrum(identifier=spectrum.spec_id, precursor_mz=spectrum.prec_mz, precursor_charge=1,
                                mz=peaks_nr[:, 0],
                                intensity=peaks_nr[:, 1])

            plt.figure(figsize=(6, 4), dpi=300)
            ax = plot.spectrum(temp)

            output_folder = 'out/spectra/{}_{}/{}/{}/'.format(spectrum.snapeaks_id, spectrum.inchikey,
                                                              spectrum.instrument_type, spectrum.prec_type)
            tool_file.mkdir_folder(output_folder)

            # i = 0
            output_file = output_folder + '{}eV_specid_{}.png'.format(spectrum.collision_energy, spectrum.spec_id)
            # while os.path.exists(output_file):
            #     i += 1
            #     output_file = output_folder + '{}eV_specid_{}.png'.format(spectrum.collision_energy, spectrum.spec_id)

            plt.savefig(output_file)
            plt.close()
        count += 1
        if count % 1000 == 0:
コード例 #8
0
def generate_figure(spectrum: sus.MsmsSpectrum, extension: str,
                    **kwargs: Any) -> io.BytesIO:
    """
    Generate a spectrum plot.

    Parameters
    ----------
    spectrum : sus.MsmsSpectrum
        The spectrum to be plotted.
    extension : str
        Image format.
    kwargs : Any
        Plotting settings.

    Returns
    -------
    io.BytesIO
        Bytes buffer containing the spectrum plot.
    """
    usi = spectrum.identifier

    fig, ax = plt.subplots(figsize=(kwargs["width"], kwargs["height"]))

    sup.spectrum(
        spectrum,
        annotate_ions=kwargs["annotate_peaks"],
        annot_kws={
            "rotation": kwargs["annotation_rotation"],
            "clip_on": True
        },
        grid=kwargs["grid"],
        ax=ax,
    )

    ax.set_xlim(kwargs["mz_min"], kwargs["mz_max"])
    ax.set_ylim(0, kwargs["max_intensity"] / 100)

    if not kwargs["grid"]:
        ax.spines["right"].set_visible(False)
        ax.spines["top"].set_visible(False)
        ax.yaxis.set_ticks_position("left")
        ax.xaxis.set_ticks_position("bottom")

    title = ax.text(
        0.5,
        1.06,
        kwargs["usi1"],
        horizontalalignment="center",
        verticalalignment="bottom",
        fontsize="x-large",
        fontweight="bold",
        transform=ax.transAxes,
    )
    title.set_url(f"{USI_SERVER}spectrum/?usi1={usi}")
    subtitle = (f"Precursor $m$/$z$: "
                f'{spectrum.precursor_mz:.{kwargs["annotate_precision"]}f} '
                if spectrum.precursor_mz > 0 else "")
    subtitle += f"Charge: {spectrum.precursor_charge}"
    subtitle = ax.text(
        0.5,
        1.02,
        subtitle,
        horizontalalignment="center",
        verticalalignment="bottom",
        fontsize="large",
        transform=ax.transAxes,
    )
    subtitle.set_url(f"{USI_SERVER}spectrum/?usi1={usi}")

    buf = io.BytesIO()
    plt.savefig(buf, bbox_inches="tight", format=extension)
    buf.seek(0)
    fig.clear()
    plt.close(fig)
    gc.collect()

    return buf