Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions quantmsutils/psm/psm_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ def convert_psm(

if hit.metaValueExists("MS:1001491"):
global_qvalue = hit.getMetaValue("MS:1001491")
elif hit.metaValueExists("q-value"):
global_qvalue = hit.getMetaValue("q-value")

charge = hit.getCharge()
peptidoform = hit.getSequence().toString()
Expand Down
122 changes: 120 additions & 2 deletions quantmsutils/rescoring/ms2rescore.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,130 @@
import importlib.resources
import json
import logging
from typing import List

import click
import pyopenms as oms
from ms2rescore import package_data, rescore
from psm_utils import PSMList
from psm_utils.io.idxml import IdXMLReader, IdXMLWriter
from typing import Iterable, List, Union
from pathlib import Path
from psm_utils.psm import PSM

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")


class IDXMLReaderPatch(IdXMLReader):
def __init__(self, filename: Union[Path, str], *args, **kwargs) -> None:
"""
Patch Reader for idXML files based on IDXMLReader.

Parameters
----------
filename: str, pathlib.Path
Path to idXML file.

Examples
--------
"""
super().__init__(filename, *args, **kwargs)
self.protein_ids, self.peptide_ids = self._parse_idxml()
self.user_params_metadata = self._get_userparams_metadata(self.peptide_ids[0].getHits()[0])
self.rescoring_features = self._get_rescoring_features(self.peptide_ids[0].getHits()[0])
self.skip_invalid_psm = 0

def __iter__(self) -> Iterable[PSM]:
"""
Iterate over file and return PSMs one-by-one.
Test cases will:

Input PSM 1: PeptideHit with metavalue
"MSGF:ScoreRatio" value="0.212121212121212"/>
"MSGF:Energy" value="130.0"/>
"MSGF:lnEValue" value="-3.603969939390662"/>
"MSGF:lnExplainedIonCurrentRatio" value="-0.881402756873971"/>
"MSGF:lnNTermIonCurrentRatio" value="-1.931878317286471"/>
"MSGF:lnCTermIonCurrentRatio" value="-1.311462733724937"/>
"MSGF:lnMS2IonCurrent" value="9.702930189540499"/>
"MSGF:MeanErrorTop7" value="259.986879999999985"/>
"MSGF:sqMeanErrorTop7" value="6.75931777721344e04"/>
"MSGF:StdevErrorTop7" value="143.678020000000004"/>
PSM2: PeptideHit No above metaValue

Run:
reader = IDXMLReaderPatch(input_file)
psm_list = reader.read_file()

psm_list: return [PSM 1]

"""
for peptide_id in self.peptide_ids:
for peptide_hit in peptide_id.getHits():
psm = self._parse_psm(self.protein_ids, peptide_id, peptide_hit)
if psm is not None:
yield psm
else:
self.skip_invalid_psm += 1

def _parse_psm(
self,
protein_ids: oms.ProteinIdentification,
peptide_id: oms.PeptideIdentification,
peptide_hit: oms.PeptideHit,
) -> PSM:
"""
Parse idXML :py:class:`~pyopenms.PeptideHit` to :py:class:`~psm_utils.psm.PSM`.

Uses additional information from :py:class:`~pyopenms.ProteinIdentification` and
:py:class:`~pyopenms.PeptideIdentification` to annotate parameters of the
:py:class:`~psm_utils.psm.PSM` object.
"""
peptidoform = self._parse_peptidoform(
peptide_hit.getSequence().toString(), peptide_hit.getCharge()
)
# This is needed to calculate a qvalue before rescoring the PSMList
peptide_id_metadata = {
"idxml:score_type": str(peptide_id.getScoreType()),
"idxml:higher_score_better": str(peptide_id.isHigherScoreBetter()),
"idxml:significance_threshold": str(peptide_id.getSignificanceThreshold()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we probably don't use the significance threshold

@ypriverol ypriverol Nov 28, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what do you mean? I think this logic is in the original ms2rescore from @jonasscheid, no @daichengxin? How is it used in ms2rescore?

@ypriverol ypriverol Nov 28, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jpfeuffer is this always annotated: peptide_id.getSignificanceThreshold()?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Afaik MS2Rescore computes the q-value before rescoring and IdXMLWriter puts it as a metaValue in the PeptideHit obj. Maybe you can just get that score and probably you don't need to to any extra steps in that regard

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what do you mean? I think this logic is in the original ms2rescore from @jonasscheid, no @daichengxin? How is it used in ms2rescore?

Yes. This logic is in the original ms2rescore. I only reconstruct parse psm function to skip invalid psm without search engines score features.

@ypriverol ypriverol Nov 29, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jonasscheid This error comes from MSGF+, which produces some PSMs without search engine scores. bigbio/quantms#447

In the new version of OpenMS @timosachsenberg has introduced a patch OpenMS/OpenMS#7713. Im wondering if we need to also remove the PSMs with the latest dummy values:

hit->setMetaValue("MeanErrorAll", 0.0);
hit->setMetaValue("StdevErrorAll", 0.0);
hit->setMetaValue("MeanErrorTop7", 0.0);
hit->setMetaValue("StdevErrorTop7", 0.0);
hit->setMetaValue("MeanRelErrorAll", 0.0);
hit->setMetaValue("StdevRelErrorAll", 0.0);
hit->setMetaValue("MeanRelErrorTop7", 0.0);
hit->setMetaValue("StdevRelErrorTop7", 0.0);

@jpfeuffer @timosachsenberg @daichengxin @jonasscheid

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would keep them an evaluate

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I vote keep if these dummy values have not effect. Are these PSMs likely to appear in the final results or are they filtered out in subsequent steps?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If they are of general low quality I think ms2rescore and percolator will assign a bad score so they get filtered out.
So no problem there. On the other had good hits (e.g., with good denovo or raw score) can still survice the filtering even though the other scores are set to dummy values. I think this is better than just filtering them.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But they will not be used, no? With no score, those PSMS will be noisy all over the place. I can guess they will receive some scores coming from ms2rescore because some new features are introduced, like PEPLEN, PredictedRT, MS2PIP, etc., but the original search engine scores will be gone. In the downstream analysis, this will also be strange because you have PSMs with no Scores.

BTW, @timosachsenberg the version from MSGF+ that OpenMS is using is MS-GF+ Release (v2023.01.12) (12 January 2023), I re-run the dataset with the latest version of MSGF+ here the mziD: bigbio/quantms#447 (comment)

}
peptide_hit_metadata = {
key: peptide_hit.getMetaValue(key) for key in self.user_params_metadata
}

# Get search engines score features and check valueExits
rescoring_features = {}
for key in self.rescoring_features:
feature = peptide_hit.metaValueExists(key)
if not feature:
return None
else:
rescoring_features[key] = float(peptide_hit.getMetaValue(key))

return PSM(
peptidoform=peptidoform,
spectrum_id=peptide_id.getMetaValue("spectrum_reference"),
run=self._get_run(protein_ids, peptide_id),
is_decoy=self._is_decoy(peptide_hit),
score=peptide_hit.getScore(),
precursor_mz=peptide_id.getMZ(),
retention_time=peptide_id.getRT(),
# NOTE: ion mobility will be supported by OpenMS in the future
protein_list=[
accession.decode() for accession in peptide_hit.extractProteinAccessionsSet()
],
rank=peptide_hit.getRank() + 1, # 0-based to 1-based
source="idXML",
# Storing proforma notation of peptidoform and UNIMOD peptide sequence for mapping back
# to original sequence in writer
provenance_data={str(peptidoform): peptide_hit.getSequence().toString()},
# Store metadata of PeptideIdentification and PeptideHit objects
metadata={**peptide_id_metadata, **peptide_hit_metadata},

rescoring_features=rescoring_features,
)


def parse_cli_arguments_to_config(
config_file: str = None,
feature_generators: str = None,
Expand Down Expand Up @@ -119,9 +232,14 @@ def parse_cli_arguments_to_config(
def rescore_idxml(input_file, output_file, config) -> None:
"""Rescore PSMs in an idXML file and keep other information unchanged."""
# Read PSMs
reader = IdXMLReader(input_file)
reader = IDXMLReaderPatch(input_file)
psm_list = reader.read_file()

if reader.skip_invalid_psm != 0:
logging.warning(
f"Removed {reader.skip_invalid_psm} PSMs without search engine features!"
)

# Rescore
rescore(config, psm_list)

Expand Down