Skip to content

perf(ProteinQuantifier): fix O(N^2) stall in PeptideAndProteinQuant::quantifyProteins - #9683

Merged
timosachsenberg merged 2 commits into
developfrom
fix/pepprotquant-quadratic-stall
Jun 29, 2026
Merged

timosachsenberg merged 2 commits into
developfrom
fix/pepprotquant-quadratic-stall

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Problem

On large isobaric (TMT/iTRAQ) inputs (~7M PSMs), the isobaric workflow / ProteinQuantifier appears to hang "at Quantifying peptides...". That log line is the only one emitted by PeptideAndProteinQuant::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 in quantifyProteins().

Root cause & fix

Three quadratic hotspots in quantifyProteins() / its helpers, all replaced with one-time indexes. All output is byte-identical.

Location Before After
calculateFileAndChannelLevelProteinAbundances_ — rescanned all of pep_quant_ calling AASequence::toUnmodifiedString() on every entry, for each (protein, selected peptide) pair O(N_pep²) (the dominant stall) reverse index unmodified seq → pep_quant_ entries, built once → ~O(N_pep)
mapAccessionToLeader(proteins) rebuilt inside the per-protein loop (loop-invariant) O(P²) hoisted, built once → O(P)
annotateQuantificationsToProteins — std::find_if over all indistinguishable groups per protein (the next stall after the above) O(P²) accession → group index, 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 preserves std::map (AASequence-sorted) iteration order. The first-match break therefore selects the identical peptidoform, and floating-point accumulation order is unchanged. The accession → group index keeps the first group in id_groups order, matching the previous find_if semantics.

Also

Fixes two pre-existing dead-#ifdef debug-only compile errors in the same file (a wrong getAccession_ overload and an undefined accession variable).

Testing

  • PeptideAndProteinQuant_test ✅
  • All 35 TOPP_ProteinQuantifier_* tests ✅, including the isobaric _16 (sample-level) and _17 (file+channel-level) references — byte-identical.

Notes

IsobaricWorkflow itself has no functional TOPP test (the block at src/tests/topp/CMakeLists.txt:986-990 is commented out); its quantification path is covered indirectly via the shared ProteinQuantifier references. Adding a dedicated IsobaricWorkflow functional test is a sensible follow-up.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved consistency of protein quantification and protein-level annotations, especially for file- and channel-level results.
    • Enhanced reliability when mapping peptide quantifications to protein groups and leaders in large datasets.
  • Refactor
    • Optimized internal lookup and indexing used during quantification to reduce repeated rescans of peptide/protein containers.
    • Streamlined protein-group and accession/label lookups to reuse precomputed mappings across calculations.

…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]>
@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Refactors PeptideAndProteinQuant to precompute accession and peptide-sequence lookup indices, then reuses them in protein quantification and protein-group annotation. It also switches selected lookup containers to std::unordered_map and updates related debug output.

Changes

Precomputed index for protein quantification

Layer / File(s) Summary
New type alias and updated method signature
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h
Adds unordered-map and vector support, defines FileLabelHash and UnmodifiedToEntriesIndex, switches sample_id_lookup_ to std::unordered_map, and updates calculateFileAndChannelLevelProteinAbundances_ to accept the reverse index.
Build indices in quantifyProteins and pass to calculation
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
Builds the accession→leader map and unmodified-peptide reverse index once, passes both into calculateFileAndChannelLevelProteinAbundances_, and changes readQuantData to use an unordered lookup container.
Revised lookup logic inside calculateFileAndChannelLevelProteinAbundances_
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
Extends the function signature, replaces the full pep_quant_ scan with bucketed reverse-index lookup, and updates debug leader accession reporting.
Optimized group lookup in annotateQuantificationsToProteins and debug fix
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp
Builds a one-time accession→ProteinGroup* index, replaces the find_if scan with direct lookup, and updates transferPeptideDataToProteins_ debug output to use leader_accession.

Suggested Reviewers

  • jpfeuffer

Poem

A rabbit hopped through peptide snow,
With lookup maps now set to grow.
One scan became a tiny hop,
Across the data, tickety-top.
Quant bunnies cheer: “No more full sweep!” 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 accurately highlights the main change: fixing the O(N^2) performance stall in PeptideAndProteinQuant::quantifyProteins.
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
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/pepprotquant-quadratic-stall

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.

🧹 Nitpick comments (3)
src/openms/source/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.cpp (2)

1079-1085: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use OpenMS debug logging and \n in changed debug output.

These changed debug blocks still write directly to std::cout and flush with endl.

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_PEPTIDEANDPROTEINQUANT output blocks.

As per coding guidelines, "**/*.cpp: Avoid std::endl and use \n instead" and "**/*.{h,hpp,cpp}: Use OpenMS logging macros and OpenMS::LogStream instead of std::cout or std::cerr directly."

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 win

Avoid raw pointers in the new group index.

accession_to_group is non-owning and local, so std::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 to id_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 win

Align 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 @brief Doxygen block. Consider std::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 @brief tag" 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

📥 Commits

Reviewing files that changed from the base of the PR and between da383e3 and 23609f3.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h
  • src/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]>

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

🧹 Nitpick comments (1)
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h (1)

216-222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer a non-owning reference type for the reverse index.

UnmodifiedToEntriesIndex is a lookup over existing pep_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

📥 Commits

Reviewing files that changed from the base of the PR and between 23609f3 and 5809365.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h
  • src/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

@timosachsenberg
timosachsenberg merged commit 519efd2 into develop Jun 29, 2026
18 checks passed
@timosachsenberg
timosachsenberg deleted the fix/pepprotquant-quadratic-stall branch June 29, 2026 10:44
timosachsenberg added a commit that referenced this pull request Jun 30, 2026
- #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]>
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