Skip to content

[FIX,TOPP,ID] ProteomicsLFQ, IsobaricWorkflow: reduce identifications to one per spectrum (#9871) - #9892

Merged
timosachsenberg merged 3 commits into
developfrom
lfq-iso-reduce-per-spectrum
Aug 9, 2026
Merged

timosachsenberg merged 3 commits into
developfrom
lfq-iso-reduce-per-spectrum

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

ProteomicsLFQ and IsobaricWorkflow measure one value per (spectrum, peptidoform, charge). Input carrying several identifications of that same triple leaves it undecided which one owns the measurement, and both tools silently took all of them. This reduces to the best-scoring one at load, in both tools, and documents the precondition.

The shape, and why this reduces rather than refuses

Two OpenMS tools produce it deliberately, so refusing would refuse the library's own output:

  • PSMFeatureExtractor -multiple_search_engines -concat — documented as "Naive merging of PSMs from different search engines: concatenate multiple search results instead of merging on scan level" (PSMFeatureExtractor.cpp:94), assigning every engine's identifications one run identifier (:257-260). The repo already ships a fixture of it: combined.concat.perco.in.idXML:137,594 — same scan=334, same sequence HYSEEEYDSEFDDADDDEEQ, same charge.
  • PercolatorAdapter at its default -score:fdr 1.0 — :1449-1470, verbatim: "If the input contains multiple PSMs per spectrum, Percolator only reports the top scoring PSM. The remaining PSMs should be reported as not identified" (PEP and q-value set to 1.0).

Both are resolved but not reduced: something upstream already ranked them, it just did not delete the losers. Picking the better of two scores on one scale is a tie-break, not a scoring decision — combining scores from different engines stays ConsensusIDAlgorithm's job and is deliberately not done here.

The one genuinely unresolvable case needs no new code: ProteomicsLFQ::switchScoreType_ (:764-779) already refuses input lacking a PEP score everywhere, so an un-rescored -concat file (MS-GF:RawScore higher-better vs expect lower-better) is rejected today, for the right reason. What reaches the reduction is always one comparable scale.

Measured effect of a single duplicated identification

IsobaricWorkflow — 7 consensus features instead of 6, the extra one bit-identical. It builds one consensus feature per identification (:631) and all identifications of one spectrum read the same MS2/MS3 scan, so the same reporter intensities enter quantification twice:

unreduced reduced
consensus features 7 6
PSM rows / PEP rows 5 / 5 4 / 4
PEP abundances unchanged unchanged
PRT abundance (PROTA, ch1) 2.176e04 1.584e04 (+37%)
PSM q-value column 0.1667 0.2

Worth noting the damage is not a doubled peptide abundance — the peptide row duplicates with identical values, and the inflation lands at protein level. Not a clean 2× either, since a protein aggregates several peptides and only one is duplicated.

ProteomicsLFQ — 116 mzTab PSM rows against 115, plus a consensusXML difference. MSstats and Triqler output is unaffected; the damage from a duplicate is not uniform across exporters.

Placement

In ProteomicsLFQ the reduction runs after the missing-spectrum-reference repair (SpectrumMetaDataLookup::addMissingSpectrumReferences). An identification with no reference cannot be keyed at all, so reducing earlier would silently skip exactly the files whose references had to be reannotated. The fixture demonstrates this rather than asserting it: BSA1_F1.idXML carries no spectrum references at all, so at the earlier position the test would pass green while doing nothing.

Implementation notes

  • Identifications are keyed on the top hit as stored — hits are never re-sorted, so the key matches what the exporters and quantifiers read (QPXFile writes hits[0] unsorted, as does ConsensusMapArrowExport::topHitPsmIdentity).
  • Group membership uses the ordering the range was sorted with, not operator==. AASequence's two operators disagree on what identifies a residue — operator< compares the one-letter code (AASequence.cpp:354-363), operator== the interned Residue* (:873-884) — so a pair operator< calls equivalent could otherwise be split apart and its duplicate silently missed.
  • A group disagreeing on isHigherScoreBetter() has no defined "best" and is left intact rather than reduced by a coin flip.
  • Ties break on input position, so the survivor is deterministic; survivors keep their original relative order.
  • Identifications without a spectrum reference, and those without hits, are left untouched.
  • Chimeric spectra are unaffected: two identifications of one spectrum naming different peptidoforms are two distinct measurements and both survive.

Testing

Both TOPP tests diff against the existing un-duplicated reference files rather than new ones — "the duplicate changed no number" is exactly the assertion — so there is zero reference-file churn. Each also requires the reduction to report, since an identical output could otherwise mean it never ran.

  • IDConflictResolverAlgorithm_test: 8 cases, including both score directions, chimeric, missing reference, hitless, ordering, and empty input.
  • TOPP_ProteomicsLFQ_duplicate_psm (+4 diffs), TOPP_IsobaricWorkflow_duplicate_psm (+1 diff).
  • 95/95 TOPP_ProteomicsLFQ + TOPP_IsobaricWorkflow pass.
  • Each check was verified able to fail: reverting each reduction in turn turns the relevant tests red for the right reason, and inverting the score direction in the primitive turns its direction test red.
  • doc target rebuilt; the Doxygen log contains only the two pre-existing HAVE_DOT warnings.

Relation to #9871

#9871 reported this as "one PSM row per search engine" from a quantms run. That diagnosis does not hold — the reported parquet predates #9818 and its collisions are the pre-#9818 run_file_name collapse (analysis). But the underlying shape is real and OpenMS mishandled it, which is what this fixes. The issue's actual request — one PSM carrying per-engine scores — is not implementable in the exporter, since no per-hit engine label survives Percolator or ConsensusID; it belongs at ConsensusIDAlgorithm.cpp:107 (//TODO add SE name) and is left for a follow-up.

Not in scope, each worth its own issue: the qpxScanComponents vendor truncation (every Sciex MS2 collapses onto its experiment index; merged PASEF takes the wrong token), and moving duplicate-primary-key detection into QPXCollectionExport::requireExportable.

🤖 Generated with Claude Code

https://claude.ai/code/session_01S7QNzj4dhRnX5htcHZFmDm

Summary by CodeRabbit

  • New Features

    • Improved peptide identification handling by retaining the best-scoring match for duplicate spectrum, peptidoform, and charge combinations.
    • Preserved distinct peptidoforms from chimeric spectra as separate identifications.
    • Added diagnostics for unresolved duplicates, missing spectrum references, and conflicting score directions.
    • Added filename utilities for extracting names and validating file-list matches.
  • Documentation

    • Clarified input requirements and recommendations for combining search results in IsobaricWorkflow and ProteomicsLFQ.
  • Tests

    • Added regression coverage for duplicate peptide-spectrum matches, filename handling, and identification edge cases.

timosachsenberg and others added 2 commits August 8, 2026 19:22
… to one per spectrum

Adds IDConflictResolverAlgorithm::reduceToOnePerSpectrum(), which keeps the best-scoring
identification of each (spectrum_reference, top-hit peptidoform, top-hit charge) group and
removes the rest, reporting what it did.

Quantification tools measure one value per such triple. Input carrying several identifications
of one triple - two search engines concatenated rather than combined - leaves it undecided which
owns the measurement, and keeping all of them counts one measurement several times. Picking the
better of two scores that something upstream already assigned is a tie-break, not a scoring
decision; combining scores from different engines remains ConsensusIDAlgorithm's job and is
deliberately not done here.

Details that matter:

- Identifications are keyed on the top hit AS STORED. Hits are never re-sorted, so the key
  matches what the exporters and quantifiers read (QPXFile writes hits[0] unsorted, as does
  ConsensusMapArrowExport::topHitPsmIdentity).
- Group membership uses the ordering the range was sorted with, not operator==. AASequence's
  two operators disagree on what identifies a residue - operator< compares the one-letter code,
  operator== the interned Residue* - so a pair operator< calls equivalent could otherwise be
  split apart and its duplicate silently missed.
- A group whose members disagree on isHigherScoreBetter() has no defined "best" and is left
  intact rather than reduced by a coin flip.
- Ties break on input position, so the survivor is deterministic; survivors keep their original
  relative order.
- Identifications without a spectrum reference, and those without hits, are left untouched.

No caller yet, so no behaviour changes with this commit.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01S7QNzj4dhRnX5htcHZFmDm
…er spectrum (#9871)

Both tools now reduce their input to one identification per (spectrum, peptidoform, charge)
at load, and document the precondition on -ids / -in_id and in their tool docs.

The shape being handled is a search-engine merge that concatenates rather than combines.
OpenMS produces it in two places: PSMFeatureExtractor -multiple_search_engines -concat, whose
documented purpose is "naive merging ... instead of merging on scan level" and which assigns
every engine's identifications one run identifier; and PercolatorAdapter at its default
-score:fdr 1.0, which retains the PSMs target-decoy competition rejected, marked as not
identified. Both are resolved but not reduced - something upstream ranked them, it just did not
delete the losers - which is why this reduces rather than refuses.

Measured effect of a single duplicated identification:

- IsobaricWorkflow: 7 consensus features instead of 6, the extra one bit-identical. Because it
  builds one consensus feature per identification and all identifications of one spectrum read
  the same MS2/MS3 scan, the same reporter intensities enter the quantification twice. Protein
  abundance +37% (PROTA channel 1: 2.176e04 vs 1.584e04) and the PSM q-value column moves from
  0.1667 to 0.2. The peptide row is duplicated with unchanged values, so the damage lands at
  protein level rather than as a doubled peptide abundance.
- ProteomicsLFQ: 116 mzTab PSM rows against 115, plus a consensusXML difference. MSstats and
  Triqler output is unaffected.

Placement in ProteomicsLFQ is deliberately after the missing-spectrum-reference repair
(SpectrumMetaDataLookup::addMissingSpectrumReferences): an identification with no reference
cannot be keyed at all, so reducing earlier would silently skip exactly the files whose
references had to be reannotated. The new fixture demonstrates this - BSA1_F1.idXML carries no
spectrum references at all.

Both TOPP tests diff against the EXISTING un-duplicated references rather than new ones, since
"the duplicate changed no number" is the assertion; they also require the reduction to report,
because an identical output could otherwise mean it never ran. Verified by reverting each
reduction in turn and confirming the tests go red for the right reason.

ctest: 95/95 TOPP_ProteomicsLFQ + TOPP_IsobaricWorkflow pass, no reference file churn.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01S7QNzj4dhRnX5htcHZFmDm
@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Identification deduplication

Layer / File(s) Summary
Resolver API and implementation
src/openms/include/OpenMS/ANALYSIS/ID/IDConflictResolverAlgorithm.h, src/openms/source/ANALYSIS/ID/IDConflictResolverAlgorithm.cpp, src/pyOpenMS/bindings/bind_analysis.cpp
Adds reduceToOnePerSpectrum, reduction statistics, and Python bindings. The resolver retains the best-scoring entry for each spectrum, peptidoform, and charge group.
Resolver validation
src/tests/class_tests/openms/source/IDConflictResolverAlgorithm_test.cpp
Tests score directions, duplicate keys, chimeric spectra, missing data, inconsistent score directions, ordering, diagnostics, and empty input.
IsobaricWorkflow integration
src/topp/IsobaricWorkflow.cpp, src/tests/topp/CMakeLists.txt, src/tests/topp/IsobaricWorkflow_duplicate_psm_input.idXML, CHANGELOG
Reduces identifications before consensus-feature allocation. Adds diagnostics, input documentation, a duplicate-PSM fixture, and regression comparisons.
ProteomicsLFQ integration
src/topp/ProteomicsLFQ.cpp, src/tests/topp/CMakeLists.txt, src/tests/topp/ProteomicsLFQ_duplicate_psm_1.idXML, CHANGELOG
Reduces identifications after spectrum-reference repair. Adds diagnostics, input documentation, a duplicate-PSM fixture, and output regression comparisons.

Filename validation utilities

Layer / File(s) Summary
Filename utility API and implementation
src/openms/include/OpenMS/FORMAT/FileName.h, src/openms/source/FORMAT/FileName.cpp
Adds OpenMS::FileName utilities for stem and extension extraction and for validating filename lists by basename, extension, order, and set.
Filename utility validation
src/tests/class_tests/openms/source/FileName_test.cpp
Tests filename extraction and matching behavior across paths, extensions, ordering, set differences, count differences, and empty lists.

Sequence Diagram(s)

sequenceDiagram
  participant IsobaricWorkflow
  participant ProteomicsLFQ
  participant IDConflictResolverAlgorithm
  participant PeptideIdentificationList
  IsobaricWorkflow->>IDConflictResolverAlgorithm: reduceToOnePerSpectrum(ids)
  IDConflictResolverAlgorithm->>PeptideIdentificationList: remove duplicate identifications
  IDConflictResolverAlgorithm-->>IsobaricWorkflow: return reduction diagnostics
  ProteomicsLFQ->>IDConflictResolverAlgorithm: reduceToOnePerSpectrum(repaired ids)
  IDConflictResolverAlgorithm-->>ProteomicsLFQ: return reduction diagnostics
Loading

Possibly related issues

  • OpenMS/OpenMS 9871: Describes duplicate PSM rows that this change reduces in ProteomicsLFQ and IsobaricWorkflow.

Possibly related PRs

Suggested reviewers: jpfeuffer

Poem

A rabbit sorted spectra with care,
Kept one best match in each shared pair.
Distinct peptidoforms stayed in sight,
Filename lists matched left and right.
Tests hopped through the changes bright.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the affected tools and the main change: reducing duplicate identifications to one per spectrum.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch lfq-iso-reduce-per-spectrum

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

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

@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: 3

🧹 Nitpick comments (2)
src/tests/class_tests/openms/source/IDConflictResolverAlgorithm_test.cpp (1)

211-327: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a modified-peptidoform case.

Every sequence in this section is unmodified, so the section cannot show how the grouping treats modifications. Add a case with two identifications of one spectrum and charge, one carrying a modification, and assert that both survive.

💚 Proposed additional case
+  // Two peptidoforms of one backbone are two measurements and must both survive.
+  {
+    PeptideIdentificationList ids;
+    ids.push_back(makePepID_(ref, "PEPTIDEK", 2, 0.1));
+    ids.push_back(makePepID_(ref, "PEPT(Phospho)IDEK", 2, 0.2));
+    auto report = IDConflictResolverAlgorithm::reduceToOnePerSpectrum(ids);
+    TEST_EQUAL(report.removed, 0)
+    TEST_EQUAL(ids.size(), 2)
+  }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/IDConflictResolverAlgorithm_test.cpp`
around lines 211 - 327, Add a test case within reduceToOnePerSpectrum using two
identifications sharing the same spectrum and charge but differing by a peptide
modification, and assert both remain in ids with report.removed equal to zero.
Use the existing modified-peptidoform construction conventions and verify the
grouping distinguishes the modified and unmodified forms.
src/topp/IsobaricWorkflow.cpp (1)

639-672: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Extract the shared "reduce and log" pattern instead of duplicating it in two TOPP tools. Both sites call IDConflictResolverAlgorithm::reduceToOnePerSpectrum and then log each field of UnresolvedIdentifications with near-identical branching. The duplication has already caused the two copies to diverge: one reports one fewer diagnostic field than the other. ProteomicsLFQ already uses a shared DDAWorkflowCommons class for other cross-tool logic (e.g. mapMzML2Ids, calculateSeeds), which is a natural place for this helper.

  • src/topp/IsobaricWorkflow.cpp#L639-L672: extract this block into a shared helper (or add the missing multiply_identified_spectra log branch to match ProteomicsLFQ) so the two tools cannot drift again.
  • src/topp/ProteomicsLFQ.cpp#L953-L998: replace reduceToOnePerSpectrum_ with a call to the same shared helper used by IsobaricWorkflow.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/topp/IsobaricWorkflow.cpp` around lines 639 - 672, The duplicated
identification-reduction and diagnostic logging must use one shared
implementation. In src/topp/IsobaricWorkflow.cpp:639-672, move the
reduceToOnePerSpectrum reporting into a shared DDAWorkflowCommons helper,
including every UnresolvedIdentifications diagnostic such as
multiply_identified_spectra; in src/topp/ProteomicsLFQ.cpp:953-998, replace
reduceToOnePerSpectrum_ with that same helper and remove the duplicate local
logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@CHANGELOG`:
- Around line 333-339: Move the new IsobaricWorkflow bullet from the heading
near line 333 into the existing IsobaricWorkflow section later in the Changes
section, preserving the bullet text and removing the duplicate heading. Keep the
entry alongside the existing IsobaricWorkflow bullets, matching the
single-section pattern used by ProteomicsLFQ.

In `@src/openms/include/OpenMS/ANALYSIS/ID/IDConflictResolverAlgorithm.h`:
- Around line 125-145: The new public API is missing from pyOpenMS. Update the
analysis bindings in bind_analysis.cpp and the corresponding pyOpenMS stub/.pxd
declarations to expose IDConflictResolverAlgorithm::UnresolvedIdentifications
and its static reduceToOnePerSpectrum(PeptideIdentificationList&) method,
preserving the C++ return type and argument behavior.

In `@src/openms/source/ANALYSIS/ID/IDConflictResolverAlgorithm.cpp`:
- Around line 134-140: Update the inconsistent-group branch in
IDConflictResolverAlgorithm to increment surviving_here once per unresolved
group rather than by group_end - group. Preserve the existing group advancement
and continue behavior, matching the resolved branch’s group-level counting so
multiply_identified_spectra is not inflated.

---

Nitpick comments:
In `@src/tests/class_tests/openms/source/IDConflictResolverAlgorithm_test.cpp`:
- Around line 211-327: Add a test case within reduceToOnePerSpectrum using two
identifications sharing the same spectrum and charge but differing by a peptide
modification, and assert both remain in ids with report.removed equal to zero.
Use the existing modified-peptidoform construction conventions and verify the
grouping distinguishes the modified and unmodified forms.

In `@src/topp/IsobaricWorkflow.cpp`:
- Around line 639-672: The duplicated identification-reduction and diagnostic
logging must use one shared implementation. In
src/topp/IsobaricWorkflow.cpp:639-672, move the reduceToOnePerSpectrum reporting
into a shared DDAWorkflowCommons helper, including every
UnresolvedIdentifications diagnostic such as multiply_identified_spectra; in
src/topp/ProteomicsLFQ.cpp:953-998, replace reduceToOnePerSpectrum_ with that
same helper and remove the duplicate local logic.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bb4dbed5-8f67-49be-a8d1-738e013d9079

📥 Commits

Reviewing files that changed from the base of the PR and between 1131d8f and 49f487b.

📒 Files selected for processing (9)
  • CHANGELOG
  • src/openms/include/OpenMS/ANALYSIS/ID/IDConflictResolverAlgorithm.h
  • src/openms/source/ANALYSIS/ID/IDConflictResolverAlgorithm.cpp
  • src/tests/class_tests/openms/source/IDConflictResolverAlgorithm_test.cpp
  • src/tests/topp/CMakeLists.txt
  • src/tests/topp/IsobaricWorkflow_duplicate_psm_input.idXML
  • src/tests/topp/ProteomicsLFQ_duplicate_psm_1.idXML
  • src/topp/IsobaricWorkflow.cpp
  • src/topp/ProteomicsLFQ.cpp

Comment thread CHANGELOG Resolved
timosachsenberg added a commit that referenced this pull request Aug 8, 2026
Three findings from the automated review of #9892, all valid:

1. reduceToOnePerSpectrum() reported an unresolvable group as a chimeric spectrum. A group whose
   members disagree on isHigherScoreBetter() is left intact, and every member was then added to
   the per-spectrum survivor count, pushing multiply_identified_spectra above 1. That counter is
   documented -- and logged by both tools -- as spectra "naming different peptidoforms", so a
   single repeated peptidoform with a direction disagreement produced a second, contradictory
   message. Counted once now, as the reduced branch already does. The class test gained the
   assertion that pins it; verified to fail before the change (got 1, expected 0).

2. IDConflictResolverAlgorithm is wrapped in pyOpenMS, so the new API is bound too:
   UnresolvedIdentifications (read-only fields) and the reduceToOnePerSpectrum static.
   Exercised from Python: a duplicate pair reduces to the better-scoring one and reports it.

3. CHANGELOG had two "IsobaricWorkflow:" headings under one "Changes:" section -- the new entry
   is merged into the pre-existing one, matching how the ProteomicsLFQ entry was added.

ctest: 109/109 across TOPP_ProteomicsLFQ, TOPP_IsobaricWorkflow and IDConflictResolverAlgorithm.
pyOpenMS builds clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01S7QNzj4dhRnX5htcHZFmDm
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

All three review findings were valid and are fixed in 0ac0faa.

1. Unresolved group reported as chimeric (IDConflictResolverAlgorithm.cpp) — correct, and the reasoning was exactly right. A group whose members disagree on isHigherScoreBetter() is left intact, and I was then adding every member to the per-spectrum survivor count, which pushed multiply_identified_spectra above 1. That counter is documented — and logged by both tools — as spectra naming different peptidoforms, so one repeated peptidoform with a direction disagreement produced a second, contradictory message. Counted once now, as the reduced branch already did.

The class test gained TEST_EQUAL(report.multiply_identified_spectra, 0) on that case. I reverted the fix to check it constrains anything: it fails with got '1', expected '0', so it does.

2. pyOpenMS wrapper — also correct; I'd missed that the class is already bound at bind_analysis.cpp:562. Added UnresolvedIdentifications (read-only fields) and the reduceToOnePerSpectrum static, and exercised it from Python rather than just compiling it:

removed         = 1
example         = controllerType=0 controllerNumber=1 scan=2075 / PEPTIDEK / charge 2
surviving       = 1  score 0.1
multiply_ident. = 0

3. Duplicate CHANGELOG heading — correct, merged into the pre-existing IsobaricWorkflow: section, matching how the ProteomicsLFQ entry was added.

One note on the committable suggestion for (1): it renders as +report.inconsistent_score_direction; and +surviving_here; — the increment operators lost a character somewhere in generation, so it would not have compiled. The diff above it was right, and that is what I applied.

ctest: 109/109 across TOPP_ProteomicsLFQ, TOPP_IsobaricWorkflow and IDConflictResolverAlgorithm. pyOpenMS builds clean.

@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/pyOpenMS/bindings/bind_analysis.cpp (2)

578-589: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the unresolved score-direction case.

The docstring says that the best identification is kept for each key. The native implementation leaves a duplicate group unchanged when its isHigherScoreBetter() values disagree and increments inconsistent_score_direction. Document this exception and state that score ties retain the first input identification.

Proposed documentation update
         Identifications of one spectrum naming different peptidoforms are left alone, as are those without a spectrum reference or without hits.
+        Groups with conflicting `isHigherScoreBetter()` values are also left unchanged and counted in `inconsistent_score_direction`.
+        Score ties retain the first input identification.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/pyOpenMS/bindings/bind_analysis.cpp` around lines 578 - 589, Update the
reduceToOnePerSpectrum docstring to document that duplicate groups with
conflicting isHigherScoreBetter() values remain unchanged and are reported as
inconsistent_score_direction. Also state that score ties retain the first input
identification.

562-569: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add copy support for UnresolvedIdentifications.

This value type exposes only nb::init<>. Add its copy constructor, __copy__, and __deepcopy__ methods to match the surrounding pyOpenMS bindings. Otherwise Python callers cannot rely on standard copy behavior for the report returned by reduceToOnePerSpectrum.

Proposed binding update
     nb::class_<OpenMS::IDConflictResolverAlgorithm::UnresolvedIdentifications>(
             m, "UnresolvedIdentifications", "What IDConflictResolverAlgorithm.reduceToOnePerSpectrum did")
         .def(nb::init<>())
+        .def(nb::init<const OpenMS::IDConflictResolverAlgorithm::UnresolvedIdentifications &>())
+        .def("__copy__", [](const OpenMS::IDConflictResolverAlgorithm::UnresolvedIdentifications& self) {
+            return OpenMS::IDConflictResolverAlgorithm::UnresolvedIdentifications(self);
+        })
+        .def("__deepcopy__", [](const OpenMS::IDConflictResolverAlgorithm::UnresolvedIdentifications& self, nb::dict) {
+            return OpenMS::IDConflictResolverAlgorithm::UnresolvedIdentifications(self);
+        }, "memo"_a)
         .def_ro("removed", &OpenMS::IDConflictResolverAlgorithm::UnresolvedIdentifications::removed)

As per coding guidelines, pyOpenMS bindings must include default and copy constructors, plus __copy__ and __deepcopy__, when available.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/pyOpenMS/bindings/bind_analysis.cpp` around lines 562 - 569, Update the
UnresolvedIdentifications binding to expose its copy constructor alongside
nb::init<>, and add __copy__ and __deepcopy__ methods using the surrounding
pyOpenMS binding conventions. Keep the existing read-only fields unchanged.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openms/include/OpenMS/FORMAT/FileName.h`:
- Around line 31-43: Replace the line comments documenting public methods
stemName() and extension() with /** */ Doxygen blocks. Add `@brief`, `@param`[in]
file, and `@return` tags while preserving each method’s current behavior and
examples; do not alter the MatchingFileListsStatus enum documentation unless
needed for the same public API style.

In `@src/openms/source/FORMAT/FileName.cpp`:
- Around line 47-83: Replace the duplicate-dropping sl1_set and sl2_set
containers in the filename comparison logic with multiplicity-preserving
comparisons, such as std::multiset, so same_set is false when normalized names
have different counts and the result is SET_MISMATCH. Add a regression test
covering repeated normalized names such as ["a", "a", "b"] versus ["a", "b",
"b"], while preserving existing MATCH and ORDER_MISMATCH behavior.

---

Nitpick comments:
In `@src/pyOpenMS/bindings/bind_analysis.cpp`:
- Around line 578-589: Update the reduceToOnePerSpectrum docstring to document
that duplicate groups with conflicting isHigherScoreBetter() values remain
unchanged and are reported as inconsistent_score_direction. Also state that
score ties retain the first input identification.
- Around line 562-569: Update the UnresolvedIdentifications binding to expose
its copy constructor alongside nb::init<>, and add __copy__ and __deepcopy__
methods using the surrounding pyOpenMS binding conventions. Keep the existing
read-only fields unchanged.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 77c6195b-21f9-4769-aa5e-33bc169895f9

📥 Commits

Reviewing files that changed from the base of the PR and between 49f487b and 0ac0faa.

📒 Files selected for processing (8)
  • CHANGELOG
  • src/openms/extern/nlohmann_json/ lohmann-json:
  • src/openms/include/OpenMS/FORMAT/FileName.h
  • src/openms/source/ANALYSIS/ID/IDConflictResolverAlgorithm.cpp
  • src/openms/source/FORMAT/FileName.cpp
  • src/pyOpenMS/bindings/bind_analysis.cpp
  • src/tests/class_tests/openms/source/FileName_test.cpp
  • src/tests/class_tests/openms/source/IDConflictResolverAlgorithm_test.cpp
🚧 Files skipped from review as they are similar to previous changes (3)
  • CHANGELOG
  • src/tests/class_tests/openms/source/IDConflictResolverAlgorithm_test.cpp
  • src/openms/source/ANALYSIS/ID/IDConflictResolverAlgorithm.cpp

Comment on lines +31 to +43
/// Returns the basename of @p file without its (known) extension, e.g. "/x/foo.mzML.gz" -> "foo".
static String stemName(const String& file);

/// Returns the (known) extension of @p file including the leading '.', or "" if it has none.
static String extension(const String& file);

/// Result of validateMatchingFileNames().
enum class MatchingFileListsStatus
{
MATCH = 0, ///< Everything matches perfectly
ORDER_MISMATCH = 1, ///< Same set of files but in wrong order
SET_MISMATCH = 2 ///< Different sets of files (including size mismatch)
};

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use block Doxygen for the new public API.

Lines 31-43 use line comments. The public methods also omit required @brief, @param[in], and @return tags. Replace these comments with /** */ Doxygen blocks.

Proposed documentation update
-    /// Returns the basename of `@p` file without its (known) extension, e.g. "/x/foo.mzML.gz" -> "foo".
+    /**
+      `@brief` Return the basename without its known extension.
+      `@param`[in] file Input file name.
+      `@return` Basename without its extension.
+    */
     static String stemName(const String& file);

-    /// Returns the (known) extension of `@p` file including the leading '.', or "" if it has none.
+    /**
+      `@brief` Return the known extension, including the leading period.
+      `@param`[in] file Input file name.
+      `@return` The extension, or an empty string if no extension exists.
+    */
     static String extension(const String& file);

As per coding guidelines, Doxygen comments must use /** */ with @ tags, @brief is required, and parameter tags must specify direction.

📝 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
/// Returns the basename of @p file without its (known) extension, e.g. "/x/foo.mzML.gz" -> "foo".
static String stemName(const String& file);
/// Returns the (known) extension of @p file including the leading '.', or "" if it has none.
static String extension(const String& file);
/// Result of validateMatchingFileNames().
enum class MatchingFileListsStatus
{
MATCH = 0, ///< Everything matches perfectly
ORDER_MISMATCH = 1, ///< Same set of files but in wrong order
SET_MISMATCH = 2 ///< Different sets of files (including size mismatch)
};
/**
`@brief` Return the basename without its known extension.
`@param`[in] file Input file name.
`@return` Basename without its extension.
*/
static String stemName(const String& file);
/**
`@brief` Return the known extension, including the leading period.
`@param`[in] file Input file name.
`@return` The extension, or an empty string if no extension exists.
*/
static String extension(const String& file);
/// Result of validateMatchingFileNames().
enum class MatchingFileListsStatus
{
MATCH = 0, ///< Everything matches perfectly
ORDER_MISMATCH = 1, ///< Same set of files but in wrong order
SET_MISMATCH = 2 ///< Different sets of files (including size mismatch)
};
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/include/OpenMS/FORMAT/FileName.h` around lines 31 - 43, Replace
the line comments documenting public methods stemName() and extension() with /**
*/ Doxygen blocks. Add `@brief`, `@param`[in] file, and `@return` tags while
preserving each method’s current behavior and examples; do not alter the
MatchingFileListsStatus enum documentation unless needed for the same public API
style.

Source: Coding guidelines

Comment thread src/openms/source/FORMAT/FileName.cpp Outdated
Comment on lines +47 to +83
set<String> sl1_set;
set<String> sl2_set;
bool different_name_at_index = false;

// Process and compare each filename
for (size_t i = 0; i != sl1.size(); ++i)
{
String sl1_name = sl1[i];
String sl2_name = sl2[i];

if (basename)
{
sl1_name = File::basename(sl1_name);
sl2_name = File::basename(sl2_name);
}

if (ignore_extension)
{
sl1_name = FileHandler::stripExtension(sl1_name);
sl2_name = FileHandler::stripExtension(sl2_name);
}

sl1_set.insert(sl1_name);
sl2_set.insert(sl2_name);

if (sl1_name != sl2_name)
{
different_name_at_index = true;
}
}

const bool same_set = (sl1_set == sl2_set);

// Check if it's an order mismatch or complete mismatch
if (same_set)
{
return different_name_at_index ? MatchingFileListsStatus::ORDER_MISMATCH : MatchingFileListsStatus::MATCH;

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve duplicate file-name counts during comparison.

Line 47 and Line 48 use std::set, which removes duplicates. For ["a", "a", "b"] and ["a", "b", "b"], Line 78 reports equal sets and Line 83 returns ORDER_MISMATCH. The normalized lists have different multiplicities, so the result must be SET_MISMATCH.

Use std::multiset or per-name counts. Add a regression test with repeated normalized file names.

Proposed implementation update
-    set<String> sl1_set;
-    set<String> sl2_set;
+    multiset<String> sl1_set;
+    multiset<String> sl2_set;

As per coding guidelines, add or update relevant tests for changes under src/**/*.cpp.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/FORMAT/FileName.cpp` around lines 47 - 83, Replace the
duplicate-dropping sl1_set and sl2_set containers in the filename comparison
logic with multiplicity-preserving comparisons, such as std::multiset, so
same_set is false when normalized names have different counts and the result is
SET_MISMATCH. Add a regression test covering repeated normalized names such as
["a", "a", "b"] versus ["a", "b", "b"], while preserving existing MATCH and
ORDER_MISMATCH behavior.

Source: Coding guidelines

Three findings from the automated review of #9892, all valid:

1. reduceToOnePerSpectrum() reported an unresolvable group as a chimeric spectrum. A group whose
   members disagree on isHigherScoreBetter() is left intact, and every member was then added to
   the per-spectrum survivor count, pushing multiply_identified_spectra above 1. That counter is
   documented -- and logged by both tools -- as spectra "naming different peptidoforms", so a
   single repeated peptidoform with a direction disagreement produced a second, contradictory
   message. Counted once now, as the reduced branch already does. The class test gained the
   assertion that pins it; verified to fail before the change (got 1, expected 0).

2. IDConflictResolverAlgorithm is wrapped in pyOpenMS, so the new API is bound too:
   UnresolvedIdentifications (read-only fields) and the reduceToOnePerSpectrum static.
   Exercised from Python: a duplicate pair reduces to the better-scoring one and reports it.

3. CHANGELOG had two "IsobaricWorkflow:" headings under one "Changes:" section -- the new entry
   is merged into the pre-existing one, matching how the ProteomicsLFQ entry was added.

ctest: 109/109 across TOPP_ProteomicsLFQ, TOPP_IsobaricWorkflow and IDConflictResolverAlgorithm.
pyOpenMS builds clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01S7QNzj4dhRnX5htcHZFmDm
@timosachsenberg
timosachsenberg force-pushed the lfq-iso-reduce-per-spectrum branch from 0ac0faa to 23d2637 Compare August 8, 2026 18:29
@jpfeuffer

Copy link
Copy Markdown
Contributor

Hmm I think that feature linking was still retrieving matching non-best identifications from features that were linked together.
How is FeatureLinking currently resolving ambiguities?

Copy link
Copy Markdown
Contributor Author

How is FeatureLinking currently resolving ambiguities?

It doesn't — the linker resolves which features to group, never which identification wins.

With use_identifications=true (forced, ProteomicsLFQ.cpp:341), GridFeature snapshots annotations_ = the set of getHits()[0].getSequence() — sequence only, no charge, no score, no spectrum reference (GridFeature.cpp:18-36). QTCluster::add admits a neighbour only if its annotations intersect the centre's, either-side-empty admitted unconditionally, which is what makes MBR work (QTCluster.cpp:111-123). Centre with 0 or ≥2 annotations → optimizeAnnotations_ picks the sequence minimising summed feature distance across maps (QTCluster.cpp:282-355). RT/m/z/intensity, not PSM score.

And that choice is then discarded: createConsensusFeature_ → ConsensusFeature::insert copies every ID of every member unconditionally (ConsensusFeature.cpp:96-105). The TODO at QTCluster.cpp:343-347 says exactly this. So all ID-level resolution happens in the IDConflictResolverAlgorithm calls around the linker.

On the non-best retrieval: you're right that :1344 is keep_matching=true and resolveConflictKeepMatching_ scans all hits of the other IDs, promoting a match to rank 1 (IDConflictResolverAlgorithm.cpp:76-102). But the lower-rank promotion can't fire on this path — FFID truncates every ID to a single hit in addPeptideToMap_ before it ever reaches a feature (FeatureFinderIdentificationAlgorithm.cpp:1868-1870, invariant noted at :1763), so :1344 only ever sees hits[0]. What it does keep is one ID per run for the winning sequence, which is deliberate.

Why reduce at load: FFID keys on (AASequence, charge), so both copies of the duplicate land in the same assay, and every assay ID inside the feature's RT window is attached to it (:1731-1735, :1623-1634) — identical RT, so both. :1294 keeps one and moves the other to unassigned, not deleted; postprocess_ carries that list into the ConsensusMap (FeatureGroupingAlgorithm.h:50); ProteomicsLFQ passes report_unmapped=true into mzTab's export_unassigned_ids (:1916); and the PSM section exports assigned + unassigned (MzTab.cpp:2809-2813). That's the extra row. The linker can't catch it either way: it matches on sequence alone and never sees the spectrum reference. Reducing at load removes it before FFID sees it.

Making the linker's distance-based choice actually count is the QTCluster.cpp:343-347 TODO — I'd open that as its own issue rather than widen this PR.


Generated by Claude Code

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

one pattern that emerges a lot are the missing data contracts.
we get an input file that is valid idXML or consensusXML and we always need to ensure preconditions like: consistent score directions, if something is id resolved etc.

might be worth tightening what we write out to reduce the amount of pre-checks

This seems to be good to go for now (and is needed to move forward in the larger audit for qpx 1.1)

@jpfeuffer

Copy link
Copy Markdown
Contributor

Yes but I am not sure if this is the right contract here.

You have the information about the potential match of a feature against a spectrum but we decide to report it as unassigned only because it was the second best hit. Instead of leaving it attached or reattaching. Note that I think this can happen quite frequently with peptidoforms where in one map the algorithm decides on a different modification position as number 1.

@jpfeuffer

Copy link
Copy Markdown
Contributor

It will now look like a transferred identification instead of a genuine potentially close tie at a specific feature in a map.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

@jpfeuffer Maybe I overlooked something but I don't think we properly resolve those currently. If we want to support resolving nearly tied hits via linking I think we need to make sure all algorithms really support this use case. Then it should also be more explicit.
Note that this can also lead to errors: if e.g. a phospho site is on S in one run and on T in another, this might also hide something real.

@jpfeuffer

Copy link
Copy Markdown
Contributor

But it wasn't about resolving. It was about carrying over agreeing identifications to the result.

@jpfeuffer

Copy link
Copy Markdown
Contributor

If you link feature with IDs

  • A, B
  • C, A
  • A

Then the idea was to report that there was indeed evidence for A in map 2 with all its scores. And that it is not just a transferred identification

@jpfeuffer

Copy link
Copy Markdown
Contributor

It is a bit niche but could be valuable and less confusing as having an unattached PSM dangling somewhere.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

hmm I see the point but I see also a lot of ways this can go wrong e.g. both peptides elute at different RTs etc.
and properly solving that is an optimization problem

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Correcting my earlier comment — two of its citations were wrong, and they pointed in the wrong direction.

ProteomicsLFQ never calls the conflict resolver. I said :1344 is keep_matching=true and that resolveConflictKeepMatching_ runs on this path. It doesn't. ProteomicsLFQ.cpp:1344 is a meta-value strip loop, and resolveConflicts / resolveBetweenFeatures appear nowhere in ProteomicsLFQ.cpp — the only callers in the tree are the standalone IDConflictResolver tool (IDConflictResolver.cpp:131,153). My :1294 reference was wrong too; that line is targeted-experiment peptide conversion.

So nothing on this path is unassigned for being second best. The unassigned pushes reachable here are decoy (FeatureFinderIdentificationAlgorithm.cpp:1877), below psm_score_cutoff_ (:1886), RT region claimed by no feature (:1644), and assay with no feature candidates (:1833) — all unmappable-or-filtered, none rank-based. Linking drops nothing either: ConsensusFeature::insert copies every member's identifications unconditionally with a map_index stamp (ConsensusFeature.cpp:96-105).

@jpfeuffer — on carrying agreeing identifications over: you're right that we don't do it, and the reason is earlier than I suggested. Rank-2+ hits aren't demoted to unassigned, they're deleted: addPeptideToMap_ does peptide.getHits().resize(1) in place (~:1868-1870), with the invariant documented at :1763. By the time features exist the evidence is gone. resolveConflictKeepMatching_ (IDConflictResolverAlgorithm.cpp:218-244) is written to do exactly what you describe — it scans all hits for one matching the winner — but on this path every hit list has length 1, so it could only ever confirm a rank-1 hit that already agreed.

One thing worth recording for whenever that decision gets made: that function doesn't add the agreeing identification, it replaces the map's own rank-1 call with the winner (hits[0] = *hit; hits.resize(1)). So "carry over" as currently implemented would substitute a peptidoform the map didn't rank first — which is the flip side of the S-vs-T risk above. Add-with-provenance and replace are different features, and the existing code silently picks the second.

Supporting this needs FFID to retain rank-2+ hits against an invariant several call sites rely on, plus that add-vs-replace decision. Separate piece of work, not for this thread.

For the record on this PR specifically: reduceToOnePerSpectrum removes whole duplicate PeptideIdentifications of one spectrum (same peptidoform, same charge) and never edits a hit list, so rank-2 hits reach FFID exactly as before. Localization variants are never grouped — the key uses AASequence ordering, which compares per-residue modifications (AASequence.cpp:354-363), so PEP(Phospho)TIDE and PEPT(Phospho)IDE sort apart and both survive.

timosachsenberg added a commit that referenced this pull request Aug 11, 2026
Audited PRs merged since the last CHANGELOG update (#9881): most of
them (#9879, #9880, #9882, #9884, #9886, #9892, #9896, #9898, #9900,
#9901, #9888) already carried their own CHANGELOG entries. Only the
Docker library-stage fix (#9891) was missing one.


Claude-Session: https://claude.ai/code/session_01Jgrv6mFL3oawgLdYs1efPH

Co-authored-by: Claude <[email protected]>
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.

2 participants