Repository navigation
perf(ProteinQuantifier): fix O(N^2) stall in PeptideAndProteinQuant::quantifyProteins - #9683
Conversation
…quantifyProteins On large isobaric (TMT/iTRAQ) inputs (~7M PSMs) the isobaric workflow / ProteinQuantifier appeared to hang "at Quantifying peptides...". That log line is the only one emitted by quantifyPeptides(); quantifyProteins() runs next and emits no log of its own, so its cost was attributed to the previous line. quantifyPeptides() is linear; the stall was quadratic work in quantifyProteins(). Fixes (all output byte-identical): - calculateFileAndChannelLevelProteinAbundances_ no longer rescans all of pep_quant_ (calling AASequence::toUnmodifiedString() on every entry) for each (protein, selected peptide) pair. A reverse index (unmodified sequence -> pep_quant_ entries) is built once and looked up directly. O(N_pep^2) -> ~O(N_pep). This was the dominant stall. - mapAccessionToLeader(proteins) is hoisted out of the per-protein loop (it is loop-invariant). O(P^2) -> O(P). - annotateQuantificationsToProteins() replaces the per-protein std::find_if over all indistinguishable groups with a one-time accession->group index. O(P^2) -> O(P). (This was the next stall after the two above on the same large inputs.) The reverse index is built by a single forward pass over pep_quant_, so each bucket preserves std::map (AASequence-sorted) iteration order; the first-match break therefore selects the identical peptidoform and floating-point accumulation order is unchanged. Also fixes two pre-existing dead-#ifdef debug-only compile errors in the same file (a wrong getAccession_ overload and an undefined `accession` variable). Validated: PeptideAndProteinQuant_test and all 35 TOPP_ProteinQuantifier_* tests (including the isobaric sample-level _16 and file+channel-level _17) pass with byte-identical output. Co-Authored-By: Claude Opus 4.8 <[email protected]>
📝 WalkthroughWalkthroughRefactors ChangesPrecomputed index for protein quantification
Suggested Reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp (2)
1079-1085: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse OpenMS debug logging and
\nin changed debug output.These changed debug blocks still write directly to
std::coutand flush withendl.Suggested direction
- std::cout << "DEBUG: Adding abundance for protein " << leader_accession + OPENMS_LOG_DEBUG << "DEBUG: Adding abundance for protein " << leader_accession << " fraction " << fraction.first << " filename " << filename.first << " charge " << charge.first << " channel " << channel.first - << ": " << channel.second << endl; + << ": " << channel.second << "\n";Apply the same pattern to the
DEBUG_PEPTIDEANDPROTEINQUANToutput blocks.As per coding guidelines, "
**/*.cpp: Avoidstd::endland use\ninstead" and "**/*.{h,hpp,cpp}: Use OpenMS logging macros andOpenMS::LogStreaminstead ofstd::coutorstd::cerrdirectly."Also applies to: 1287-1295, 1337-1344
🤖 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/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp` around lines 1079 - 1085, The DEBUG_PROTEINQUANTIFIER debug prints in PeptideAndProteinQuant should use OpenMS logging instead of writing directly to std::cout, and they should avoid std::endl in favor of newline output. Update the affected debug blocks in the abundance logging code paths (including the related DEBUG_PEPTIDEANDPROTEINQUANT sections) to route messages through the appropriate OpenMS log macro/LogStream pattern while preserving the same message content and formatting.Source: Coding guidelines
867-897: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAvoid raw pointers in the new group index.
accession_to_groupis non-owning and local, sostd::reference_wrapper<ProteinIdentification::ProteinGroup>communicates the lifetime contract without nullable raw pointers.Suggested direction
- std::map<std::string, ProteinIdentification::ProteinGroup*> accession_to_group; + std::map<std::string, std::reference_wrapper<ProteinIdentification::ProteinGroup>> accession_to_group; for (auto & g : id_groups) { for (const auto & a : g.accessions) { - accession_to_group.emplace(a, &g); + accession_to_group.emplace(a, std::ref(g)); } }- ProteinIdentification::ProteinGroup* id_group = group_it->second; + ProteinIdentification::ProteinGroup& id_group = group_it->second.get();Then update the local
id_group->...uses toid_group.....As per coding guidelines, "
**/*.{h,hpp,cpp}: Avoid raw pointers; prefer references or smart pointers."🤖 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/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp` around lines 867 - 897, The new accession_to_group index in PeptideAndProteinQuant::annotateProteinGroups uses a non-owning raw pointer for ProteinIdentification::ProteinGroup, which violates the pointer guideline. Replace the map value type with std::reference_wrapper<ProteinIdentification::ProteinGroup> so the lifetime contract is explicit, update the insertion in the id_groups loop accordingly, and switch the later id_group dereferences in the quantified-protein loop to reference access. Keep the existing “first group wins” behavior while removing nullable pointer semantics.Source: Coding guidelines
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h (1)
201-206: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAlign the new index alias with the header/raw-pointer guidelines.
The new header declaration uses non-owning raw pointers and
///text instead of the required@briefDoxygen block. Considerstd::reference_wrapper<const PeptideQuant::value_type>for the stored entries and update the comment format.Suggested direction
+#include <functional> `#include` <vector>- /// Index: unmodified peptide sequence -> all `@p` pep_quant_ entries (modified - /// peptidoforms) sharing that unmodified sequence, in `@p` pep_quant_ - /// (AASequence-sorted) iteration order. Built once per quantifyProteins() call so - /// that channel-level aggregation does not rescan `@p` pep_quant_ (calling - /// AASequence::toUnmodifiedString() on every entry) for every (protein, peptide) pair. - typedef std::map<std::string, std::vector<const PeptideQuant::value_type*>> UnmodifiedToEntriesIndex; + /** + `@brief` Index from unmodified peptide sequence to matching `@p` pep_quant_ entries. + + Stores non-owning references to modified peptidoform entries in `@p` pep_quant_ + in AASequence-sorted iteration order. Built once per quantifyProteins() call + so channel-level aggregation does not rescan `@p` pep_quant_ for every + (protein, peptide) pair. + */ + typedef std::map<std::string, std::vector<std::reference_wrapper<const PeptideQuant::value_type>>> UnmodifiedToEntriesIndex;As per coding guidelines, "
**/*.h: Add Doxygen documentation with@brieftag" and "**/*.{h,hpp,cpp}: Avoid raw pointers; prefer references or smart pointers."🤖 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/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h` around lines 201 - 206, The new UnmodifiedToEntriesIndex alias in PeptideAndProteinQuant.h should be updated to follow the header guidelines by replacing the non-owning raw pointer storage with std::reference_wrapper<const PeptideQuant::value_type> (or another reference-based alternative) and converting the surrounding /// prose into a proper Doxygen `@brief` block. Keep the alias name and its use in quantifyProteins() consistent, and adjust any indexing/building code that currently pushes or dereferences raw pointers so it stores and accesses references cleanly.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.
Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h`:
- Around line 201-206: The new UnmodifiedToEntriesIndex alias in
PeptideAndProteinQuant.h should be updated to follow the header guidelines by
replacing the non-owning raw pointer storage with std::reference_wrapper<const
PeptideQuant::value_type> (or another reference-based alternative) and
converting the surrounding /// prose into a proper Doxygen `@brief` block. Keep
the alias name and its use in quantifyProteins() consistent, and adjust any
indexing/building code that currently pushes or dereferences raw pointers so it
stores and accesses references cleanly.
In `@src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp`:
- Around line 1079-1085: The DEBUG_PROTEINQUANTIFIER debug prints in
PeptideAndProteinQuant should use OpenMS logging instead of writing directly to
std::cout, and they should avoid std::endl in favor of newline output. Update
the affected debug blocks in the abundance logging code paths (including the
related DEBUG_PEPTIDEANDPROTEINQUANT sections) to route messages through the
appropriate OpenMS log macro/LogStream pattern while preserving the same message
content and formatting.
- Around line 867-897: The new accession_to_group index in
PeptideAndProteinQuant::annotateProteinGroups uses a non-owning raw pointer for
ProteinIdentification::ProteinGroup, which violates the pointer guideline.
Replace the map value type with
std::reference_wrapper<ProteinIdentification::ProteinGroup> so the lifetime
contract is explicit, update the insertion in the id_groups loop accordingly,
and switch the later id_group dereferences in the quantified-protein loop to
reference access. Keep the existing “first group wins” behavior while removing
nullable pointer semantics.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 01df595d-5966-4b9a-b38c-9a652abab3a0
📒 Files selected for processing (2)
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.hsrc/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
…ptideAndProteinQuant Three maps that are only ever looked up by key (never range-iterated, so their iteration order can never affect output) are switched from std::map to std::unordered_map for O(1) average access. Output remains byte-identical. - sample_id_lookup_ (hit per (filename,charge,channel) cell in the innermost aggregation loop) and the local file_and_label_to_msfile_entry (hit per consensus feature) now use std::unordered_map keyed on pair<string,UInt> via a new private FileLabelHash functor. - UnmodifiedToEntriesIndex (the reverse index added in the previous commit) is now an unordered_map<string, vector<...>>. Only .find() is used; the per-bucket vector still preserves pep_quant_ (AASequence-sorted) order, so the first-match selection is unchanged. Containers whose iteration order is observable (pep_quant_/prot_quant_ row order, PeptideData.abundances float-accumulation order, and the SampleAbundances family which feeds orderBest_'s tie-break key driving top-N peptide selection) are deliberately left as std::map. Validated: PeptideAndProteinQuant_test and all 35 TOPP_ProteinQuantifier_* tests pass with byte-identical output. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h (1)
216-222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPrefer a non-owning reference type for the reverse index.
UnmodifiedToEntriesIndexis a lookup over existingpep_quant_entries, so raw pointers add nullable semantics that this code path does not need.std::reference_wrapper<const PeptideQuant::value_type>(or iterators) would express the contract more clearly and matches the OpenMS guideline to avoid raw pointers. As per coding guidelines,**/*.{h,hpp,cpp}: Avoid raw pointers; prefer references or smart pointers.🤖 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/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h` around lines 216 - 222, The reverse index type in PeptideAndProteinQuant is using raw pointers for entries that are only referencing existing pep_quant_ elements, which adds unnecessary nullable semantics. Update UnmodifiedToEntriesIndex to use a non-owning reference-based type such as std::reference_wrapper<const PeptideQuant::value_type> or iterators, and adjust any code that builds or reads this index accordingly so quantifyProteins() and related lookup logic continue to preserve ordering without raw pointers.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.
Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h`:
- Around line 216-222: The reverse index type in PeptideAndProteinQuant is using
raw pointers for entries that are only referencing existing pep_quant_ elements,
which adds unnecessary nullable semantics. Update UnmodifiedToEntriesIndex to
use a non-owning reference-based type such as std::reference_wrapper<const
PeptideQuant::value_type> or iterators, and adjust any code that builds or reads
this index accordingly so quantifyProteins() and related lookup logic continue
to preserve ordering without raw pointers.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: bbfb23ab-a7d3-483b-924f-e01905e304f6
📒 Files selected for processing (2)
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.hsrc/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
- src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
- #9654: on-disc extractIonImage for imzML (IonImageExtraction.h shared kernel, OnDiscImzMLExperiment::extractIonImage without full dataset load) - #9683: perf fix for three O(N²)/O(P²) hotspots in PeptideAndProteinQuant::quantifyProteins that caused hangs on large isobaric inputs (~7M PSMs) - #9511: vcpkg integration (GSOC 2026) — vcpkg.json, CMakePresets.json, and CI workflow for reproducible dependency management Claude-Session: https://claude.ai/code/session_01KNeJXnuadWQJgwm5kXVQjo Co-authored-by: Claude <[email protected]>
Problem
On large isobaric (TMT/iTRAQ) inputs (~7M PSMs), the isobaric workflow /
ProteinQuantifierappears to hang "at Quantifying peptides...". That log line is the only one emitted byPeptideAndProteinQuant::quantifyPeptides(). The next call,quantifyProteins(), emits no log of its own, so its cost is attributed to the previous line.quantifyPeptides()is linear — the stall is quadratic work inquantifyProteins().Root cause & fix
Three quadratic hotspots in
quantifyProteins()/ its helpers, all replaced with one-time indexes. All output is byte-identical.calculateFileAndChannelLevelProteinAbundances_— rescanned all ofpep_quant_callingAASequence::toUnmodifiedString()on every entry, for each (protein, selected peptide) pairunmodified seq → pep_quant_ entries, built once → ~O(N_pep)mapAccessionToLeader(proteins)rebuilt inside the per-protein loop (loop-invariant)annotateQuantificationsToProteins—std::find_ifover all indistinguishable groups per protein (the next stall after the above)accession → groupindex, built once → O(P)Net for the protein phase: O(N_pep² + P²) → ~O(N_pep + P).
Why it stays byte-identical
The reverse index is built by a single forward pass over
pep_quant_, so each bucket preservesstd::map(AASequence-sorted) iteration order. The first-matchbreaktherefore selects the identical peptidoform, and floating-point accumulation order is unchanged. Theaccession → groupindex keeps the first group inid_groupsorder, matching the previousfind_ifsemantics.Also
Fixes two pre-existing dead-
#ifdefdebug-only compile errors in the same file (a wronggetAccession_overload and an undefinedaccessionvariable).Testing
PeptideAndProteinQuant_test✅TOPP_ProteinQuantifier_*tests ✅, including the isobaric_16(sample-level) and_17(file+channel-level) references — byte-identical.Notes
IsobaricWorkflowitself has no functional TOPP test (the block atsrc/tests/topp/CMakeLists.txt:986-990is commented out); its quantification path is covered indirectly via the sharedProteinQuantifierreferences. Adding a dedicatedIsobaricWorkflowfunctional test is a sensible follow-up.🤖 Generated with Claude Code
Summary by CodeRabbit