Skip to content

[FIX] OpenNuXL: score every same-formula adduct and cross-linkable nucleotide - #10746

Closed
TomSmithCGAT wants to merge 3 commits into
OpenMS:developfrom
TomSmithCGAT:fix/nuxl-scoring-loop-localisation
Closed

TomSmithCGAT wants to merge 3 commits into
OpenMS:developfrom
TomSmithCGAT:fix/nuxl-scoring-loop-localisation

Conversation

@TomSmithCGAT

@TomSmithCGAT TomSmithCGAT commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #10739. In slow scoring (the default), OpenNuXL scores only the first adduct of each precursor sum formula and only the alphabetically first cross-linkable nucleotide. Fast scoring copies and rescores hits with the wrong adduct. Once every adduct is scored, localisation of a hit on a second adduct reads past the end of a vector and can abort the run with std::length_error. This PR fixes all three.

Scoring every adduct and nucleotide creates copies of a hit that differ only in adduct or nucleotide. The PR keeps their side effects in check:

  • the candidate count stays as on develop;
  • the total-loss part is scored once per spectrum;
  • copies don't take several report:top_hits slots;
  • score ties resolve the same way on every run.

Changes

Line numbers are on develop before this PR.

Slow scoring

  • OpenNuXL.cpp 5568, 5753, 5961: for (auto & l = low_it; ...) → for (auto l = low_it; ...). The reference advanced low_it itself, so after the first nucleotide of the first adduct, low_it == up_it and the remaining adducts and nucleotides got no spectra. The auto & came in with e842eca (2019). The loop over same-formula adducts was added later, in 5ad7df3 (2020), so in slow scoring it never scored more than the first adduct.
  • The adducts of a sum formula are collected first. A single loop over spectra then scores the total-loss part once: scorePeptideIons_, badTotalLossScore, ladder scores and mass error. Only scoreXLIons_ and what follows are computed per adduct × cross-linkable nucleotide, on copies of peak_matched and n_theoretical_peaks. scoreXLIons_ gets the total-loss b/y templates, which come from the same generateTheoreticalMZsZ1_ call as the partial-loss templates did.
  • nr_candidates is counted once per (peptide, sum formula, spectrum), with the same ID-filter condition as fast scoring, not once per adduct and nucleotide.

Fast scoring (rescoreFastHits_)

  • 3304: the loop that copies each hit per ambiguous adduct now advances NA_adduct_it, so each copy gets the cross-linkable nucleotides of its own adduct. Before, every copy used the first adduct's nucleotides. A U-H2O1 copy was labelled C, and C isn't feasible for U-H2O1.
  • 3353: each hit is rescored only with its own adduct, by direct lookup. Before, every hit was rescored once per adduct in its set. The last adduct's partial-loss and marker-ion scores overwrote the others, and total_MIC += was applied once per adduct.
  • The rescoring loop runs with #pragma omp parallel for, like the copy loop above it.

Not changed: fast scoring's main loop still scores total loss against the first adduct of the formula, as its comment intends. Rescoring then picks the adduct and nucleotide.

Hit selection

  • NuXLAnnotatedHit::hasBetterScore breaks score ties on sequence, peptide_mod_index, NA_mod_index, NA_adduct_amb_index, cross_linked_nucleotide and isotope_error. A tie between copies goes to the first adduct of the formula and the alphabetically first nucleotide, which is what develop reports.
  • keepTopUniqueHits_ keeps at most one hit per (peptide, peptide modification, sum formula, isotope error). It's used in the inline trim of the cross-link hits and in filterTopNAnnotations_, so it also covers the copies rescoreFastHits_ makes.

Precursor adduct lookup and localisation

  • NuXLModificationMassesResult::findPrecursorAdduct(NA_mod_index, NA_adduct_amb_index) returns a hit's sum formula and adduct, with bounds checks. rescoreFastHits_, fillSpectrumID_ and annotateAndLocate_ use it. If a lookup fails, the hit is skipped with a warning, because all three run inside OpenMP loops.
  • NuXLAnnotateAndLocate.cpp 365: annotateAndLocate_ takes the precursor adduct from the hit's NA_adduct_amb_index instead of the first adduct of the formula. Take a U-H2O1 hit cross-linked at U: its nucleotide was looked up among the nucleotides of C-H3N1, the find_if returned end(), and that was dereferenced. The iterator bug hid this, because no hit was ever on a second adduct. The nucleotide lookup and the all_feasible_adducts.at() calls are now explicit checks, and failures leave the hit unlocalised with a warning. NuXLAnnotateAndLocate.h documents this.

Test

  • TOPP_OpenNuXL_7 searches OpenNuXL_1_input with RNA-UV (UCGA), slow scoring and -report:top_hits 2. OpenNuXL_7_ambiguous_adducts_test.cmake checks:
    • a hit won by the second adduct of its formula (AEADNLDDK(NuXL:U-H2O1)K, NT U);
    • a hit won by the second nucleotide of AU (YTPY(NuXL:AU)LGR, NT U);
    • nr_candidates counted once per formula;
    • an exact C-H3N1/U-H2O1 tie that resolves to C-H3N1, without the other copy taking the second slot.

Effect on results

Hits on the second adduct of a formula, or on a later cross-linkable nucleotide, are now reported where they explain the spectrum best. Tied copies resolve to what develop reports, and nr_candidates is unchanged.

Some second adducts still never win: UU-H2O1, UUU-H2O1, CUU-H2O1, AUU-H2O1 and GUU-H2O1. Every nucleotide of each one also occurs in its partner (e.g. CU-H3N1 for UU-H2O1). The fragment adducts of an oligonucleotide precursor depend only on the cross-linked nucleotide, so those hits are reported under the partner with NuXL:NT = U. We read that as an ambiguity the data can't resolve, not as part of this bug.

Verification

We built OpenNuXL from v3.6.0 (5d5cbff) plus this PR. The build is standalone against the released libOpenMS 3.6.0 (bioconda), on macOS arm64, and we compared it with a build of unmodified v3.6.0. We didn't build develop. The code this PR edits is the same in v3.6.0 and on develop.

Measured on the first two commits (before the review changes). We'll update these after re-running. The later changes score the total loss once per spectrum, restore nr_candidates (a Percolator feature) and change tie-breaking and top-hit selection, so run time and identification counts will shift.

Both datasets use four target nucleotides, -NuXL:length 3, -NuXL:can_cross_link UCGA and precursor adducts including C:-NH3 and U:-H2O, with Percolator 3.09. Within a dataset, the unmodified and patched builds get identical arguments.

Full file, slow scoring. 210920_LU02_aleitner_NELF_02 (PRIDE PXD030569, NELF with UV 254 nm), fragment tolerance 20 ppm, 12 threads:

v3.6.0 v3.6.0 + first two commits
Wall time 24:23 min 40:19 min (1.65×)
Peak memory 2202 MB 2197 MB
Target PSMs at 1% FDR 1,419 1,434
Target cross-link PSMs at 1% cross-link FDR 412 424
C-H3N1 / U-H2O1 PSMs (100% FDR file) 307 / 0 221 / 113
CC-H3N1 / CU-H2O1 126 / 0 53 / 81
AC-H3N1 / AU-H2O1 43 / 0 57 / 64
CG-H3N1 / GU-H2O1 185 / 0 93 / 89
NuXL:NT = U on mixed-nucleotide adducts 0 of 4,530 2,709 of 5,603

Without the localisation change, the same run with only the loop change aborted with std::length_error during "localization of cross-links".

RT slice, slow and fast scoring. 210217_LU02_csarnowski_2102_2b (PRIDE PXD029930, PTBP1), FileFilter -rt 1304:1632, 3,252 spectra, fragment tolerance 0.2 Da with -filter filter_pc_mass_error idfilter (autotune off), 8 threads:

v3.6.0 v3.6.0 + first two commits
Slow: wall time 5:38 min 10:45 min (1.9×)
Slow: cross-link PSMs on the second adduct of a pair 0 of 700 94 of 732
Fast: completes yes yes
Fast: C-H3N1 / U-H2O1 (100% FDR file, 1,055 PSMs in both) 29 / 0 7 / 22
Fast: U-H2O1 PSMs with NuXL:NT = C 0 (no U-H2O1 PSMs at all) 0

With the loop changes but without the localisation change, fast scoring aborted on this slice in the same way.

Review changes. Scoring the total loss once per spectrum, the lookup helper and the parallel rescoring loop don't change any output: all TOPP test outputs and the UCGA run below are identical with and without them (FuzzyDiff). On the TOPP test input searched with RNA-UV (UCGA), top 2 hits:

v3.6.0 first two commits this PR
Spectra whose two reported hits are the same peptide (other adduct or nucleotide) 0 10 0
nr_candidates v3.6.0 values about 2× v3.6.0 values
Exactly tied C-H3N1/U-H2O1 pairs reported as C-H3N1 (U-H2O1 not scored) 5 of 6 6 of 6
AEADNLDDK… reported as C-H3N1 (63.13) U-H2O1 (65.48) U-H2O1 (65.48)

TOPP tests. We ran the TOPP_OpenNuXL_1–_7 commands and their checks by hand, because these tests are disabled on macOS, plus TOPP_OpenNuXL_adduct_in_sequence.

  • Tests 1, 2, 3, 5 and adduct_in_sequence give the same output as unmodified v3.6.0 and pass against the v3.6.0 references.
  • TOPP_OpenNuXL_7 passes. It fails on v3.6.0 and on the first two commits.
  • Tests 4 and 6 change because of the tie-breaker:
    • Test 4 (fast, top 2): a tie at fast score 4.95275 for the second slot now keeps IIGNENFVVAAR instead of LVQPFGWENPR, which rescores to 11.37 instead of 8.77.
    • Test 6 (-precursor:mass_tolerance 1e9): ties between adducts of different mass change the ppm-error mean and SD of the 20 best IDs. That moves the filter_pc_mass_error cutoff and drops the EDIAAIR peptide hit.
    • Their develop references need regenerating. We can't do that from a 3.6.0 build, because develop's references already differ from 3.6.0's.

Checklist

  • Make sure that you are listed in the AUTHORS file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
    Unit tests not run locally (no full OpenMS build). Of the files changed here, only NuXLModificationsGenerator.h is included by an OpenNuXL class test (NuXLModificationsGenerator_test, NuXLParameterParsing_test, NuXLReport_test). The addition is an inline member function those tests don't call, and the header compiles in our OpenNuXL build. Relying on CI.
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

No need to edit the CHANGELOG file: entries are generated automatically once per week from merged changes.

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.

⚠️ 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

  • Bug Fixes
    • Improved handling of results with multiple possible precursor adducts. Scoring and annotations now use the adduct associated with each result, helping keep candidate matches and displayed annotations consistent.
    • Results with unresolved adducts or cross-linked nucleotides now produce a warning and retain unmodified annotations rather than proceeding with incomplete information.
    • Top-scoring results are deduplicated, and equally scoring candidates are selected consistently.

…cleotide in slow scoring

The spectrum loops in the main scoring loop iterate over a copy of
low_it (`auto l`), so every adduct sharing a precursor sum formula and
every cross-linkable nucleotide is scored against the matching spectra.

annotateAndLocate_ localises each hit against its own precursor adduct
(NA_adduct_amb_index), as fillSpectrumID_ does, so the nucleotide
lookup finds the hit's nucleotide for second and later adducts of a
sum formula.

See OpenMS#10739.
…duct

In rescoreFastHits_, the loop that copies each hit per ambiguous
precursor adduct advances NA_adduct_it with NA_adduct_amb_index, so
each copy takes its cross-linkable nucleotides from its own adduct.

The rescoring loop skips adducts other than the hit's
NA_adduct_amb_index, so partial-loss and marker-ion scores come from
the hit's adduct and total_MIC is incremented once per hit.

See OpenMS#10739.
@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d1d54962-27f2-4d06-b264-fa75cefddad3
Commits

Reviewing files that changed from the base of the PR and between df43494 and 1a3dc25.

Files selected for processing: 7
  • src/tests/topp/CMakeLists.txt
  • src/tests/topp/OpenNuXL_7_ambiguous_adducts_test.cmake
  • src/topp/OpenNuXL/OpenNuXL.cpp
  • src/topp/OpenNuXL/include/NuXLAnnotateAndLocate.h
  • src/topp/OpenNuXL/include/NuXLAnnotatedHit.h
  • src/topp/OpenNuXL/include/NuXLModificationsGenerator.h
  • src/topp/OpenNuXL/source/NuXLAnnotateAndLocate.cpp

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

Walkthrough

OpenNuXL now resolves precursor adducts using both stored indices. Slow scoring processes ambiguous adducts and cross-linkable nucleotides, reuses per-spectrum total-loss scores, and counts candidates once per spectrum and formula. Hit selection removes duplicates, and a new TOPP test checks ambiguous-adduct results.

Changes: OpenNuXL adduct-aware scoring

Layer / File(s) Summary
Resolve precursor adducts for reporting and localization
src/topp/OpenNuXL/include/NuXLModificationsGenerator.h, src/topp/OpenNuXL/OpenNuXL.cpp, src/topp/OpenNuXL/source/NuXLAnnotateAndLocate.cpp, src/topp/OpenNuXL/include/NuXLAnnotateAndLocate.h
findPrecursorAdduct resolves formula and nucleotide-composition data using both indices. Rescoring, hit reporting, and localization use this lookup. Invalid lookups produce warnings; localization preserves unshifted annotations when feasible adducts or the cross-linked nucleotide cannot be resolved.
Score ambiguous candidates and retain unique hits
src/topp/OpenNuXL/OpenNuXL.cpp, src/topp/OpenNuXL/include/NuXLAnnotatedHit.h
Slow scoring collects adduct-specific data and reuses total-loss scores across candidates. Candidate counts are incremented once per spectrum and formula. Top-hit selection removes duplicates, and equal-score hits use a field-based tie-break. Rescoring over spectra is now OpenMP-parallel when enabled.
Verify ambiguous-adduct results
src/tests/topp/CMakeLists.txt, src/tests/topp/OpenNuXL_7_ambiguous_adducts_test.cmake
A non-macOS TOPP test runs slow scoring with a two-hit limit. The idXML check verifies adduct and nucleotide selections, candidate count, and the absence of an alternate equal-scoring hit.

Sequence Diagram(s)

sequenceDiagram
  participant OpenNuXL
  participant PrecursorAdductLookup
  participant SlowScoring
  participant HitSelection
  OpenNuXL->>PrecursorAdductLookup: Resolve adduct by formula and ambiguity indices
  OpenNuXL->>SlowScoring: Score matching spectra and collected adduct candidates
  SlowScoring->>HitSelection: Submit scored hits
  HitSelection->>OpenNuXL: Return unique top hits
Loading

Suggested reviewers: timosachsenberg

Priority: Normal

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Moderate · up to 1a3dc

The tie-break change alters which adduct is reported when scores tie. Per the author, this changes the outputs of two existing OpenNuXL regression tests, and their reference files were not updated in this PR. Regenerate and commit those reference files, or confirm that the differences fall within the comparison tolerance, before merging so CI stays green.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 38.46% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surv… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: slow scoring now covers every same-formula adduct and every cross-linkable nucleotide, which matches the linked issue #10739 and the stated objectives. It is short, sp…
Linked Issues check Passed Issue #10739 requires three fixes. Each fix is present in the whole-PR diff (mergeBase 31e6d9d to head 1a3dc25).

(a) Slow scoring scores every same-formula adduct. The three candidate loops ("none"…
Out of Scope Changes check Passed Each changed area relates to #10739 or to a side effect that the fix creates:

- findPrecursorAdduct in NuXLModificationsGenerator.h: bounds-checked lookup used by fast rescoring, `fillSpectrumID_…
Full details: Title check

Explanation

The title names the main change: slow scoring now covers every same-formula adduct and every cross-linkable nucleotide, which matches the linked issue #10739 and the stated objectives. It is short, specific, and uses the [FIX] convention. The rest of the changeset (fast rescoring, deduplication, bounds-checked lookups, localization checks, and the new TOPP_OpenNuXL_7 test) is supporting detail that the title does not need to list.

Full details: Linked Issues check

Explanation

Issue #10739 requires three fixes. Each fix is present in the whole-PR diff (mergeBase 31e6d9d to head 1a3dc25).

(a) Slow scoring scores every same-formula adduct. The three candidate loops ("none" branch, xl branch, and fast-scoring loop) now use for (auto l = low_it; ...) instead of auto & l. The adducts of a formula are collected in xl_adducts, and one loop then scores them. The adduct loop no longer consumes low_it.

(b) Slow scoring scores every cross-linkable nucleotide. The per-adduct partial-loss scoring runs for each collected adduct and each cross-linkable nucleotide, and the total-loss part runs once per spectrum. The remainder of the slow-scoring diff was truncated in the tool output. This verdict relies on the PR summary for that block.

(c) Fast scoring. rescoreFastHits_ now increments NA_adduct_it in the copy loop (line 3304 on develop). Each copy gets the cross-linkable nucleotides of its own adduct. The rescoring loop selects the precursor adduct by findPrecursorAdduct(ah.NA_mod_index, ah.NA_adduct_amb_index). It no longer rescores each hit once per adduct.

(d) Localization no longer aborts. annotateAndLocate_ takes the precursor adduct from the hit indices. The nucleotide find_if result and the all_feasible_adducts lookup are checked. Failures warn and leave the hit unlocalised, which removes the end() dereference.

Issue-related side effects are handled. nr_candidates counts once per (peptide, sum formula, spectrum). keepTopUniqueHits_ and the hasBetterScore tie-breaks keep copies from occupying several top-hit slots.

Open points, not requirements of #10739: TOPP tests 4 and 6 change, and their develop references are not regenerated in this PR. The issue's proposed follow-up names TOPP test reference changes as part of the fix. The unresolved UU/UUU/CUU/AUU/GUU -H2O cases are described in the issue as an ambiguity, not as part of the bug.

Full details: Out of Scope Changes check

Explanation

Each changed area relates to #10739 or to a side effect that the fix creates:

  • findPrecursorAdduct in NuXLModificationsGenerator.h: bounds-checked lookup used by fast rescoring, fillSpectrumID_ and annotateAndLocate_. It implements the localization fix and the adduct-index lookups.
  • NuXLAnnotateAndLocate.cpp and .h: explicit checks for the adduct lookup and nucleotide lookup, with warnings. These implement the abort fix in issue #10739.
  • keepTopUniqueHits_ and filterTopNAnnotations_: the copies created by scoring all adducts and nucleotides would otherwise use several report:top_hits slots.
  • NuXLAnnotatedHit::hasBetterScore: tie-breaking so copies resolve the same way on every run.
  • nr_candidates counted once per spectrum: keeps the Percolator denominator at the develop value.
  • #pragma omp parallel for in the fast rescoring loop: a performance change in the loop that this PR rewrites. The PR says it follows the copy loop above it. It is not a functional requirement of #10739, so it is noted as a minor extra. Its scan_index writes stay per spectrum, so no shared state is written in the loop body.
  • TOPP_OpenNuXL_7, OpenNuXL_7_ambiguous_adducts_test.cmake, and CMakeLists.txt: tests for the second-adduct, second-nucleotide, candidate-count and tie cases.
  • NuXLAnnotatedHit.h <tuple> include and NuXLModificationsGenerator.h <iterator> include: support the changes above.

No change is unrelated to #10739, the autotune issue #10725 or the listed fixes.

Full details: Docstring Coverage

Explanation

Docstring coverage is 38.46% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 13 functions across 5 files. (2 skipped: 2 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

A rabbit checks each adduct in the row,
Then watches candidate counts grow.
Shared scores cross the spectrum,
Unique hits take their place;
The test confirms the chosen base,
And hops away with a pleased face.

Comment @coderabbitai help to get the list of available commands.

@timosachsenberg timosachsenberg 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.

Scoring every same-formula adduct and rescoring fast hits with their own adduct fixes real bugs. The inline comments below are roughly ordered by severity. They cover:

  • side effects of now scoring every adduct × nucleotide: ties between copies decide the reported adduct nondeterministically, nr_candidates is inflated, near-duplicates crowd out top_hits, and total-loss work is repeated
  • one new unchecked index
  • some cleanups

Comments marked pre-existing are about the fast-scoring path this PR touches but are not caused by it. They could go in a follow-up.

Test coverage: no regression test covers either fix. The OpenNuXL TOPP tests (src/tests/topp/CMakeLists.txt, OpenNuXL_1..6) only cross-link and modify U. So no sum formula maps to two cross-linkable adducts, and no adduct has more than one cross-linkable nucleotide. On those tests, the old auto & l = low_it bug and the first-adduct copy bug give the same output as the fixed code, so either bug could come back unnoticed. A small run with the RNA-UV (UCGA) preset would cover both, since C-NH3 and U-H2O share a sum formula there.


Generated by Claude Code

Comment thread src/topp/OpenNuXL/OpenNuXL.cpp Resolved
Comment thread src/topp/OpenNuXL/OpenNuXL.cpp Outdated
}

for (auto & l = low_it; l != up_it; ++l)
for (auto l = low_it; l != up_it; ++l)

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.

nr_candidates is now counted once per adduct × cross-linkable nucleotide. This loop no longer consumes low_it, so ++nr_candidates[scan_index] (L5763) fires once per (adduct, nucleotide) instead of once per (peptide, formula, spectrum).

With UCGA/TCGAd, a dinucleotide adduct such as CU counts 2 per spectrum, and so does an ambiguous set like {C-NH3, U-H2O}. The none formula and fast scoring still count 1. nr_candidates is exported as a Percolator feature and is the denominator of λ in -ln(poisson). Its scale now depends on the adduct composition and differs between fast and slow mode.

Suggestion: count once per (peptide, formula, spectrum), outside the adduct/nucleotide loops.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed: slow scoring counts once per (peptide, sum formula, spectrum) in a loop before the adduct loop, with the same ID-filter condition as fast scoring. The values match develop again, and TOPP_OpenNuXL_7 checks one. Change: candidate count.

Comment thread src/topp/OpenNuXL/OpenNuXL.cpp Resolved
Comment thread src/topp/OpenNuXL/OpenNuXL.cpp Resolved
Comment thread src/topp/OpenNuXL/OpenNuXL.cpp Resolved
Comment thread src/topp/OpenNuXL/OpenNuXL.cpp Outdated
auto NA_adduct_it = mod_combinations_it->second.begin();
for (size_t NA_adduct_amb_index = 0; NA_adduct_amb_index != NA_adducts.size(); ++NA_adduct_amb_index, ++NA_adduct_it)
{ // for all NA adducts with current sum formula (e.g, U-H2O and C-NH3)
if (NA_adduct_amb_index != ah.NA_adduct_amb_index) continue; // only rescore with the precursor adduct of this hit

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.

Pre-existing, not caused by this PR: further down this loop, ah.pl_err = plss_err; (L3456) is set, but plss_err is never passed to postScorePartialLossFragments_ (the argument is commented out at L3449). So every rescored fast hit reports NuXL:pl_err equal to fragment_mass_tolerance. That Percolator feature is constant in fast mode and has a different distribution than in slow mode.

The same loop also never fills pl_pc_MIC, pl_im_MIC or the tag_* fields.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed. Like the matched_peaks comment, it changes fast-mode Percolator features, so we'd suggest the same separate PR. See the top-level reply for a related marker-ion question.

Comment thread src/topp/OpenNuXL/OpenNuXL.cpp Resolved
std::advance(mod_combinations_it, a.NA_mod_index);
const std::string precursor_na_adduct = *mod_combinations_it->second.begin(); // TODO: check if it is enough to consider only first precursor adduct ????????????????????????????????????????????????????????
auto NA_adduct_it = mod_combinations_it->second.cbegin();
std::advance(NA_adduct_it, a.NA_adduct_amb_index);

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.

std::advance by a.NA_adduct_amb_index has no bounds check. Before, begin() was valid for any non-empty set. Now two kinds of inconsistent hit dereference an end() iterator in release builds:

  • NA_adduct_amb_index ≥ the size of the set
  • cross_linked_nucleotide is not in that adduct's feasible list

The lookup at L433/437 is guarded only by OPENMS_POSTCONDITION, which compiles out in release. In debug builds it throws inside the OpenMP region, which calls std::terminate.

Suggestion: check explicitly and give a clear error, or skip the hit with a warning.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. The adduct lookup goes through findPrecursorAdduct, which checks both indices. all_feasible_adducts.at() became a find with a check, and the OPENMS_POSTCONDITION on the nucleotide lookup became an explicit check. Each failure logs a warning and leaves the hit unlocalised, which is the fallback the header documents. Change: adduct lookup, feasible adducts, nucleotide.

auto mod_combinations_it = mm.mod_combinations.cbegin();
std::advance(mod_combinations_it, a.NA_mod_index);
const std::string precursor_na_adduct = *mod_combinations_it->second.begin(); // TODO: check if it is enough to consider only first precursor adduct ????????????????????????????????????????????????????????
auto NA_adduct_it = mod_combinations_it->second.cbegin();

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.

Note on history: commit 1640994 on its own is broken. This line already uses the hit's own adduct there, but rescoreFastHits_ keeps giving copies of later adducts the first adduct's nucleotides until df43494.

Example: fast scoring with UCGA at 1640994 gives the U-H2O copy nucleotide C (from C-NH3). C is not in U-H2O's feasible list, so the lookup dereferences end(). This only matters if the PR is not squash-merged.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, we're happy for the PR to be squash-merged.

const std::string precursor_na_adduct = *mod_combinations_it->second.begin(); // TODO: check if it is enough to consider only first precursor adduct ????????????????????????????????????????????????????????
auto NA_adduct_it = mod_combinations_it->second.cbegin();
std::advance(NA_adduct_it, a.NA_adduct_amb_index);
const std::string precursor_na_adduct = *NA_adduct_it; // precursor adduct of this hit (e.g., U-H2O or C-NH3 for the same sum formula)

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.

The documentation for annotateAndLocate_ in include/NuXLAnnotateAndLocate.h is now out of date:

  • L54 still says the precursor adduct is the "first entry of the composition set".
  • L79 still says hits "whose first precursor adduct" cannot be resolved fall back.

Neither is true now that the code uses NA_adduct_amb_index. L78 also says no exceptions are thrown, but all_feasible_adducts.at() can throw. Worth updating along with this change.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated: the header now describes the lookup through NA_mod_index and NA_adduct_amb_index, and the warning-and-fallback behaviour for hits whose adduct or nucleotide can't be resolved. Since .at() became an explicit check, the "no exceptions are thrown" sentence holds for these lookups. Change: lookup, fallback.

…re total loss once

- NuXLAnnotatedHit::hasBetterScore: deterministic tie-breaker on
  sequence, peptide modification, NA modification, adduct index,
  cross-linked nucleotide and isotope error
- slow scoring: nr_candidates counted once per peptide, sum formula
  and spectrum; adducts of a sum formula collected first, total-loss
  part scored once per spectrum, partial-loss part per adduct and
  nucleotide with the total-loss b/y templates
- keepTopUniqueHits_: at most one hit per peptide, peptide
  modification, sum formula and isotope error, in the inline XL trim
  and filterTopNAnnotations_
- rescoreFastHits_: direct adduct lookup, parallel rescoring loop
- NuXLModificationMassesResult::findPrecursorAdduct: bounds-checked
  lookup of a hit's sum formula and adduct, used in rescoreFastHits_,
  fillSpectrumID_ and annotateAndLocate_
- annotateAndLocate_: explicit checks for unresolvable adducts and
  nucleotides (warning, hit left unlocalised); header docs updated
- TOPP_OpenNuXL_7: RNA-UV (UCGA) search checking second adducts,
  second nucleotides, nr_candidates and tie resolution
@TomSmithCGAT

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review. The new commit addresses every comment caused by this PR. We'd like to deal with the pre-existing issues separately (details below).

Side effects of scoring every adduct × nucleotide

  • Ties: NuXLAnnotatedHit::hasBetterScore now breaks score ties on sequence, peptide_mod_index, NA_mod_index, NA_adduct_amb_index, cross_linked_nucleotide and isotope_error. A tie between adduct or nucleotide copies goes to the first adduct of the sum formula and the alphabetically first nucleotide, which is what develop reports.
  • nr_candidates: slow scoring counts each spectrum once per peptide and sum formula, as fast scoring does. The values are back to what develop gives. The PR description said the fix doubles nr_candidates and shifts the Percolator input of every hit. That was true of the first two commits and is no longer true, so we've corrected the description.
  • report:top_hits: a new keepTopUniqueHits_ keeps at most one hit per (peptide, peptide modification, sum formula, isotope error). It's used in the inline trim of annotated_XLs and in filterTopNAnnotations_, so it also covers the copies rescoreFastHits_ makes.
  • Repeated total-loss work: slow scoring now collects the adducts of a sum formula first. It then scores the total-loss part (scorePeptideIons_, badTotalLossScore, ladder scores, mass error) once per spectrum, and only scoreXLIons_ and what follows per adduct × nucleotide, on copies of peak_matched and n_theoretical_peaks. scoreXLIons_ now gets the total-loss templates, as you suggested, since the partial-loss ones came from the identical call. We also dropped two pieces of dead code from that block: the commented-out hyperscore test and a DEBUG_OpenNuXL line that referenced an undefined score.

Robustness and cleanups

  • New helper NuXLModificationMassesResult::findPrecursorAdduct(NA_mod_index, NA_adduct_amb_index). It checks both indices and returns the sum formula and the adduct. rescoreFastHits_, fillSpectrumID_ and annotateAndLocate_ use it. If a lookup fails, the hit is skipped with a warning, since all three run in OpenMP loops. The cross-linked nucleotide lookup and all_feasible_adducts.at() in annotateAndLocate_ are now explicit checks too. The other places that walk mod_combinations go through every adduct on purpose, and fast scoring's main loop still takes the first adduct on purpose.
  • rescoreFastHits_: direct lookup instead of the loop with continue, and #pragma omp parallel for over the rescoring loop.
  • NuXLAnnotateAndLocate.h documentation updated.

Test: new TOPP_OpenNuXL_7 runs OpenNuXL_1_input with RNA-UV (UCGA), slow scoring and -report:top_hits 2. OpenNuXL_7_ambiguous_adducts_test.cmake checks four things:

  • the second adduct of a sum formula wins where it should (AEADNLDDK(NuXL:U-H2O1)K, NT U);
  • the second nucleotide of a dinucleotide adduct wins where it should (YTPY(NuXL:AU)LGR, NT U);
  • nr_candidates is counted once per formula;
  • an exact C-H3N1/U-H2O1 tie on DDMNMQK…DAIFGGK resolves to C-H3N1, without the equally scoring copy taking the second slot.

On our build, the test fails on v3.6.0 and on the first two commits of this PR, and passes with this commit.

Question: references for TOPP_OpenNuXL_4 and _6. The tie-breaker changes the output of these two tests. Tests 1, 2, 3, 5 and adduct_in_sequence don't change.

  • Test 4 (fast, top 2): two peptides tie at fast score 4.95275 for the second slot before rescoring. The tie-breaker keeps IIGNENFVVAAR instead of LVQPFGWENPR. After rescoring it scores 11.37 rather than 8.77.
  • Test 6 (slow, -precursor:mass_tolerance 1e9): many hits tie between adducts of different mass (e.g. UU-H2O1 and UU-H3O4P1). Which one ranks first changes the mean and SD of the precursor ppm error over the 20 best IDs. That moves the 5·SD cutoff of filter_pc_mass_error, and the EDIAAIR peptide hit falls outside it.

We build OpenNuXL on its own against the released libOpenMS 3.6.0. develop's reference files already differ from 3.6.0's, so we can't produce correct develop references for these two tests. How would you like them created? From the CI output, or would you prefer to regenerate them?

Pre-existing issues (matched_peaks and pl_err in fast mode, missing pl_pc_MIC/pl_im_MIC/tag_*): we agree these are real. Fixing them changes fast-mode Percolator features, so we'd suggest separate PRs rather than widening this one. One related point came up while restructuring. scoreXLIons_ ignores its marker_ions_sub_score_spectrum_z1 argument ((void)) and scores marker ions against all_possible_marker_ion_sub_score_spectrum_z1, the union over all precursor adducts. Two consequences:

  • In slow scoring, all adduct copies of a hit get the same marker_ions_score, so it can't help separate them.
  • Fast-mode rescoring (postScorePartialLossFragments_) does use the per-adduct marker ions, so NuXL:marker_ions_score is computed differently in the two modes.

Is the union intended? If not, it could go into the same follow-up. We left it unchanged here because either choice changes scores.

History: we're happy for this to be squash-merged, which avoids the broken intermediate commit 1640994.

Numbers in the description: the run-time and identification numbers were measured on the first two commits. Scoring the total loss once per spectrum should cut the slow-scoring run time, and nr_candidates feeds Percolator. We'll re-run NELF_02 and update the description.

Verification for this commit was done the same way as before (standalone build against libOpenMS 3.6.0, macOS arm64). The changes for total-loss reuse, the lookup helper and the parallel rescoring leave every TOPP test output and the UCGA run identical (FuzzyDiff).

Copy link
Copy Markdown
Contributor

@TomSmithCGAT the remaining CI failures here (TOPP_OpenNuXL_4_out1/out2 and TOPP_OpenNuXL_6_out1/out2, identical on all three Linux jobs) are the reference changes you predicted. I regenerated them on Linux and checked every changed line. Each one is an exact score tie that the new tie-breaker resolves differently:

  • Test 4: at RT 31.812, IIGNENFVVAAR and LVQPFGWENPR tie at fast score 4.95275402 for the second slot.
  • Test 6: 10 ties between adducts or modifications of the same peptide resolve differently (mostly UU-H2O1 vs UU-H3O4P1). The changed rank-1 precursor errors move the filter_pc_mass_error cutoff (5×SD 786,491 → 731,308 ppm), which removes EDIAAIR (|ppm|−|mean| = 776,317).

On develop the same build passes all existing OpenNuXL tests against the old references, and on your branch plus the update all 34 TOPP_OpenNuXL tests pass. Only the lines that actually change were replaced, so the diff stays small.

The update is a single commit on top of your branch head (1a3dc25): a135b0cb. It's in #10761, which carries your three commits unchanged plus that commit. You can pick it into this PR:

git fetch https://github.com/OpenMS/OpenMS claude/openms-pr-10746-failures-1922dv
git cherry-pick a135b0cb

Or we can continue in #10761. Either is fine; details are in the #10761 description.


Generated by Claude Code

@TomSmithCGAT

Copy link
Copy Markdown
Contributor Author

Thanks @timosachsenberg. Let's close this and continue on #10761 then.

timosachsenberg added a commit that referenced this pull request Oct 28, 2026
…cleotide (#10746 + updated test references) (#10761)

* [FIX] OpenNuXL: score every same-formula adduct and cross-linkable nucleotide in slow scoring

The spectrum loops in the main scoring loop iterate over a copy of
low_it (`auto l`), so every adduct sharing a precursor sum formula and
every cross-linkable nucleotide is scored against the matching spectra.

annotateAndLocate_ localises each hit against its own precursor adduct
(NA_adduct_amb_index), as fillSpectrumID_ does, so the nucleotide
lookup finds the hit's nucleotide for second and later adducts of a
sum formula.

See #10739.

* [FIX] OpenNuXL: rescore fast-scoring hits with their own precursor adduct

In rescoreFastHits_, the loop that copies each hit per ambiguous
precursor adduct advances NA_adduct_it with NA_adduct_amb_index, so
each copy takes its cross-linkable nucleotides from its own adduct.

The rescoring loop skips adducts other than the hit's
NA_adduct_amb_index, so partial-loss and marker-ion scores come from
the hit's adduct and total_MIC is incremented once per hit.

See #10739.

* [FIX] OpenNuXL: deduplicate adduct copies, count candidates once, score total loss once

- NuXLAnnotatedHit::hasBetterScore: deterministic tie-breaker on
  sequence, peptide modification, NA modification, adduct index,
  cross-linked nucleotide and isotope error
- slow scoring: nr_candidates counted once per peptide, sum formula
  and spectrum; adducts of a sum formula collected first, total-loss
  part scored once per spectrum, partial-loss part per adduct and
  nucleotide with the total-loss b/y templates
- keepTopUniqueHits_: at most one hit per peptide, peptide
  modification, sum formula and isotope error, in the inline XL trim
  and filterTopNAnnotations_
- rescoreFastHits_: direct adduct lookup, parallel rescoring loop
- NuXLModificationMassesResult::findPrecursorAdduct: bounds-checked
  lookup of a hit's sum formula and adduct, used in rescoreFastHits_,
  fillSpectrumID_ and annotateAndLocate_
- annotateAndLocate_: explicit checks for unresolvable adducts and
  nucleotides (warning, hit left unlocalised); header docs updated
- TOPP_OpenNuXL_7: RNA-UV (UCGA) search checking second adducts,
  second nucleotides, nr_candidates and tie resolution

* [TEST] OpenNuXL: update TOPP_OpenNuXL_4/_6 references for deterministic tie-breaking

NuXLAnnotatedHit::hasBetterScore now breaks score ties on sequence,
peptide_mod_index, NA_mod_index, ... instead of leaving them to
std::partial_sort's unspecified order. Every changed hit is an exact score
tie that now resolves the other way:

- OpenNuXL_4 (fast scoring, top 2): at RT 31.812 IIGNENFVVAAR (CU-H2O1) and
  LVQPFGWENPR (GU-H3O4P1) tie at fast score 4.95275402 for the second slot;
  IIGNENFVVAAR is now kept (rescored to 11.37 instead of 8.77).
- OpenNuXL_6 (precursor tolerance 1e9 ppm, top 2): rank 1/2 ties between
  UU-H2O1 and UU-H3O4P1 (and U-H2O1/U-H1O3P1, MATSGMMTELGK with/without
  Met oxidation) now go to the lower sum-formula/modification index. The
  changed rank-1 hits shift the precursor-error mean/SD of the 20 best IDs
  (mean 34789 -> 43371 ppm, 5*sd 786491 -> 731308 ppm), so the
  filter_pc_mass_error cutoff now removes the EDIAAIR peptide hit
  (|ppm| - |mean| = 776317 ppm).

Only the lines that differ between develop and this branch's output were
replaced; all other lines are unchanged. Generated on Linux x64, g++ 13.3,
Release. All 34 TOPP_OpenNuXL tests pass; on develop, the same build passes
all OpenNuXL tests except the new TOPP_OpenNuXL_7_ambiguous_adducts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0149aXmZp4ZWSMDF4PaXvwak

---------

Co-authored-by: tomsmithCGAT <[email protected]>
Co-authored-by: Claude <[email protected]>

Copy link
Copy Markdown
Contributor

@TomSmithCGAT this PR's changes are now on develop via #10761, which was merged with your three commits unchanged plus the updated TOPP_OpenNuXL_4/_6 references. Nothing from here is left to merge, so this PR can be closed. Thanks for the thorough fix and write-up!


Generated by Claude Code

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.

OpenNuXL: slow scoring only scores the first adduct and first cross-linkable nucleotide for each precursor sum formula

2 participants