Skip to content

feature: Nucleotide-Protein search engine NuXL - #7815

Merged
timosachsenberg merged 462 commits into
developfrom
feature/NuXL
Jun 25, 2025
Merged

timosachsenberg merged 462 commits into
developfrom
feature/NuXL

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jan 22, 2025 •

Copy link
Copy Markdown
Contributor

Description

This PR brings the NuXL search engine into the develop branch. It’s been thoroughly tested, but getting it into a mergeable state was a bit of a challenge, so bear with me if I’ve overlooked anything! 😅

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

How can I get additional information on failed tests during CI

Click to expand If your PR is failing you can check out

Advanced commands (admins / reviewer only)

Click to expand
  • /reformat (experimental) applies the clang-format style changes as additional commit. Note: your branch must have a different name (e.g., yourrepo:feature/XYZ) than the receiving branch (e.g., OpenMS:develop). Otherwise, reformat fails to push.
  • setting the label "NoJenkins" will skip tests for this PR on jenkins (saves resources e.g., on edits that do not affect tests)
  • commenting with rebuild jenkins will retrigger Jenkins-based CI builds

⚠️ Note: Once you opened a PR try to minimize the number of pushes to it as every push will trigger CI (automated builds and test) and is rather heavy on our infrastructure (e.g., if several pushes per day are performed).

Summary by CodeRabbit

  • New Features

    • Introduced the OpenNuXL tool for peptide-RNA/DNA cross-linking identification.
    • Added extensive support for nucleotide cross-linking analysis, including customizable presets, advanced fragment ion generation, deisotoping, and detailed reporting.
    • Implemented adapted false discovery rate (FDR) calculations specific to cross-linked peptides.
    • Enabled configuration of RNA/DNA modifications and adducts through JSON presets.
    • Expanded export functionality to include peak annotations in peptide reports.
    • Enhanced scoring methods to consider charge states and mass errors in peptide identification.
  • Bug Fixes

    • Enhanced isotope error handling and mass error calculations in search algorithms.
    • Improved error handling and robustness in peptide and protein processing workflows.
  • Documentation

    • Added detailed README and usage documentation for OpenNuXL presets and parameters.
  • Tests

    • Added comprehensive unit and integration tests covering NuXL modifications, parameter parsing, deisotoping, and scoring.
  • Chores

    • Integrated NuXL source and header files into build and test configurations.
    • Updated naming conventions, replacing legacy RNPxl references with NuXL for consistency.

timosachsenberg and others added 30 commits February 28, 2021 09:39
* Additional features in SimpleSearchEngine

* add missing constants

* update test file

Co-authored-by: timosachsenberg <[email protected]>

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 0

♻️ Duplicate comments (3)
src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp (3)

55-159: Refactor this complex method into smaller helper functions.

The method handles multiple responsibilities that could be separated:

  • Precursor adduct to mass/formula mapping (lines 65-102)
  • Feasible adduct calculation and ambiguity tracking (lines 104-138)
  • Indistinguishable cross-link detection and reporting (lines 140-156)

Consider extracting these into separate helper methods to improve readability and maintainability.


230-241: Fix debug code issues.

The debug code has two issues:

  1. Uses cout instead of OPENMS_LOG_DEBUG
  2. References undefined variable precursor_to_fragment_adducts

Apply this diff to fix:

 #ifdef DEBUG_OpenNuXL
-  for (auto const & p2fas : precursor_to_fragment_adducts)
+  for (auto const & n2fas : nucleotide_to_fragment_adducts)
     {
-      for (auto const & p2fa : p2fas.second)
+      for (auto const & fa : n2fas.second)
       {
-        cout << "nucleotide:" << p2fas.first
-             << " fragment adduct:" << p2fa.formula.toString()
-             << " fragment adduct mass:" << p2fa.mass
-             << " name:" <<  p2fa.name << endl;
+        OPENMS_LOG_DEBUG << "nucleotide:" << n2fas.first
+                         << " fragment adduct:" << fa.formula.toString()
+                         << " fragment adduct mass:" << fa.mass
+                         << " name:" << fa.name << endl;
       }
     }
 #endif

307-307: Replace cout with appropriate logging.

Direct console output should use the logging framework.

-    cout << "Mandatory cross-linking nt/sugar: " << *must_xl.begin() << " in precursor adduct: " << exp_pc_adduct  << endl;
+    OPENMS_LOG_INFO << "Mandatory cross-linking nt/sugar: " << *must_xl.begin() << " in precursor adduct: " << exp_pc_adduct  << endl;
🧹 Nitpick comments (1)
src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp (1)

249-468: Consider refactoring this long method.

The method spans 219 lines and handles multiple distinct cases. Consider extracting:

  • Oligonucleotide processing logic (lines 323-356) into a separate method
  • Monomer processing logic (lines 358-398) into a separate method
  • Default marker ion addition (lines 402-427) into a separate method

This would improve readability and make the code easier to test and maintain.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between db84808 and e4b61fd.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp (1 hunks)
🧰 Additional context used
🪛 GitHub Check: CodeFactor
src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp

[notice] 51-156: src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp#L51-L156
Complex Method

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: cppcheck-test
🔇 Additional comments (2)
src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp (2)

24-53: LGTM!

The implementation correctly aggregates and deduplicates marker ions by mass.


471-497: LGTM!

Clean implementation for retrieving modifications with proper handling of terminal specificity.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

♻️ Duplicate comments (3)
src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp (3)

55-159: Method complexity needs refactoring.

This method performs multiple distinct tasks and could benefit from being split into smaller, focused helper methods.


230-241: Debug code has unresolved issues.

The debug block uses cout instead of logging and references undefined variable precursor_to_fragment_adducts.


307-307: Console output should use logging framework.

Direct console output should be replaced with the appropriate logging mechanism.

🧹 Nitpick comments (2)
src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp (2)

18-18: Avoid using namespace std in implementation files.

While less problematic than in headers, it's still better practice to use explicit std:: prefixes or specific using declarations.


355-355: Consider using regular copy instead of std::move from set.

Moving elements from a set can be problematic and may not provide performance benefits unless the elements have expensive copy operations.

-    std::move(std::begin(marker_ion_set), std::end(marker_ion_set), std::back_inserter(ret.marker_ions));
+    std::copy(marker_ion_set.begin(), marker_ion_set.end(), std::back_inserter(ret.marker_ions));
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f279de7 and 5559f45.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp (1 hunks)
🧰 Additional context used
🪛 GitHub Check: CodeFactor
src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp

[notice] 51-156: src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp#L51-L156
Complex Method

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: cppcheck-test
🔇 Additional comments (2)
src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp (2)

24-53: Well-implemented marker ion extraction.

The method efficiently extracts and deduplicates marker ions using appropriate STL algorithms and clear lambda functions.


471-497: Clean implementation of modification retrieval.

The method correctly handles different modification types with clear logic.

Comment on lines +250 to +468
NuXLParameterParsing::getFeasibleFragmentAdducts(const String &exp_pc_adduct,
const String &exp_pc_formula,
const NuXLParameterParsing::NucleotideToFragmentAdductMap &nucleotide_to_fragment_adducts,
const set<char> &can_xl,
const bool always_add_default_marker_ions,
const bool default_marker_ions_RNA)
{
OPENMS_LOG_DEBUG << "Generating fragment adducts for precursor adduct: '" << exp_pc_adduct << "'" << endl;

MS2AdductsOfSinglePrecursorAdduct ret;

// no precursor adduct?
if (exp_pc_formula.empty()) { return ret; } // no fragment adducts or marker ions are expected!

// count nucleotides in precursor adduct (e.g.: "TCA-H2O" yields map: T->1, C->1, A->1)
// and determine the set of cross-linkable nucleotides in the precursor adduct
size_t nt_count(0);

set<char> exp_pc_xl_nts; // the cross-linkable nucleotides in the precursor adduct
map<char, Size> exp_pc_nucleotide_count; // all nucleotides in the precursor adduct (e.g., used to determine marker ions)

{
for (String::const_iterator exp_pc_it = exp_pc_adduct.begin(); exp_pc_it != exp_pc_adduct.end(); ++exp_pc_it, ++nt_count)
{
// we are finished with nucleotides in string if first loss/gain is encountered
if (*exp_pc_it == '+' || *exp_pc_it == '-') break;

// count occurence of nucleotide
if (exp_pc_nucleotide_count.count(*exp_pc_it) == 0)
{
exp_pc_nucleotide_count[*exp_pc_it] = 1;
if (can_xl.count(*exp_pc_it)) { exp_pc_xl_nts.insert(*exp_pc_it); };
}
else
{
exp_pc_nucleotide_count[*exp_pc_it]++;
}
}
}

// check if at least one nucleotide present that can cross link
bool has_xl_nt = !exp_pc_xl_nts.empty();
OPENMS_LOG_DEBUG << "\t" << exp_pc_adduct << " has cross-linkable nucleotide (0 = false, 1 = true): " << has_xl_nt << endl;

// no cross-linkable nt contained in the precursor adduct? Return an empty fragment adduct definition set
if (!has_xl_nt) { return ret; }

// determine if there is a nucleotide/sugar/etc. that must be the cross-linked one
set<char> must_xl;
for (auto c : exp_pc_xl_nts) { if (c == 'd' || c == 'r') must_xl.insert(c); }
if (must_xl.size() >= 2)
{
OPENMS_LOG_WARN << "More than one nucleotide present that is marked as mandatory cross-linked ('d' or 'r')." << endl;
return ret;
}
else if (must_xl.size() == 1)
{
cout << "Mandatory cross-linking nt/sugar: " << *must_xl.begin() << " in precursor adduct: " << exp_pc_adduct << endl;
exp_pc_xl_nts = must_xl;
}
// else we have no mandatory cross-linked nts

///////////////////////////////////////////////////////////////////
// HERE: at least one cross-linkable nt present in precursor adduct

// extract loss string from precursor adduct (e.g.: "-H2O")
// String exp_pc_loss_string(exp_pc_it, exp_pc_adduct.end());

OPENMS_LOG_DEBUG << "\t" << exp_pc_adduct << " is monomer (1 = true, >1 = false): " << nt_count << endl;

// Handle the cases of monomer or oligo nucleotide bound to the precursor.
// This distinction is made because potential losses on the precursor only allows us to reduce the set of chemical feasible fragment adducts if they are on a monomer.
// In the case of an oligo we can't be sure if the cross-linked amino acid or any other in the oligo had the loss.
if (nt_count > 1) // No monomer? For every nucleotide that can be cross-linked: Create all fragment adducts without restriction by losses (no restriction as the loss could be on the other nts)
{
// for each nucleotide and potential set of fragment adducts
for (auto const & n2fa : nucleotide_to_fragment_adducts)
{
const char & nucleotide = n2fa.first; // the nucleotide without any associated loss
const set<NuXLFragmentAdductDefinition>& fragment_adducts = n2fa.second; // all potential fragment adducts that may arise from the unmodified nucleotide

// check if nucleotide is cross-linkable and part of the precursor adduct
if (exp_pc_xl_nts.find(nucleotide) != exp_pc_xl_nts.end())
{
OPENMS_LOG_DEBUG << "\t" << exp_pc_adduct << " found nucleotide: " << String(nucleotide) << " in precursor RNA." << endl;
OPENMS_LOG_DEBUG << "\t" << exp_pc_adduct << " nucleotide: " << String(nucleotide) << " has fragment_adducts: " << fragment_adducts.size() << endl;

// store feasible adducts associated with a cross-link with character nucleotide
vector<NuXLFragmentAdductDefinition> faa;
std::copy(fragment_adducts.begin(), fragment_adducts.end(), back_inserter(faa));
ret.feasible_adducts.emplace_back(make_pair(nucleotide, faa));
}
}

// Create set of marker ions for *all* nucleotides contained in the precursor adduct (including those that do not cross-link.)
// Note: The non-cross-linked nt in the precursor adduct are more likely to produce the marker ions (=more fragile than the cross-linked nt).
set<NuXLFragmentAdductDefinition> marker_ion_set;
for (auto const & n2fa : nucleotide_to_fragment_adducts)
{
const char & nucleotide = n2fa.first; // the nucleotide without any associated loss
if (exp_pc_nucleotide_count.find(nucleotide) != exp_pc_nucleotide_count.end())
{
marker_ion_set.insert(n2fa.second.begin(), n2fa.second.end());
}
}
std::move(std::begin(marker_ion_set), std::end(marker_ion_set), std::back_inserter(ret.marker_ions));
}
else // nt_count == 1: monomer. We need to check if the neutral loss reduces the set of feasible (e.g., chemically sound) fragment adducts
{
for (auto const & n2fa : nucleotide_to_fragment_adducts)
{
const char & nucleotide = n2fa.first; // one letter code of the nt

set<NuXLFragmentAdductDefinition> fas = n2fa.second; // all potential fragment adducts that may arise from NT assuming no loss on the precursor adduct

// check if nucleotide is cross-linkable and part of the precursor adduct
if (exp_pc_xl_nts.find(nucleotide) != exp_pc_xl_nts.end())
{
OPENMS_LOG_DEBUG << "\t" << exp_pc_adduct << " found nucleotide: " << String(nucleotide) << " in precursor NA adduct." << endl;
OPENMS_LOG_DEBUG << "\t" << exp_pc_adduct << " nucleotide: " << String(nucleotide) << " has fragment_adducts: " << fas.size() << endl;

// check chemical feasibility by checking if subtraction of adduct would result in negative elemental composition
for (auto it = fas.begin(); it != fas.end(); )
{
bool negative_elements = (EmpiricalFormula(exp_pc_formula) - it->formula).toString().hasSubstring("-");

if (negative_elements) // fragment adduct can't be subformula of precursor adduct
{
it = fas.erase(it);
}
else
{
++it; // STL erase idiom (mind the pre-increment)
}
}

if (fas.empty()) continue; // no feasible fragment adducts left? continue

// store feasible adducts associated with a cross-link with character nucleotide[0]
vector<NuXLFragmentAdductDefinition> faa;
std::copy(fas.begin(), fas.end(), back_inserter(faa));
ret.feasible_adducts.emplace_back(make_pair(nucleotide, faa));

// We only have one nucleotide in the precursor adduct (the cross-linked one)
// Note: marker ions of the cross-linked nucleotide are often missing or of very low intensity
std::copy(std::begin(fas), std::end(fas), std::back_inserter(ret.marker_ions));
}
}
}

// for chemical cross-linkers like DEB, fragments always carry DEB but marker ions might just be U or U' (and losses)
// In that case we need to ensure that the the default marker ions are added
if (always_add_default_marker_ions)
{
// Note: add the uncharged mass. Protons are added during spectrum generation.
if (default_marker_ions_RNA) // TODO: check if we can derive this from target nucleotides
{
ret.marker_ions.emplace_back(EmpiricalFormula("C9H13N2O9P1"), String("U"), EmpiricalFormula("C9H13N2O9P1").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C9H14N3O8P"), "C", EmpiricalFormula("C9H14N3O8P").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C10H14N5O8P"), "G", EmpiricalFormula("C10H14N5O8P").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C10H14N5O7P"), "A", EmpiricalFormula("C10H14N5O7P").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C4H4N2O2"), "U'", EmpiricalFormula("C4H4N2O2").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C4H5N3O"), "C'", EmpiricalFormula("C4H5N3O").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C5H5N5O"), "G'", EmpiricalFormula("C5H5N5O").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C5H5N5"), "A'", EmpiricalFormula("C5H5N5").getMonoWeight());
}
else // DNA
{
ret.marker_ions.emplace_back(EmpiricalFormula("C10H15N2O8P"), "T", EmpiricalFormula("C10H15N2O8P").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C9H14N3O7P"), "C", EmpiricalFormula("C9H14N3O7P").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C10H14N5O7P"), "G", EmpiricalFormula("C10H14N5O7P").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C10H14N5O6P"), "A", EmpiricalFormula("C10H14N5O6P").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C5H6N2O2"), "T'", EmpiricalFormula("C5H6N2O2").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C4H5N3O"), "C'", EmpiricalFormula("C4H5N3O").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C5H5N5O"), "G'", EmpiricalFormula("C5H5N5O").getMonoWeight());
ret.marker_ions.emplace_back(EmpiricalFormula("C5H5N5"), "A'", EmpiricalFormula("C5H5N5").getMonoWeight());
}
}


// Because, e.g., ribose might be a feasible fragment of any nucleotide, we keep only one version
// Note: sort by formula and (as tie breaker) the name
std::sort(ret.marker_ions.begin(), ret.marker_ions.end(),
[](NuXLFragmentAdductDefinition const & a, NuXLFragmentAdductDefinition const & b)
{
const String as = a.formula.toString();
const String bs = b.formula.toString();
return std::tie(as, a.name) < std::tie(bs, b.name);
}
);
// Note: for uniqueness, we only rely on the formula (in case of tie: keeping the first = shortest name)
auto it = std::unique(ret.marker_ions.begin(), ret.marker_ions.end(),
[](NuXLFragmentAdductDefinition const & a, NuXLFragmentAdductDefinition const & b)
{
return a.formula == b.formula;
}
);
ret.marker_ions.resize(std::distance(ret.marker_ions.begin(), it));

// print feasible fragment adducts
for (auto const & ffa : ret.feasible_adducts)
{
const char & nucleotide = ffa.first;
OPENMS_LOG_DEBUG << " Cross-linkable nucleotide '" << nucleotide << "' and feasible fragment adducts:" << endl;
for (auto const & a : ffa.second)
{
OPENMS_LOG_DEBUG << "\t" << a.name << "\t" << a.formula.toString() << "\t" << a.mass << "\n";
}
}

// print marker ions
OPENMS_LOG_DEBUG << " Marker ions:" << endl;
for (auto const & a : ret.marker_ions)
{
OPENMS_LOG_DEBUG << "\t" << a.name << "\t" << a.formula.toString() << "\t" << a.mass << "\n";
}

return ret;
}

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.

🛠️ Refactor suggestion

Refactor this complex method for better maintainability.

This 200+ line method handles multiple scenarios and would benefit from being split into smaller, focused helper methods:

  • Extract nucleotide counting logic (lines 266-288)
  • Extract monomer handling (lines 357-398)
  • Extract oligonucleotide handling (lines 323-355)
  • Extract marker ion addition logic (lines 400-427)

Would you like me to help create a refactored version with smaller, more focused methods?

🤖 Prompt for AI Agents
In src/openms/source/ANALYSIS/NUXL/NuXLParameterParsing.cpp between lines 250
and 468, the getFeasibleFragmentAdducts method is overly long and complex,
making it hard to maintain. Refactor by extracting the nucleotide counting logic
(lines 266-288) into a separate helper function, isolate the oligonucleotide
handling code (lines 323-355) into its own method, move the monomer handling
code (lines 357-398) into another helper, and separate the marker ion addition
logic (lines 400-427) into a dedicated function. This will improve readability
and maintainability without changing functionality.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/openms/source/ANALYSIS/ID/HyperScore.cpp (2)

190-283: Consider performance implications of the peak matching approach.

The new charge-aware compute method introduces important functionality, but uses findNearest instead of MatchedIterator which may be less efficient for large spectra. Additionally, there's significant code duplication with the existing methods.

Performance concern: The findNearest approach (line 238) performs O(log n) search for each theoretical peak, potentially resulting in O(m log n) complexity compared to the more efficient MatchedIterator used in existing methods.

Code duplication: Consider extracting common logic into helper functions to reduce duplication between the charge-aware and standard methods.

// Consider using MatchedIterator with charge filtering instead:
-      Size index = exp_spectrum.findNearest(theo_mz);
-      const double exp_mz = exp_spectrum[index].getMZ();
-      // ... charge and tolerance checks
+      // Use MatchedIterator with additional charge filtering logic

245-247: Replace debug output with proper logging mechanism.

The current debug output uses std::cout and #ifdef DEBUG_HYPERSCORE, which is not ideal for a library component. Consider using OpenMS logging facilities instead.

#ifdef DEBUG_HYPERSCORE
- std::cout << "exp_z != theo_z " << exp_z << "\t" << theo_z << std::endl;
+ OPENMS_LOG_DEBUG << "exp_z != theo_z " << exp_z << "\t" << theo_z << std::endl;
#endif

This approach would be more consistent with OpenMS logging practices and provide better control over debug output.

Also applies to: 266-268, 343-345, 361-364, 376-378, 411-413

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5559f45 and 135c38f.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/ID/HyperScore.cpp (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: cppcheck-test
🔇 Additional comments (1)
src/openms/source/ANALYSIS/ID/HyperScore.cpp (1)

20-33: LGTM! Improved accuracy with std::lgamma.

The refactoring to use std::lgamma instead of manual factorial calculations provides better numerical accuracy and efficiency. The logic correctly computes log(x!) - log((base-1)!) = lgamma(x+1) - lgamma(base), and proper edge case handling is maintained.

Comment on lines 286 to 416

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.

⚠️ Potential issue

Ensure boundary safety in peptide position mapping.

The intensity accumulation logic maps ion positions to peptide coordinates, but lacks bounds checking which could lead to out-of-bounds access.

Potential out-of-bounds access:

  • Line 366: y_ions[N-1 - (ii-1)] could access invalid indices if ii is larger than expected
  • Line 381: b_ions[ii - 1] could access negative indices if ii is 0 or if ii-1 >= N

Required fix:

// Add bounds checking for y-ions
+ if (ii > 0 && ii <= static_cast<int>(N)) {
    y_ions[N-1 - (ii-1)] += exp_spectrum[index].getIntensity();
+ } else {
+   std::cout << "Warning: y-ion position " << ii << " out of bounds for peptide length " << N << std::endl;
+ }

// Add bounds checking for b-ions  
+ if (ii > 0 && ii <= static_cast<int>(N)) {
    b_ions[ii - 1] += exp_spectrum[index].getIntensity();
+ } else {
+   std::cout << "Warning: b-ion position " << ii << " out of bounds for peptide length " << N << std::endl;
+ }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/openms/source/ANALYSIS/ID/HyperScore.cpp between lines 286 and 416, the
code updates y_ions and b_ions vectors using indices derived from ii without
verifying if these indices are within valid bounds, risking out-of-bounds
access. To fix this, add explicit boundary checks before updating
y_ions[N-1-(ii-1)] and b_ions[ii-1] to ensure the indices are >= 0 and less than
N, and skip the update if the indices are invalid.

Comment on lines 352 to 383

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.

🛠️ Refactor suggestion

Validate string parsing robustness and consider error handling improvements.

The ion name parsing logic is complex and could benefit from more robust error handling. The current implementation silently continues on parsing failures, which might mask data quality issues.

String parsing concerns:

  1. Line 357: StringUtils::extractInt failure is handled with continue, but this might silently skip valid ions due to unexpected ion name formats
  2. Lines 354-355, 370-371: Direct iterator arithmetic assumes ion names start with single character (y/b) followed immediately by digits

Suggested improvements:

// Add validation and logging for better debugging
if ((*ion_names)[i][0] == 'y')
{
+  if ((*ion_names)[i].size() < 2) {
+    std::cout << "Warning: Invalid y-ion name format: " << (*ion_names)[i] << std::endl;
+    continue;
+  }
  auto start = (*ion_names)[i].begin() + 1;
  auto end = (*ion_names)[i].end();
  int ii(0);
-  if (!StringUtils::extractInt(start, end, ii)) continue;
+  if (!StringUtils::extractInt(start, end, ii)) {
+    std::cout << "Warning: Failed to parse ion number from: " << (*ion_names)[i] << std::endl;
+    continue;
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if ((*ion_names)[i][0] == 'y')
{
auto start = (*ion_names)[i].begin() + 1;
auto end = (*ion_names)[i].end();
int ii(0);
if (!StringUtils::extractInt(start, end, ii)) continue;
dot_product += exp_spectrum[index].getIntensity() * theo_intensity;
#ifdef DEBUG_HYPERSCORE
std::cout << (*ion_names)[i] << " intensity: " << exp_spectrum[index].getIntensity() << std::endl;
std::cout << "N:" << N << "\t" << ii << "\t" << N-1 - (ii-1) << std::endl;
#endif
// we observed the suffix (N-1-ii, N-1] in 0-based AA coordinates
y_ions[N-1 - (ii-1)] += exp_spectrum[index].getIntensity();
}
else if ((*ion_names)[i][0] == 'b')
{
auto start = (*ion_names)[i].begin() + 1;
auto end = (*ion_names)[i].end();
int ii(0);
if (!StringUtils::extractInt(start, end, ii)) continue;
dot_product += exp_spectrum[index].getIntensity() * theo_intensity;
#ifdef DEBUG_HYPERSCORE
std::cout << (*ion_names)[i] << " intensity: " << exp_spectrum[index].getIntensity() << std::endl;
std::cout << "N:" << N << "\t" << ii << "\t" << (ii-1) << std::endl;
#endif
// we observed the prefix [0, ii) in 0-based AA coordinates
b_ions[ii - 1] += exp_spectrum[index].getIntensity();
}
}
if ((*ion_names)[i][0] == 'y')
{
// Added sanity check for very short/invalid names
if ((*ion_names)[i].size() < 2) {
std::cout << "Warning: Invalid y-ion name format: " << (*ion_names)[i] << std::endl;
continue;
}
auto start = (*ion_names)[i].begin() + 1;
auto end = (*ion_names)[i].end();
int ii(0);
// Now logs a warning instead of silently continuing
if (!StringUtils::extractInt(start, end, ii)) {
std::cout << "Warning: Failed to parse ion number from: " << (*ion_names)[i] << std::endl;
continue;
}
dot_product += exp_spectrum[index].getIntensity() * theo_intensity;
#ifdef DEBUG_HYPERSCORE
std::cout << (*ion_names)[i] << " intensity: " << exp_spectrum[index].getIntensity() << std::endl;
std::cout << "N:" << N << "\t" << ii << "\t" << N-1 - (ii-1) << std::endl;
#endif
// we observed the suffix (N-1-ii, N-1] in 0-based AA coordinates
y_ions[N-1 - (ii-1)] += exp_spectrum[index].getIntensity();
}
else if ((*ion_names)[i][0] == 'b')
{
auto start = (*ion_names)[i].begin() + 1;
auto end = (*ion_names)[i].end();
int ii(0);
if (!StringUtils::extractInt(start, end, ii)) continue;
dot_product += exp_spectrum[index].getIntensity() * theo_intensity;
#ifdef DEBUG_HYPERSCORE
std::cout << (*ion_names)[i] << " intensity: " << exp_spectrum[index].getIntensity() << std::endl;
std::cout << "N:" << N << "\t" << ii << "\t" << (ii-1) << std::endl;
#endif
// we observed the prefix [0, ii) in 0-based AA coordinates
b_ions[ii - 1] += exp_spectrum[index].getIntensity();
}
}
🤖 Prompt for AI Agents
In src/openms/source/ANALYSIS/ID/HyperScore.cpp between lines 352 and 383, the
ion name parsing assumes the first character is 'y' or 'b' followed immediately
by digits, and silently continues on integer extraction failure, which may hide
data issues. To fix this, add explicit checks to ensure the ion name length is
sufficient before iterator arithmetic, validate the format more robustly before
calling extractInt, and replace silent continue on failure with logging or error
handling to flag unexpected formats or parsing errors for better traceability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants