Skip to content

feature: ascore with phospho decoys - #7933

Closed
timosachsenberg wants to merge 17 commits into
developfrom
feature_ascore
Closed

timosachsenberg wants to merge 17 commits into
developfrom
feature_ascore

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Mar 21, 2025 •

Copy link
Copy Markdown
Contributor

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

  • New Features

    • PhosphoScoring: optional inclusion of decoy phosphorylation sites (A, G, L) for FLR analysis via an "add_decoys" option.
    • AScore now emits a ProFormaString meta value with localization scores.
    • New numerical utilities for binomial/log-sum-exp calculations.
  • Bug Fixes / Stability

    • AScore rewritten for improved numerical stability and non-recursive performance.
  • Tests

    • Expanded tests for decoy handling and the new math utilities.
  • Chores

    • Spectrum preprocessing promoted to the public API.

@coderabbitai

coderabbitai Bot commented Mar 21, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

AScore and related tooling were extended to optionally include PhosphoDecoy residues (A, G, L) in phosphorylation-site analysis. New helpers for residue classification, ProForma string generation, and spectrum generation were added; AScore internals were refactored (defaulted destructor, TheoreticalSpectrumGenerator member, add_decoys_ flag). Math utilities and public spectrum preprocessing were also introduced and tests updated.

Changes

Cohort / File(s) Change Summary
AScore public header
src/openms/include/OpenMS/ANALYSIS/ID/AScore.h
Converted ProbablePhosphoSites to a struct, added TheoreticalSpectrumGenerator spectrum_generator_, bool add_decoys_, new static methods isPhosphoSite(char) and isPhosphoDecoySite(char), generateProFormaString_(...), and changed destructor to = default.
AScore implementation
src/openms/source/ANALYSIS/ID/AScore.cpp
Added add_decoy parameter/flag handling; implemented isPhosphoDecoySite; updated numberOfPhosphoEvents_, getSites_, and createTheoreticalSpectra_ to count and optionally include decoy sites and emit metadata.
AScore tests & test helpers
src/tests/class_tests/openms/source/AScore_test.cpp
Added AScoreTestHelper, new tests for phospho and phospho-decoy site detection (getPhosphoSitesTest_, getPhosphoDecoySitesTest_, isPhosphoDecoy), adjusted existing tests to expect updated ion counts and decoy-aware behavior.
PhosphoScoring tool
src/topp/PhosphoScoring.cpp
Added add_decoys parameter to enable PhosphoDecoy analysis; included SimpleSearchEngineAlgorithm header for preprocessing support.
Math utilities
src/openms/include/OpenMS/MATH/MathFunctions.h
Added numerical-stable helpers: log_binomial_coef, log_sum_exp, and binomial_cdf_complement with validation and edge-case handling.
Math tests
src/tests/class_tests/openms/source/MathFunctions_test.cpp
Removed zoomIn tests; added tests for log_binomial_coef, log_sum_exp, and binomial_cdf_complement.
SimpleSearchEngineAlgorithm API
src/openms/include/OpenMS/ANALYSIS/ID/SimpleSearchEngineAlgorithm.h
Promoted preprocessSpectra to public API (OPENMS_DLLAPI) and removed private preprocessSpectra_. Added header guard (#pragma once).
SimpleSearchEngineAlgorithm impl
src/openms/source/ANALYSIS/ID/SimpleSearchEngineAlgorithm.cpp
Renamed implementation preprocessSpectra_ → preprocessSpectra and updated call sites accordingly.
pyOpenMS pxd
src/pyOpenMS/pxds/AScore.pxd
Removed member Size AScore from ProbablePhosphoSites binding.
CHANGELOG Documented PhosphoDecoy support, AScore refactor (non-recursive/performance), ProForma meta value, and new score-switching API mentions.

Sequence Diagram(s)

sequenceDiagram
    participant Tool as PhosphoScoring (tool)
    participant A as AScore
    participant TG as TheoreticalSpectrumGenerator
    participant PP as Preprocessing (SimpleSearchEngineAlgorithm::preprocessSpectra)
    Note over Tool,PP: new optional step when add_decoys=true
    Tool->>PP: preprocess spectra (frag tol, ppm?)
    Tool->>A: compute scores (peptide, spectrum, add_decoys flag)
    A->>A: identify phospho sites (isPhosphoSite / isPhosphoDecoySite)
    alt include decoys
        A->>TG: generate theoretical spectra (apply decoy mods on A/G/L)
    else only canonical
        A->>TG: generate theoretical spectra (apply S/T/Y mods)
    end
    A-->>Tool: results + ProFormaString meta + phospho counts (regular, decoy)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • fix:: AScore #7905 — Modified AScore's phosphorylation-event counting logic (numberOfPhosphoEvents_), directly related to decoy-event counting changes in this PR.

Suggested labels

Review effort 2/5

Suggested reviewers

  • jpfeuffer
  • cbielow

Poem

I'm a rabbit nibbling code by moonlight bright,
A, G, L join S, T, Y in the scoring night.
I flag decoys and stitch ProForma strings neat,
Hopping through spectra with quick, tiny feet.
🐰✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% 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 PR title "feature: ascore with phospho decoys" is concise and accurately summarizes the primary change — adding phospho-decoy support to AScore — which matches the diffs (add_decoys parameter, AScore logic/test updates, and PhosphoScoring changes); it is specific enough for a reviewer scanning history.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature_ascore

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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab26b59 and e43e853.

📒 Files selected for processing (2)
  • src/openms/source/ANALYSIS/ID/AScore.cpp (10 hunks)
  • src/topp/PhosphoScoring.cpp (2 hunks)
🧰 Additional context used
🪛 Cppcheck (2.10-2)
src/topp/PhosphoScoring.cpp

[error] 300-300: Unmatched ')'. Configuration

(syntaxError)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (windows-2022, cl.exe, default)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: cppcheck-test
🔇 Additional comments (10)
src/topp/PhosphoScoring.cpp (1)

59-61: Good documentation addition for the new feature.

The documentation clearly explains the new functionality to analyze PhosphoDecoy sites (A, G, L) for false localization rate (FLR) calculations, and how to enable it using the 'add_decoys' parameter.

src/openms/source/ANALYSIS/ID/AScore.cpp (9)

41-42: Good addition of the add_decoys parameter.

The parameter is well documented and properly configured with valid strings. This provides a clean way to enable/disable PhosphoDecoy site analysis.


63-101: Well-structured implementation for phosphorylation event counting.

The code properly counts both regular phosphorylation events and PhosphoDecoy events separately, with good logging and error handling. The warning for PhosphoDecoy sites when add_decoys is disabled is particularly helpful.


160-164: Good metadata addition for phosphorylation types.

Adding separate metadata values for regular and decoy phosphorylation counts will be valuable for downstream analysis and debugging.


432-435: Clean implementation of helper method for decoy site identification.

The isPhosphoDecoySite_ method provides a clear way to identify PhosphoDecoy residues (A, G, L).


437-454: Good extension of site retrieval to include decoy sites.

The getSites_ method now properly includes PhosphoDecoy sites when the feature is enabled, maintaining backward compatibility.


457-480: Well-implemented counting function for phosphorylation events.

The numberOfPhosphoEvents_ method has been updated to count both regular and decoy phosphorylation events with appropriate debug logging.


485-566: Improved permutation calculation with early termination checks.

The implementation now includes early termination checks to avoid excessive computations when the number of permutations would exceed the maximum limit. Good error handling and detailed debug logging.


604-629: Well-structured modification application based on residue type.

The code now properly distinguishes between standard phosphorylation sites (S, T, Y) and PhosphoDecoy sites (A, G, L) when applying modifications, with appropriate debug logging and error handling.


753-753: Parameter update in updateMembers_.

The add_decoys_ member variable is correctly initialized from the parameter value.

Comment thread src/topp/PhosphoScoring.cpp Resolved

@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/ID/AScore.cpp (1)

609-634: Robust modification application logic in createTheoreticalSpectra_

The implementation correctly:

  1. Determines the residue type at each position
  2. Applies either Phospho or PhosphoDecoy modification based on residue type
  3. Logs detailed debug information about applied modifications
  4. Includes warning for unexpected residue types

One suggestion: consider adding a precondition check to validate permutation positions against sequence length to prevent potential out-of-bounds access.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e43e853 and 4364bd0.

📒 Files selected for processing (4)
  • src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (3 hunks)
  • src/openms/source/ANALYSIS/ID/AScore.cpp (10 hunks)
  • src/tests/class_tests/openms/source/AScore_test.cpp (5 hunks)
  • src/topp/PhosphoScoring.cpp (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/topp/PhosphoScoring.cpp
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (windows-2022, cl.exe, default)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: cppcheck-test
🔇 Additional comments (16)
src/tests/class_tests/openms/source/AScore_test.cpp (4)

434-446: Good addition of tests for isPhosphoDecoySite method

The test correctly verifies that 'A', 'G', and 'L' are identified as phospho decoy sites, while 'S', 'T', and 'Y' are correctly identified as non-phospho decoy sites. This ensures the core functionality for distinguishing between regular phosphorylation sites and decoy sites works correctly.


459-480: Comprehensive test coverage for getSitesTest_ with add_decoys parameter

The tests effectively cover both cases:

  1. When add_decoys=true: verifies that all potential sites (S, T, Y, A, G, L) are detected
  2. When add_decoys=false: verifies that only standard sites (S, T, Y) are detected

This ensures the parameter correctly controls whether PhosphoDecoy sites are included in the analysis.


541-544: Test for phospho decoy removal from sequence

Good addition of a test case that verifies PhosphoDecoy modifications are properly removed from sequences, complementing the existing test for regular Phospho modifications.


728-760: Comprehensive tests for PhosphoDecoy functionality in compute method

The tests effectively verify:

  1. When add_decoys=true: both regular and decoy phosphorylation events are recognized and counted
  2. When add_decoys=false: PhosphoDecoy sites are ignored, and a warning is logged
  3. Metadata is correctly updated with counts for different modification types

This provides good coverage for the new functionality.

src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (3)

44-46: Good documentation of the PhosphoDecoy feature

The added documentation clearly explains that the implementation now supports PhosphoDecoy modifications on A, G, and L residues in addition to standard phosphorylation sites, and explains the purpose (FLR calculations).


70-75: Well-designed utility methods for site identification

The two new static methods provide a clear and maintainable way to identify phospho and phospho decoy sites. This encapsulates the logic for determining what constitutes each type of site, making the code more maintainable and reducing the risk of inconsistencies.


187-187: Appropriate addition of member variable for controlling decoy inclusion

The new boolean member variable add_decoys_ properly allows for controlling whether PhosphoDecoy sites should be included in the analysis, which is consistent with the new parameter.

src/openms/source/ANALYSIS/ID/AScore.cpp (9)

41-43: Well-defined parameter for PhosphoDecoy inclusion

The parameter is properly defined with:

  • Clear description explaining its purpose for FLR calculation
  • Default value of "false" to maintain backward compatibility
  • Validation to ensure only "true" or "false" values are accepted
  • Tagged as an advanced parameter, which is appropriate

This ensures users can control the feature without breaking existing workflows.


63-101: Robust handling of phosphorylation event counting

The implementation now:

  1. Counts both regular and decoy phosphorylation events
  2. Separates counters for detailed metadata
  3. Logs helpful debug information when decoys are enabled
  4. Provides a clear warning when decoys are found but the feature is disabled

This ensures proper handling of the different modification types and good user feedback.


160-164: Good metadata enrichment for phosphorylation types

Adding metadata about the counts of regular and decoy phosphorylation events provides valuable information for downstream analysis, particularly for FLR calculations.


432-440: Clear implementation of site identification methods

The implementation of isPhosphoDecoySite and isPhosphoSite is straightforward and correctly identifies the respective residue types. This encapsulation improves code readability and maintainability.


447-456: Properly updated getSites_ method

The method now correctly handles both standard phosphorylation sites and decoy sites based on the add_decoys_ setting, ensuring consistency with the rest of the implementation.


462-485: Thorough reimplementation of numberOfPhosphoEvents_

The method has been properly reimplemented to count:

  1. Regular phosphorylation events using "(Phospho)" marker
  2. PhosphoDecoy events using "(PhosphoDecoy)" marker
  3. Log helpful debug information about the total count

This ensures accurate counting of all phosphorylation events in the sequence.


491-572: Improved computePermutations_ with early termination

The method now includes sophisticated early termination logic to avoid excessive computation when:

  1. The number of phosphorylation events exceeds available sites
  2. The estimated number of permutations exceeds the configured maximum
  3. The maximum is exceeded during recursion

This improves performance for complex peptides by failing fast when computation would be excessive.


582-584: Updated removePhosphositesFromSequence_ for decoy handling

The method now correctly removes both regular phosphorylation markers and decoy markers, ensuring all modifications are properly handled.


757-758: Proper member variable update in updateMembers_

The add_decoys_ member variable is correctly updated from the parameter, ensuring consistency between the parameter and internal state.

@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/ID/AScore.cpp (1)

125-133: Improved early termination handling.

The early termination check is more explicit now, and the TODO comment suggests a potential heuristic approach for handling excessive permutations.

Consider implementing the mentioned heuristic to handle cases where the number of permutations exceeds the maximum, instead of just terminating the calculation. This would improve the robustness of the algorithm.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4364bd0 and 2925e68.

📒 Files selected for processing (3)
  • src/openms/include/OpenMS/MATH/MathFunctions.h (2 hunks)
  • src/openms/source/ANALYSIS/ID/AScore.cpp (13 hunks)
  • src/tests/class_tests/openms/source/MathFunctions_test.cpp (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
src/tests/class_tests/openms/source/MathFunctions_test.cpp (1)
src/openms/include/OpenMS/MATH/MathFunctions.h (6)
  • log_binomial_coef (453-473)
  • log_binomial_coef (453-453)
  • log_sum_exp (482-491)
  • log_sum_exp (482-482)
  • binomial_cdf_complement (505-552)
  • binomial_cdf_complement (505-505)
🪛 Cppcheck (2.10-2)
src/tests/class_tests/openms/source/MathFunctions_test.cpp

[error] 19-19: There is an unknown macro here somewhere. Configuration is required. If START_TEST is a macro then please configure it.

(unknownMacro)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (windows-2022, cl.exe, default)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: cppcheck-test
🔇 Additional comments (19)
src/tests/class_tests/openms/source/MathFunctions_test.cpp (5)

5-6: Updated maintainer and authors in file header.

File maintainer and authors have been updated to reflect current ownership.


24-39: Unit tests for log_binomial_coef are comprehensive.

The tests cover normal cases, edge cases (k=0, k=n), symmetry properties, and invalid input conditions, providing good test coverage for the new function.


42-57: Thorough tests for log_sum_exp function.

Tests cover normal cases, handling of small values, and the important edge case with negative infinity, ensuring the function works correctly in all scenarios.


59-87: Comprehensive test coverage for binomial_cdf_complement function.

Tests include normal cases, edge cases, boundary conditions (p=0, p=1), invalid inputs, and specific test cases relevant to the AScore functionality. The test with large values (N=100) is especially valuable for checking numerical stability.


272-276: Good replacement of custom implementation with standard function.

Replacing the manual cumulative score calculation with the new Math::binomial_cdf_complement function improves code maintainability and numerical stability.

src/openms/source/ANALYSIS/ID/AScore.cpp (10)

40-41: Added parameter for PhosphoDecoy site analysis.

New parameter allows including PhosphoDecoy sites (A, G, L) in phosphorylation site analysis for false localization rate (FLR) calculation.


62-100: Enhanced phosphorylation event counting with separate tracking for decoys.

The code now separately counts regular phosphorylation events and PhosphoDecoy events, with appropriate logging. It also properly handles backward compatibility by returning the original hit if PhosphoDecoy sites are found but add_decoys is false.


158-163: Added metadata for phosphorylation types.

When decoys are enabled, metadata about regular and decoy phosphorylation counts is now included in the output.


438-446: Added helper methods for identifying site types.

New static methods improve code readability and maintainability by centralizing the logic for identifying PhosphoDecoy sites and phosphorylation sites.


448-465: Updated getSites_ method to include decoy sites.

The method now uses the new helper functions and includes PhosphoDecoy sites when enabled.


467-491: Improved phosphorylation event counting implementation.

The method now counts both regular and PhosphoDecoy events with better logging.


497-526: Added early termination optimization to computePermutations_.

The code now performs an early check to avoid unnecessary computation if the number of permutations would exceed the maximum. This optimization uses the binomial coefficient to estimate the number of permutations.


570-578: Added permutation count check during recursion.

The code now checks if the maximum number of permutations is exceeded during the recursion, preventing excessive computation.


602-640: Enhanced createTheoreticalSpectra_ with residue-specific modifications.

The method now applies different modifications based on residue type (standard phosphorylation vs. PhosphoDecoy) with detailed logging for debugging purposes.


764-764: Updated updateMembers_ to initialize add_decoys_ field.

The member variable is properly initialized from the parameters.

src/openms/include/OpenMS/MATH/MathFunctions.h (4)

19-22: Added necessary Boost libraries for new mathematical functions.

The new includes support the implementation of binomial coefficient, gamma function, and logarithmic calculations needed for the new functions.


445-473: Implemented log_binomial_coef function for numerical stability.

This function calculates the logarithm of the binomial coefficient C(n,k) using the log-gamma function. It includes proper edge case handling and optimization for large k values using symmetry.


475-491: Added log_sum_exp function for numerically stable calculations.

This helper function performs the log-sum-exp operation in a numerically stable way by handling negative infinity cases and using the maximum value to avoid overflow/underflow issues.


493-552: Implemented robust binomial_cdf_complement function.

This function calculates P(X ≥ n) for a binomial distribution with comprehensive handling of:

  • Input validation to ensure valid parameters
  • Edge cases for improved performance
  • Numerical stability for extreme values
  • Optimization for large p values
  • Log domain computation for numerical stability
  • Result bounds checking

The implementation is well-documented and includes all necessary validations.

…d optimize permutation generation with bitmasking
…coy and AScore improvements for numerical stability

@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)
CHANGELOG (2)

40-40: Good addition of PhosphoScoring tool enhancement, but could be more descriptive.

The changelog entry correctly documents the new feature but would benefit from a brief explanation of what PhosphoDecoy support means for users (e.g., "for false localization rate calculations").

- PhosphoScoring tool: support PhosphoDecoy
+ PhosphoScoring tool: support PhosphoDecoy modifications for false localization rate (FLR) calculations

47-47: AScore entry should mention the PhosphoDecoy support.

The AScore implementation change is documented, but doesn't explicitly mention the PhosphoDecoy functionality that appears to be a key part of this PR.

- AScore, non-recursive, more numerically stable implementation
+ AScore, non-recursive, more numerically stable implementation with PhosphoDecoy support
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2e6018f and 8755311.

📒 Files selected for processing (1)
  • CHANGELOG (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (windows-2022, cl.exe, default)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: cppcheck-test

@timosachsenberg timosachsenberg changed the title Feature ascore with phospho decoys feature: ascore with phospho decoys Mar 24, 2025

@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 (3)
CHANGELOG (1)

48-48: Consider consolidating with previous AScore entry

This entry appears to be somewhat redundant with the entry on line 41, as both mention the change from recursive to non-recursive implementation in AScore. Consider consolidating these entries or providing more unique information in this second entry.

-AScore, non-recursive, more numerically stable implementation
+AScore: Implementation is now more numerically stable
src/tests/class_tests/openms/source/MathFunctions_test.cpp (1)

5-6: Update authors to include Timo Sachsenberg in the list.

Based on previous review comments, the authors list should include Timo Sachsenberg.

 // --------------------------------------------------------------------------
-// $Maintainer: Timo Sachsenberg$
-// $Authors: Marc Sturm, Chris Bielow $
+// $Maintainer: Timo Sachsenberg $
+// $Authors: Marc Sturm, Chris Bielow, Timo Sachsenberg $
 // --------------------------------------------------------------------------
src/openms/source/ANALYSIS/ID/AScore.cpp (1)

125-127: Consider implementing the suggested heuristic in a future update.

The TODO comments outline a good heuristic approach for handling large numbers of permutations, which would be valuable to implement.

This heuristic could significantly improve performance for peptides with many potential phosphorylation sites.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 095941c and fa918dc.

📒 Files selected for processing (3)
  • CHANGELOG (1 hunks)
  • src/openms/source/ANALYSIS/ID/AScore.cpp (13 hunks)
  • src/tests/class_tests/openms/source/MathFunctions_test.cpp (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
src/tests/class_tests/openms/source/MathFunctions_test.cpp (1)
src/openms/include/OpenMS/MATH/MathFunctions.h (6)
  • log_binomial_coef (453-473)
  • log_binomial_coef (453-453)
  • log_sum_exp (482-491)
  • log_sum_exp (482-482)
  • binomial_cdf_complement (505-552)
  • binomial_cdf_complement (505-505)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (windows-2022, cl.exe, default)
  • GitHub Check: cppcheck-test
🔇 Additional comments (13)
CHANGELOG (2)

40-40: Appropriate documentation of the PhosphoDecoy support

This entry clearly documents the new support for PhosphoDecoy in the PhosphoScoring tool, which is a key feature of this PR.


41-41: Good documentation of implementation improvement

The replacement of recursive implementation with an iterative bitmask approach is well documented, including the benefits (improved performance and avoiding stack overflow for large inputs).

src/tests/class_tests/openms/source/MathFunctions_test.cpp (4)

172-188: Test cases for log_binomial_coef look good.

The test coverage is comprehensive, testing normal cases, edge cases, the symmetry property, and invalid inputs. This validates all key aspects of the function.


190-205: Test cases for log_sum_exp are comprehensive.

The tests properly validate normal cases, edge cases with very small values, and special cases with negative infinity, ensuring numerical stability in different scenarios.


207-236: Thorough test coverage for binomial_cdf_complement.

The tests cover normal cases, edge cases, specific probabilities (0, 1), invalid inputs, and larger values. The inclusion of AScore-specific test cases ensures the function works correctly in its intended context.


242-246: Good use of the new numerically stable implementation.

Utilizing Math::binomial_cdf_complement from MathFunctions.h is appropriate, and the comments clearly explain the function's purpose.

src/openms/source/ANALYSIS/ID/AScore.cpp (7)

40-41: Good parameter definition for decoy site support.

The parameter is well-defined with clear documentation and valid string options.


57-98: Well-structured handling of phospho and phospho decoy events.

The implementation properly counts both regular and decoy phosphorylation events, with good logging when decoys are enabled and appropriate warning when decoys are present but not enabled.


157-162: Useful metadata for downstream analysis.

Adding metadata about regular and decoy phospho counts provides valuable information for downstream analysis.


407-415: Good abstraction with static helper methods.

These methods provide a clean way to identify phospho and phospho decoy sites, improving code maintainability.


436-460: Improved phospho event counting.

The function now properly counts both regular and decoy phosphorylation events with good debug logging.


462-582: Excellent documentation and robustness improvements.

The extensive comments explain the algorithm, complexity, edge cases, and termination conditions. The implementation includes better early termination checks and error handling.

🧰 Tools
🪛 GitHub Check: CodeFactor

[notice] 462-554: src/openms/source/ANALYSIS/ID/AScore.cpp#L462-L554
Complex Method


616-641: Robust modification application logic.

The code correctly applies either Phospho or PhosphoDecoy modifications based on residue type, with appropriate error handling and logging.

@jpfeuffer

Copy link
Copy Markdown
Contributor

I think this could be improved a lot by actually calculating cumulative scores and not always the full binomial probability.
Then you also would not need the weird permutation generation in the beginning (for which I am not sure if I like the bitmask version better).

But if this fixes things, go ahead. The stable version at least somewhat fixes the disadvantages of this simple approach here.

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

🧹 Nitpick comments (2)
src/openms/source/ANALYSIS/ID/AScore.cpp (2)

208-210: Consider additional test cases for score calculation

Using abs() to avoid -0 score values is reasonable, but it might be worth adding unit tests to verify this behavior handles all edge cases correctly.


126-130: Consider implementing the heuristic mentioned in TODO

The TODO comment mentions a potential heuristic approach for handling cases with too many permutations, which would be a valuable enhancement.

Would you like me to suggest an implementation approach for this heuristic to handle cases with an excessive number of permutations?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa918dc and 5d6f576.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (6 hunks)
  • src/openms/source/ANALYSIS/ID/AScore.cpp (13 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (1)
src/openms/source/ANALYSIS/ID/AScore.cpp (1)
  • AScore (20-48)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (windows-2022, cl.exe, default)
  • GitHub Check: cppcheck-test
🔇 Additional comments (18)
src/openms/source/ANALYSIS/ID/AScore.cpp (12)

39-40: Good addition of PhosphoDecoy support parameter

Adding a configuration option for including decoy sites is a clean way to extend functionality while maintaining backward compatibility. The parameter documentation clearly explains the purpose.


44-47: Good initialization of spectrum generator

Proper initialization of the spectrum generator with explicit parameter settings ensures reproducible behavior across different environments.


62-87: Well-structured counting of phosphorylation events

The implementation properly separates the counting of regular phosphorylation and decoy phosphorylation events, which provides clear tracking for both types of modifications.


89-100: Good defensive programming with warnings

The code appropriately warns users when PhosphoDecoy sites are found but not enabled for analysis, preventing silent handling of unexpected data.


108-111: Clear comment for site determination

The updated comment clearly indicates that both regular and decoy sites are considered when the feature is enabled.


159-164: Useful metadata addition

Adding metadata about phosphorylation types (regular vs. decoy counts) provides valuable information for downstream analysis.


244-247: Improved numerical stability

Using the numerically stable implementation from MathFunctions for the binomial CDF calculation is an excellent improvement that prevents potential numerical issues.


409-417: Well-designed helper methods

The static methods for identifying phospho and phospho decoy sites improve code readability and maintainability by centralizing this logic.


419-436: Clean implementation of site detection

The updated getSites_ method elegantly handles both standard phosphorylation sites and decoy sites, using the newly created helper methods for clear logic.


438-462: Comprehensive phospho event counting

The rewritten numberOfPhosphoEvents_ method properly handles both types of phosphorylation events and includes helpful debug logging.


464-584: Excellent documentation and optimization of permutation calculation

The enhanced computePermutations_ method includes thorough documentation, early termination conditions for better performance, and a more efficient bitmask-based implementation.


604-642: Robust handling of modification application

The code intelligently applies the appropriate modification type based on the residue type, with good error handling for unexpected residue types.

src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (6)

17-17: Good addition of required include

Including TheoreticalSpectrumGenerator is necessary for the new member variable.


27-34: Improved struct definition with default initialization

Converting ProbablePhosphoSites from a class to a struct and initializing member variables with default values improves code clarity and prevents potential uninitialized variable issues.


42-44: Clear documentation of extended functionality

The added comment clearly describes the extended support for PhosphoDecoy modifications and their purpose (FLR calculations).


56-56: Modern C++ best practice

Using = default for the destructor follows modern C++ best practices and is more efficient than an empty implementation.


68-73: Well-documented static helper methods

The static methods are properly documented and enhance code readability by encapsulating specific checks.


185-186: Good member variable documentation

The new member variables are well-documented, making their purpose clear to future developers.

Comment on lines +68 to +73
/// return is char is a phospho decoy site
static bool isPhosphoDecoySite(char residue);

/// return is char is a phospho site
static bool isPhosphoSite(char residue);

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.

💡 Verification agent

🧩 Analysis chain

Consider unit testing for site detection methods

Since these methods are central to the new decoy functionality, ensure they have comprehensive unit tests covering all possible residue cases.


🏁 Script executed:

#!/bin/bash
# Check if there are tests for the new phospho site detection methods

echo "Searching for tests of isPhosphoDecoySite and isPhosphoSite methods..."
rg --type cpp "isPhosphoDecoySite|isPhosphoSite" src/tests/

Length of output: 851


Enhance Unit Test Coverage for Site Detection Methods

In src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (lines 68-73), both isPhosphoDecoySite and isPhosphoSite are declared. While tests for isPhosphoDecoySite are present (see src/tests/class_tests/openms/source/AScore_test.cpp), there are currently no dedicated tests for isPhosphoSite. Please add comprehensive unit tests for isPhosphoSite covering all relevant residue cases to ensure complete and robust functionality.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/openms/source/ANALYSIS/ID/AScore.cpp (2)

125-143: Consider consolidating metadata assignment.

The metadata for phosphorylation counts is set at both lines 125-127 and 186-187. This appears redundant and could lead to maintenance issues if one location is updated but not the other.

-    phospho.setMetaValue("phospho_decoy_count", decoy_phospho_count);
-    phospho.setMetaValue("regular_phospho_count", regular_phospho_count);
-    phospho.setMetaValue("phospho_sites", number_of_phosphorylation_events);

     if (number_of_sites == number_of_phosphorylation_events) 
     {
       phospho.setScore(unambiguous_score_);
      
       // Create a map with scores of 1.0 for all phosphorylation sites
       std::map<Size, double> site_scores;
       for (Size site : sites)  // 'sites' contains all phosphorylation site positions
       {
         site_scores[site] = unambiguous_score_;  // This will be converted to probability ~1.0
       }
      
       // Create ProForma string with scores for all sites
       String proforma = generateProFormaString_(phospho.getSequence(), site_scores);
       phospho.setMetaValue("ProForma", proforma);
+      phospho.setMetaValue("phospho_decoy_count", decoy_phospho_count);
+      phospho.setMetaValue("regular_phospho_count", regular_phospho_count);
+      phospho.setMetaValue("phospho_sites", number_of_phosphorylation_events);
       phospho.setMetaValue("AScore_pep_score", unambiguous_score_); // initialize score with unambiguous score  
       return phospho;
     } 

Alternatively, set the metadata only once in one location, perhaps after line 143 but before the return statement.


469-493: Consider optimizing string search operations.

The current implementation performs multiple string searches, which could be optimized for better performance. Consider a single pass through the string to count both types of modifications.

-  /// Count all phosphorylation events in a sequence, including both regular and decoy events
   Size AScore::numberOfPhosphoEvents_(const String& sequence) const 
   {
     Size cnt_phospho_events = 0;
-    Size pos = 0;
-    
-    // Count regular phosphorylation events
-    while ((pos = sequence.find("(Phospho)", pos)) != std::string::npos)
-    {
-      ++cnt_phospho_events;
-      pos += 9; // Move past "(Phospho)"
-    }
-    
-    // Count PhosphoDecoy events
-    pos = 0; // Reset position for PhosphoDecoy search
-    while ((pos = sequence.find("(PhosphoDecoy)", pos)) != std::string::npos)
-    {
-      ++cnt_phospho_events;
-      pos += 14; // Move past "(PhosphoDecoy)"
-    }
+    
+    // Count both regular and decoy phosphorylation events in a single pass
+    for (Size pos = 0; pos < sequence.size(); )
+    {
+      Size found_pos = sequence.find('(', pos);
+      if (found_pos == std::string::npos) break;
+      
+      if (sequence.substr(found_pos, 10) == "(Phospho)") 
+      {
+        ++cnt_phospho_events;
+        pos = found_pos + 10;
+      }
+      else if (sequence.substr(found_pos, 15) == "(PhosphoDecoy)") 
+      {
+        ++cnt_phospho_events;
+        pos = found_pos + 15;
+      }
+      else
+      {
+        // Skip to next opening parenthesis
+        pos = found_pos + 1;
+      }
+    }
     
     OPENMS_LOG_DEBUG << "Found " << cnt_phospho_events << " phosphorylation events in sequence: " << sequence << std::endl;
     
     return cnt_phospho_events;
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5d6f576 and 7fb3236.

📒 Files selected for processing (5)
  • CHANGELOG (1 hunks)
  • src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (7 hunks)
  • src/openms/source/ANALYSIS/ID/AScore.cpp (13 hunks)
  • src/pyOpenMS/pxds/AScore.pxd (1 hunks)
  • src/tests/class_tests/openms/source/AScore_test.cpp (10 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (2)
src/openms/source/ANALYSIS/ID/AScore.cpp (1)
  • AScore (23-51)
src/tests/class_tests/openms/source/AScore_test.cpp (2)
  • peptide (98-123)
  • peptide (98-100)
src/tests/class_tests/openms/source/AScore_test.cpp (3)
src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (2)
  • AScore (47-190)
  • AScore (56-56)
src/openms/source/ANALYSIS/ID/AScore.cpp (1)
  • AScore (23-51)
src/topp/PhosphoScoring.cpp (2)
  • hit (239-252)
  • hit (239-239)
🪛 GitHub Check: CodeFactor
src/openms/source/ANALYSIS/ID/AScore.cpp

[notice] 462-554: src/openms/source/ANALYSIS/ID/AScore.cpp#L462-L554
Complex Method

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (windows-2022, cl.exe, default)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: cppcheck-test
🔇 Additional comments (28)
src/pyOpenMS/pxds/AScore.pxd (1)

30-40: Member variable Size AScore was removed from ProbablePhosphoSites class

This change aligns with the transition mentioned in the AI summary where ProbablePhosphoSites has been changed from a class to a struct in the C++ code. The removal simplifies the structure and is consistent with the broader changes in the AScore implementation.

CHANGELOG (2)

40-42: Well-documented changes for PhosphoDecoy support and AScore improvements

The changelog entries provide clear information about the significant changes:

  1. Added PhosphoDecoy support to the PhosphoScoring tool
  2. Replaced the recursive implementation with an iterative bitmask approach to improve performance and prevent stack overflow for large inputs
  3. Added a new ProFormaString meta value output containing peptide sequences with phosphorylation site localization scores in ProForma-like format

These improvements should enhance both functionality and performance.


49-49: Consistent documentation of AScore implementation changes

This entry reinforces that the AScore implementation is now non-recursive and more numerically stable, which is consistent with the previous changelog entry. Good practice to highlight the improvement in numerical stability separately.

src/openms/source/ANALYSIS/ID/AScore.cpp (10)

13-16: Good addition of necessary includes.

The additions of MathFunctions and additional STL headers (sstream, iomanip) are appropriate for the new functionality, particularly for the ProForma string generation that needs string formatting capabilities.


42-43: Good parameter addition for PhosphoDecoy support.

The new parameter add_decoys with proper documentation and valid string options follows the established pattern in the codebase. Setting the default to "false" ensures backward compatibility.


47-50: Well-structured spectrum generator initialization.

The initialization of spectrum_generator_ with appropriate parameter values is properly placed in the constructor. Setting isotope_model to "none" and add_first_prefix_ion to "true" ensures consistent theoretical spectrum generation.


70-108: Good implementation of phosphorylation event counting with validation.

The code properly counts both regular and decoy phosphorylation events separately and includes appropriate logging. The validation check at line 102 prevents silent failures when decoy sites are found but not enabled.


440-448: Well-implemented static helper methods.

The static methods isPhosphoDecoySite and isPhosphoSite are simple and focused, making the code more maintainable and testable.


450-467: Good implementation of site detection with decoy support.

The getSites_ method has been properly modified to include PhosphoDecoy sites when enabled. The code is clear and well-structured.


623-624: Good update to handle PhosphoDecoy markers.

The removePhosphositesFromSequence_ method has been properly updated to remove both regular and decoy phosphorylation markers.


649-673: Well-structured modification application based on residue type.

The code correctly applies the appropriate modification based on residue type with good logging and error handling for unexpected cases.


791-856: Well-implemented ProForma string generation.

The generateProFormaString_ method creates a ProForma-compatible string with site scores, which is a valuable addition for downstream analysis. The code properly handles both regular and decoy sites.


865-865: Good parameter update implementation.

The code correctly initializes the add_decoys_ member variable from the parameter value in the updateMembers_ method.

src/tests/class_tests/openms/source/AScore_test.cpp (8)

81-197: Excellent addition of helper class for testing.

The new AScoreTestHelper class provides reusable functionality for creating test cases, which improves code maintainability and test clarity. The methods are well-documented with clear purposes and parameter descriptions.


553-565: Good test coverage for PhosphoDecoy site recognition.

The test for isPhosphoDecoySite covers all the relevant cases for both PhosphoDecoy sites (A, G, L) and non-PhosphoDecoy sites (S, T, Y).


570-599: Comprehensive test coverage for getSites_ with decoys.

The tests for getSitesTest_ have been expanded to cover cases with add_decoys set to both true and false, verifying the correct behavior in both scenarios.


660-663: Good testing of sequence modification removal.

The test for removePhosphositesFromSequenceTest_ now includes a case with PhosphoDecoy modifications to ensure they are properly removed.


767-768: Good test initialization for decoy support.

Setting the add_decoys parameter to "false" for the initial tests ensures backward compatibility is maintained and tested.


847-909: Excellent test coverage for PhosphoDecoy functionality.

The tests thoroughly verify the behavior of the PhosphoDecoy functionality, including testing with both enabled and disabled settings, mixed modification types, and ProForma string generation.


912-1167: Comprehensive test cases using the helper class.

The additional test section provides thorough coverage of various scenarios using the new helper class, including single and multiple phosphorylation sites, decoy sites, ambiguous localization, and edge cases.


455-457: Updated test expectations for site determining ions.

The change in expectations for site determining ions sizes from 7 to 8 indicates an improvement in the algorithm's ability to identify site-determining ions.

Also applies to: 468-473

src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (7)

17-17: Good addition of necessary include.

Including TheoreticalSpectrumGenerator.h is necessary for the new member variable and functionality.


27-34: Good change from class to struct with default initialization.

Changing ProbablePhosphoSites from a class to a struct makes sense for a simple data container. Adding default initialization (using {}) for all members is a good practice to avoid uninitialized values.


42-44: Good documentation for extended functionality.

The documentation has been updated to clearly explain the extension to support PhosphoDecoy modifications on A, G, and L residues for FLR calculations.


56-56: Good simplification with default destructor.

Using the default destructor simplifies the code and follows modern C++ practices.


68-73: Well-documented site detection methods.

The static methods isPhosphoDecoySite and isPhosphoSite are well-documented with clear purpose statements.


175-177: Good documentation for ProForma string generation.

The method description clearly explains that it generates a ProForma-like string with phosphorylation site localization scores.


188-189: Well-defined member variables.

The new member variables add_decoys_ and spectrum_generator_ are well-documented and properly placed with the other class variables.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

I think this could be improved a lot by actually calculating cumulative scores and not always the full binomial probability. Then you also would not need the weird permutation generation in the beginning (for which I am not sure if I like the bitmask version better).

It’s not a speed issue. The bitmask will probably make it easier when dealing with multiple mods in the future.

I am still not 100% sure how reassignment should handle PhosphoDecoys though. Currently they might reassign Phospho to neighboring decoy sites. Also there seem to be more permutations with same scores (because of less site determining ions if also decoys are possible).

But if this fixes things, go ahead. The stable version at least somewhat fixes the disadvantages of this simple approach here.

@jpfeuffer

Copy link
Copy Markdown
Contributor

Sorry, what's reassignment in this case? I am not too familiar with the algorithm.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

The current implementation annotates the highest scoring permutation. If decoys are enabled this can mean that PAPT(Phospho) becomes PA(PhosphoDecoy)PT if this leads to a higher score. More complex combinations also exist if multiple Phospho events are observed.

@jpfeuffer

Copy link
Copy Markdown
Contributor

Ah, I guess ideally one would at least report the best decoy score and the best target score but do the reassignment to the best target. But there is probably something more sound.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

…logic

- Added comprehensive Doxygen-style comments to the AScore class methods, constructors, and member functions to improve code readability and maintainability.
- Updated the compute method to handle edge cases more robustly, including early termination for empty spectra and improved handling of phosphorylation site counts.
- Adjusted the scoring mechanism to ensure that the highest scoring permutations are accurately reflected in the output.
- Modified unit tests to reflect changes in scoring logic, ensuring that expected values are consistent with the new implementation.
- Updated ProForma string generation to accurately represent phosphorylation site scores.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (12)
src/openms/source/ANALYSIS/ID/AScore.cpp (10)

23-29: Clarify constructor docstring.

The added doc comments are helpful but could emphasize that the constructor sets up parameters (such as add_decoys) for controlling decoy-site analysis. Including an explicit reference to how decoy-related parameters are initialized might improve clarity for new users.


55-59: Proactive parameter synchronization.

The lines initializing spectrum_generator_'s parameters look correct. Double-check that changes in default spectrum-generation settings do not conflict with other parts of the application, especially if advanced parameters (like neutral losses) need to be considered for decoy analysis.


183-195: Permutation generation limit checks.

The code logs if permutations are empty or exceed max_permutations_. This is helpful for diagnosing performance bottlenecks. Ensure that an appropriate fallback or user-facing message clarifies why early termination occurred.


253-264: AScore difference calculation.

The logic to compute AScore from difference between first and second permutations is correct. Double-check that the code properly handles edge cases where multiple permutations share the same top or second-best score.


383-475: Finding next-best permutations for site-level scoring.

The logic is complex yet well-commented. Ensure boundary conditions are tested (e.g., no second-best permutation found). Overall, it effectively captures site-level comparisons.


604-621: Composite approach in getSites_.

This method unifies logic for standard vs. decoy sites, making it easier to maintain. Confirm you handle edge cases with non-std residues or with peptides containing X placeholders.


631-654: Total phospho events in sequence.

Your approach for searching "(Phospho)" and "(PhosphoDecoy)" is reliable. Just watch out for custom naming in the future. For a large-scale system, you might consider a more robust method for tracking variable modifications, but for now this is good.


808-866: Creation of annotated theoretical spectra.

The code sets the correct modification type based on residue classification, then uses spectrum_generator_. Consider how partial decoy modifications might exist in other contexts (e.g., multiple non-phospho modifications). In normal usage, this is acceptable.


877-908: Peak picking in 100 Da windows.

Good strategy to reduce noise and normalize. For extended mass range or larger windows, you might reexamine the 100 Da bin size. Otherwise, looks fine.


921-948: Scoring permutations at multiple peak depths.

Looping from depth=1 to 10 is typical for AScore. Confirm that 10 is always appropriate, or consider making it a parameter.

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

453-469: Extended test for site-determining ion size changes.

Increasing expected ions from 7 to 8 for certain permutations indicates updated theoretical or decoy sets. Ensure coverage includes boundary cases (e.g., Ion types a/b/y only).


767-767: CodeFactor whitespace notice.

There’s a mention of redundant blank lines at or near line 1092. Consider removing extra blank lines to keep the codebase tidy and pass style checks.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7fb3236 and 8dce4dc.

📒 Files selected for processing (3)
  • src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (4 hunks)
  • src/openms/source/ANALYSIS/ID/AScore.cpp (20 hunks)
  • src/tests/class_tests/openms/source/AScore_test.cpp (10 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
src/tests/class_tests/openms/source/AScore_test.cpp (3)
src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (2)
  • AScore (72-408)
  • AScore (81-81)
src/openms/source/ANALYSIS/ID/AScore.cpp (1)
  • AScore (30-59)
src/topp/PhosphoScoring.cpp (2)
  • hit (239-252)
  • hit (239-239)
src/openms/source/ANALYSIS/ID/AScore.cpp (2)
src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (12)
  • AScore (72-408)
  • AScore (81-81)
  • compute (105-105)
  • numberOfPhosphoEvents_ (303-303)
  • removePhosphositesFromSequence_ (313-313)
  • generateProFormaString_ (379-379)
  • computePermutations_ (218-218)
  • determineHighestScoringPermutations_ (266-266)
  • computeCumulativeScore_ (292-292)
  • isPhosphoDecoySite (108-108)
  • isPhosphoSite (111-111)
  • createTheoreticalSpectra_ (327-327)
src/tests/class_tests/openms/source/AScore_test.cpp (21)
  • compute (751-751)
  • real_spectrum (68-71)
  • real_spectrum (68-68)
  • sites (34-37)
  • sites (34-34)
  • permutations (63-66)
  • permutations (63-63)
  • peptide_site_scores (46-49)
  • peptide_site_scores (46-46)
  • peptide_site_scores (75-78)
  • peptide_site_scores (75-75)
  • N (51-54)
  • N (51-51)
  • sequence (58-61)
  • sequence (58-58)
  • sequence (131-134)
  • sequence (131-131)
  • without_phospho (30-32)
  • without_phospho (30-30)
  • peptide (98-123)
  • peptide (98-100)
🪛 GitHub Check: CodeFactor
src/tests/class_tests/openms/source/AScore_test.cpp

[notice] 1092-1092: src/tests/class_tests/openms/source/AScore_test.cpp#L1092
Redundant blank line at the end of a code block should be deleted. (whitespace/blank_line)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (windows-2022, cl.exe, default)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: cppcheck-test
🔇 Additional comments (37)
src/openms/source/ANALYSIS/ID/AScore.cpp (20)

49-50: Parameter naming alignment.

The parameter name add_decoys clearly describes its purpose. Confirm that it matches naming conventions in related tools (e.g., PhosphoScoring) for consistency.


80-82: Base score reset is correct.

Re-initializing the PeptideHit’s score to -1 for fresh calculations is good practice to avoid carrying stale scoring data across runs.


84-90: Guard for empty spectra.

The early return for empty spectra is well-handled. Ensure that upstream logic (e.g., data loading or pre-filtering) also detects or warns about unexpected empty spectra.

Would you like a script to search for all calls to AScore::compute to confirm that proper checks exist upstream?


94-98: Phospho event counting and sequence stripping.

Using numberOfPhosphoEvents_ and removePhosphositesFromSequence_ clarifies the logic for subsequent permutations. Implementation looks consistent.


99-102: Separate counters for different modifications.

Storing separate counts for regular vs. decoy phosphorylations provides valuable metadata. Good addition for clarity in FLR analysis.


122-133: Return behavior when decoys are found but disabled.

When decoy_phospho_count > 0 but add_decoys_ is false, the function logs a warning and returns immediately. This is correct for preventing partial or misleading decoy-based results.


161-179: Handling unambiguous assignments.

Marking all sites phosphorylated with a special “unambiguous” score is logical. However, the large numeric value may conflict with the “lower is better” concept. Confirm that tools reading these scores do not misinterpret them.


197-199: Creating theoretical spectra for permutations.

The call to createTheoreticalSpectra_ is well-structured. Verify that advanced control over fragment types (e.g., a, b, c ions) is not needed for decoy scenarios.


294-297: Use of abs in probability-to-score conversion.

Applying abs to avoid negative-zero is a minor detail, but consistent. The rest of the code correctly does -10 log10(...). Good practice.


335-343: Base match probability logic.

Multiply by 2 * tolerance / 100 for random match probability is a known approximation. Looks consistent with prior references. No concerns.


356-365: Cumulative binomial probability computation.

Using Math::binomial_cdf_complement is an efficient approach. Implementation is straightforward.


488-518: Computing site-determining ions.

The set-difference approach with tolerance is correct. Great job ensuring that overlapping ions are excluded from both permutations. This can be crucial for high-quality site localization.


530-553: Matched ions with user-defined depth.

The function correctly truncates windows to the selected depth, ensuring consistent scoring at each level. This appears stable and well tested.


568-582: Weighted peptide score formula from Beausoleil.

Implementation matches standard references. The method is concise and clear.


587-590: PhosphoDecoy site detection.

Recognizing A, G, L as PhosphoDecoy is straightforward. The helper remains readable and well-scoped.


599-602: Phospho site detection.

Similarly, S, T, Y are handled in isPhosphoSite. Pairing it with isPhosphoDecoySite clarifies residue classification.


684-776: Bitmask approach for permutations.

Iterative combination generation is indeed more efficient than recursion for large sets. The early termination checks help with performance. Good job.


786-795: Removal of phosphorylation markers.

removePhosphositesFromSequence_ reliably strips both (Phospho) and (PhosphoDecoy) annotations. Straightforward implementation.


957-968: Ranking by weighted peptide score.

Simple multimap insertion is adequate for partial sorting. If performance becomes an issue, you could consider a custom data structure. Currently no concerns.


1090-1097: Parameter synchronization in updateMembers_.

Updating local variables from param_ is correct. This ensures that toggling “add_decoys” or adjusting tolerances is reflected promptly. Good housekeeping.

src/tests/class_tests/openms/source/AScore_test.cpp (11)

12-13: Additional includes for test utilities.

Including <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h> and <OpenMS/METADATA/DataArrays.h> expands your test harness to simulate theoretical spectra with metadata. Good approach for thorough coverage.


81-97: AScoreTestHelper utility introduction.

Providing a dedicated helper class for generating synthetic spectra and hits is excellent. It keeps test code tidy and reusable across test scenarios.


553-565: Dedicated test for isPhosphoDecoySite.

This new test verifies A/G/L residues and excludes S/T/Y. Great coverage. Consider adding borderline or unusual residues if edge cases arise.


570-577: Verifying site detection logic with standard phospho sites.

A thorough check for positions in the unmodified sequence. The test is consistent with the documented approach.


578-593: Testing add_decoys = true.

Successfully verifying that L, A, G are treated as potential sites. This ensures decoy logic is tested beyond the code. Good coverage.


594-599: Ensuring decoys are disabled properly.

Verifying that decoy residues are skipped when add_decoys is false is crucial. Well done.


660-664: Test coverage for removing both Phospho and PhosphoDecoy.

Demonstrating that (PhosphoDecoy) is also stripped from sequences is good. This matches production code changes.


845-846: Confirm the unambiguous scoring behavior.

Your test asserts the final peptide has hit7.getScore() == 1e6. This is consistent with “unambiguous” logic, but again might conflict with “lower is better.” Confirm that other code handles this special case properly.


851-869: PhosphoDecoy tests.

These lines confirm that decoy counts are stored in metadata. This meets the PR objectives for decoy site analysis. The test coverage is good.


888-909: ProForma annotation tests.

Verifying the exact string format is a great approach to ensure future changes do not break external tools expecting that format.


912-1165: Additional scenario tests (TheoreticalSpectrumGenerator usage).

The extended UTs (e.g., ambiguous spectra, multiple phospho sites, max_permutations, decoys off) demonstrate robust coverage. They closely align with the newly introduced decoy logic. This is exemplary test completeness.

🧰 Tools
🪛 GitHub Check: CodeFactor

[notice] 1092-1092: src/tests/class_tests/openms/source/AScore_test.cpp#L1092
Redundant blank line at the end of a code block should be deleted. (whitespace/blank_line)

src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (6)

17-17: Additional include for TheoreticalSpectrumGenerator.

This reflects the new capability to generate spectra within AScore. Looks aligned with the .cpp usage.


27-44: Refactoring ProbablePhosphoSites into a struct.

Declarations are more concise, with clear defaults for each member. This is well-structured—no immediate issues.


81-81: Destructor override = default.

Switching to the default destructor is idiomatic modern C++. This is simpler and correct.


107-112: Static methods for residue classification.

Both isPhosphoDecoySite and isPhosphoSite are well-placed as static methods. This matches the approach used throughout the PR.


404-404: add_decoys_ private data member.

Encapsulating the decoy toggle within the class is a good design choice. It ensures consistent usage across AScore’s internal methods.


407-407: Added TheoreticalSpectrumGenerator.

Declaring this generator as a class member is appropriate, especially for repeated calls in createTheoreticalSpectra_.

Comment on lines +61 to +75
/**
* @brief Main method to compute phosphorylation site localization scores
*
* This method implements the AScore algorithm for phosphorylation site localization:
* 1. Extracts phosphorylation sites from the peptide sequence
* 2. Generates all possible phosphorylation site permutations
* 3. Creates theoretical spectra for each permutation
* 4. Compares these with the experimental spectrum using a windowed peak picking approach
* 5. Calculates scores for each permutation and determines the most likely sites
*
* @param hit The peptide hit containing the sequence with potential phosphorylation sites
* @param real_spectrum The experimental MS/MS spectrum
* @return A modified PeptideHit with AScore values for each phosphorylation site
* The score field contains the best AScore value
*/

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.

🛠️ Refactor suggestion

Ensure consistency with “lower is better” scoring.

The doc comment states “The score field contains the best AScore value (lower is better).” However, for unambiguous assignments, the code sets a large score (unambiguous_score_ = 1e6). This might confuse implementers who expect a lower-is-better scheme. Consider clarifying or inverting that logic to avoid confusion.

…ecoy handling and add new methods for site identification

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

🧹 Nitpick comments (10)
src/topp/PhosphoScoring.cpp (1)

153-159: Consider simplifying the ppm check logic.

Here, the boolean for fragment_mass_unit_ppm is set by inverting the check on "Da". This works, but might be more intuitive to do a direct equality check for "ppm". In addition, confirm all upstream references align with the same logic.

- bool is_fragment_mass_unit_ppm = getStringOption_("fragment_mass_unit") == "Da" ? false : true;
+ bool is_fragment_mass_unit_ppm = (getStringOption_("fragment_mass_unit") == "ppm");
src/openms/include/OpenMS/ANALYSIS/ID/SimpleSearchEngineAlgorithm.h (1)

46-50: Public spectrum preprocessing API is well-structured.

Publishing this method enables greater reuse. Consider documenting potential side effects, such as whether it sorts spectra or modifies intensities, so callers understand how their data is transformed.

src/openms/source/ANALYSIS/ID/SimpleSearchEngineAlgorithm.cpp (1)

38-38: Redundant include check.

Including SimpleSearchEngineAlgorithm.h again here is not necessarily harmful, but it might be redundant if already included above. Ensure no cyclical dependencies are introduced.

src/openms/source/ANALYSIS/ID/AScore.cpp (5)

59-63: Comprehensive method documentation.

The explanation of computing AScore via “windowed peak picking + site permutations” is thorough. A pointer to relevant references or further reading in the docstring could be beneficial for new maintainers.


97-101: Metadata for decoy vs. non-decoy phospho events.

Storing metadata like regular_phospho_count and phospho_decoy_count is extremely helpful for downstream analysis. Consider also adding a combined “total_phospho_events” (though it can be derived).


153-159: Skip unneeded permutations logic.

Early returns when permutations are empty or exceed the limit help control performance. If a specialized fallback or heuristic is desired, consider documenting or implementing it, as hinted by the TODO.


773-806: Iterative bitmask approach is good for large combinations.

The fallback to an early termination if max_permutations_ is exceeded is prudent for performance. Possibly consider a user-configurable fallback strategy rather than a hard abort.


909-940: Peak picking per 100 Da windows is consistent with prior AScore logic.

Be mindful if the mass range extends significantly—for example, in top-down or large PTM analysis. Adapting window size might be needed.

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

561-571: Basic check for isPhosphoDecoySite.

Tests recognition of 'A' as decoy. Suggest adding tests for other documented decoy residues (G, L) if applicable.


962-1216: Extensive additional test cases.

All new tests are thorough and well-structured.

Please remove the redundant blank line around line 1092 per static analysis. For instance:

-    TEST_EQUAL(proforma, "PEPT[Phospho|score=1.0000]IDES[Phospho|score=1.0000]");

-
+    TEST_EQUAL(proforma, "PEPT[Phospho|score=1.0000]IDES[Phospho|score=1.0000]");
🧰 Tools
🪛 GitHub Check: CodeFactor

[notice] 1092-1092: src/tests/class_tests/openms/source/AScore_test.cpp#L1092
Redundant blank line at the end of a code block should be deleted. (whitespace/blank_line)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8dce4dc and 16ff0ee.

📒 Files selected for processing (6)
  • src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (4 hunks)
  • src/openms/include/OpenMS/ANALYSIS/ID/SimpleSearchEngineAlgorithm.h (2 hunks)
  • src/openms/source/ANALYSIS/ID/AScore.cpp (20 hunks)
  • src/openms/source/ANALYSIS/ID/SimpleSearchEngineAlgorithm.cpp (3 hunks)
  • src/tests/class_tests/openms/source/AScore_test.cpp (11 hunks)
  • src/topp/PhosphoScoring.cpp (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
src/openms/source/ANALYSIS/ID/AScore.cpp (1)
src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (21)
  • AScore (72-428)
  • AScore (81-81)
  • compute (105-105)
  • numberOfPhosphoEvents_ (323-323)
  • removePhosphositesFromSequence_ (333-333)
  • getSites_ (205-205)
  • generateProFormaString_ (399-399)
  • computePermutations_ (238-238)
  • computeBaseProbability_ (298-298)
  • calculatePermutationPeptideScores_ (375-375)
  • rankWeightedPermutationPeptideScores_ (386-386)
  • determineHighestScoringPermutations_ (286-286)
  • computeSiteDeterminingIons_ (194-194)
  • numberOfMatchedIons_ (251-251)
  • computeCumulativeScore_ (312-312)
  • isPhosphoDecoySite (108-108)
  • isPhosphoSite (111-111)
  • getPhosphoSites_ (215-215)
  • getPhosphoDecoySites_ (225-225)
  • createTheoreticalSpectra_ (347-347)
  • compareMZ_ (121-121)
🪛 GitHub Check: CodeFactor
src/tests/class_tests/openms/source/AScore_test.cpp

[notice] 1092-1092: src/tests/class_tests/openms/source/AScore_test.cpp#L1092
Redundant blank line at the end of a code block should be deleted. (whitespace/blank_line)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (windows-2022, cl.exe, default)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: cppcheck-test
🔇 Additional comments (49)
src/topp/PhosphoScoring.cpp (2)

14-14: Include usage is correct and necessary.

The newly added include for SimpleSearchEngineAlgorithm is appropriate given its usage in the subsequent code for spectrum preprocessing.


60-63: Good addition of decoy site analysis.

The explanatory comment regarding PhosphoDecoy site usage for FLR calculation is clear and helps users understand the add_decoys feature. Ensure documentation references remain up to date if more decoy residues are supported in the future.

src/openms/include/OpenMS/ANALYSIS/ID/SimpleSearchEngineAlgorithm.h (1)

9-10: Use of pragma once is appropriate.

Using #pragma once correctly prevents multiple inclusions and is more concise than traditional include guards.

src/openms/source/ANALYSIS/ID/SimpleSearchEngineAlgorithm.cpp (2)

173-218: Preprocessing function is coherent and well-structured.

  1. The filtering sequence (ThresholdMower → Normalizer → WindowMower → NLargest) is a clear pipeline for preparing spectra.
  2. Consider clarifying concurrency safety: All concurrency is done outside the function, so this method is safe as is.
  3. Review if parallel sorting is required or beneficial; for large data, concurrency might help, but synchronization overhead could also be high.

424-424: Appropriate call to static preprocessing.

Using preprocessSpectra at this point, after loading and sorting, is consistent with the typical pipeline. Double-check that the correct fragment tolerance and ppm flags are passed to maintain uniformity with the final scoring steps.

src/openms/source/ANALYSIS/ID/AScore.cpp (14)

13-13: Addition of MathFunctions include is valid.

You correctly added the needed header for advanced math operations, presumably binomial or log manipulations.


15-17: Useful new library includes for string formatting.

sstream and iomanip are helpful for generating ProForma output string with consistent numeric formatting.


23-29: Doxygen block clarity improvement.

Expanding the constructor’s doc to highlight default parameters is helpful. Confirm the parameter references (such as the enumerated bullet points) remain accurate if defaults change in the future.


47-49: Expose decoy support configuration.

The add_decoy parameter is a core addition. Ensure this is consistently documented in the class description and integrated into user-facing help so that advanced users know how to enable decoy support.


50-51: Defaults application.

Applying defaults to the parameter set in the constructor is best practice. This ensures subsequent parameter retrieval or updates start from a consistent basis.


53-57: Expanded doc clarifies algorithm steps.

The bullet list of the AScore logic is comprehensive. Good to see each step described. Bear in mind that if future refactoring modifies any step order, the docs must stay aligned.


65-73: Detailed events counting logic.

Separately counting regular vs. PhosphoDecoy events clarifies the breakdown in the final metadata. This also helps guard against accidental misinterpretation of decoy modifications.


78-88: Clear safety checks for empty spectra or decoy mismatch.

  1. Returning early on empty spectra avoids wasted calculations.
  2. Emitting a warning if decoy sites appear but add_decoys_ is off is a strong safeguard.

92-96: Efficient removal of phospho modifications.

The direct call to removePhosphositesFromSequence_ keeps the code clean. Double-check if any edge cases exist with partial modifications or unrecognized tokens in the sequence.

Would you like a quick script to scan for references to “(Phospho” or “(PhosphoDecoy” outside recognized patterns in the codebase?


604-617: Combined retrieval of phospho sites & decoy sites is logical.

Merging the results from getPhosphoSites_ and getPhosphoDecoySites_ ensures a single unified list. Sorting merges them in ascending order for further permutations.


664-687: Counting of both Phospho and PhosphoDecoy events is comprehensive.

The separate scans for (Phospho) and (PhosphoDecoy) are easy to follow. Confirm no overlap with any potential naming expansions (like "PhosphoSomethingElse") is planned downstream.


858-883: Branch conditions for decoys vs. standard phospho sites look correct.

  1. Logging clarifies which modification is set.
  2. Warnings for unexpected residues are beneficial.

1049-1115: ProForma string generation is thorough.

  1. The fallback probability approach ensures you avoid near-1.0 clustering.
  2. If the project moves to a widely accepted standard like ProForma v2, ensure backward compatibility or migration steps.

173-218:

Details

✅ Verification successful

Accurate tie-handling in best permutation selection.

Swapping if the original sequence is among multiple best-scoring permutations addresses potential reassignments. Verify that any newly introduced decoy permutations do not break this tie logic.


🏁 Script executed:

#!/bin/bash
# Searching for tie-breaking references in AScore logic beyond line 173 to ensure decoy permutations are handled properly:
rg -A 10 $'ranking.rbegin()'

Length of output: 7058


Tie-breaking logic for best permutation selection verified as correct.

The code correctly iterates over all top-scoring permutations and preferentially selects the one matching the original sequence when ties occur. The test cases in src/tests/class_tests/openms/source/AScore_test.cpp confirm this behavior, and no explicit decoy handling was found in the affected code. Should decoy permutations be introduced in the future, please ensure they are flagged or filtered appropriately so that they don’t interfere with the tie resolution logic.

src/tests/class_tests/openms/source/AScore_test.cpp (18)

12-13: Looks good.

These includes for TheoreticalSpectrumGenerator and DataArrays are necessary for the new tests.


34-36: No issues found.

This helper method correctly delegates to getPhosphoSites_.


38-40: No issues found.

Similarly, this helper method correctly delegates to getPhosphoDecoySites_.


89-95: Well-documented helper class.

The docstrings are clear, and the class name is descriptive.


96-205: Utility methods appear correct.

All methods (generateTheoreticalSpectrum, generatePeptideHit, createAmbiguousSpectrum) serve testing needs properly. The usage of string/int data arrays in createAmbiguousSpectrum is well-handled.


461-464: Test coverage increment recognized.

Checking for 8 site-determining ions is consistent with the new logic.


467-467: No issues here.

Additional check for the last ion’s m/z helps verify correctness.


476-477: Consistent test expectations.

Ensuring each site-determining spectrum has size 8 is valid.


481-481: Additional check of site-determining ions.

Still consistent with the updated logic.


573-603: Thorough tests for getSitesTest_.

Tests both regular phosphate sites and decoys under different parameter settings. Code looks correct.


606-633: Comprehensive coverage of getPhosphoSitesTest_.

Validates standard phosphorylation sites on S, T, Y. Nicely done.


635-650: Solid verification of getPhosphoDecoySitesTest_.

Ensures 'A' residues are detected as decoy sites.


710-713: Good test for removePhosphositesFromSequenceTest_.

Properly handles both Phospho and PhosphoDecoy.


794-796: Validation of b/y-ion m/z values.

No issues spotted.


817-817: Parameter update.

Correctly setting "add_decoy" to false.


895-896: Unambiguous assignment test.

Score is set to 1e6 for fully phosphorylated peptides. Straightforward.


898-929: PhosphoDecoy logic validated.

Ensures decoy count and metadata are properly set.


930-942: Mixed decoy and regular phosphorylation.

Correctly verifies both types of modifications in metadata.

src/openms/include/OpenMS/ANALYSIS/ID/AScore.h (12)

17-17: New include is appropriate.

Needed for the TheoreticalSpectrumGenerator usage.


27-43: Struct initialization and usage look fine.

Default-initialized fields are helpful to avoid uninitialized data.


50-68: Documentation enhancements.

Nicely explains expanded PhosphoDecoy concept.


81-81: Switch to default destructor is valid.

No concerns.


83-100: Compute method documentation is thorough.

Clear explanation of the approach.


107-112: Helpful new static methods.

However, the doc reference suggests decoy sites may also include 'G' or 'L'. Tests and logic only confirm 'A' so far. Recommend clarifying or extending the method, or updating docs if only 'A' is intended.


114-121: Fine-grained doc for compareMZ_.

No issues here.


123-132: Good approach for tolerant spectral difference.

Usage of compareMZ_ is consistent.


196-226: Phosphorylation site detection logic is clearly documented.

Inclusion of decoy sites is well-described.


288-299: Probability calculations well outlined.

No concerns regarding performance.


314-333: Removal of Phospho and PhosphoDecoy modifications.

Implementation strategy is sensible.


405-425: Parameter and member additions.

Documented usage of add_decoys_ references (A, G, L). Clarify if G, L are truly supported or remove from doc.

@OpenMS OpenMS deleted a comment from coderabbitai Bot Mar 26, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
src/openms/include/OpenMS/MATH/MathFunctions.h (1)

19-22: Prefer Boost binomial distribution header; drop unused special_functions/binomial.

Switching to boost::math::distributions::binomial enables using cdf/complement for a robust tail-probability implementation and removes the need for binomial_coefficient. See fix below (paired with the tail-CDF change).

-#include <boost/math/special_functions/binomial.hpp>
+#include <boost/math/distributions/binomial.hpp>
CHANGELOG (1)

110-112: Place entries under the correct release and add parameter names for clarity.

Confirm that PhosphoScoring “support PhosphoDecoy” and the iterative AScore change shipped in 3.4.0 (May 2025). If they target 3.5.0 (under development), move them accordingly and mention the exposed parameter (e.g., add_decoys) to aid users.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 16ff0ee and d6bf0c3.

📒 Files selected for processing (3)
  • CHANGELOG (2 hunks)
  • src/openms/include/OpenMS/ANALYSIS/ID/SimpleSearchEngineAlgorithm.h (2 hunks)
  • src/openms/include/OpenMS/MATH/MathFunctions.h (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/openms/include/OpenMS/ANALYSIS/ID/SimpleSearchEngineAlgorithm.h
🧰 Additional context used
📓 Path-based instructions (2)
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/MATH/MathFunctions.h
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/MATH/MathFunctions.h
🧠 Learnings (1)
📚 Learning: 2025-08-14T10:19:54.371Z
Learnt from: jpfeuffer
PR: OpenMS/OpenMS#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/MATH/MathFunctions.h
⏰ 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). (6)
  • GitHub Check: cppcheck-test
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)

Comment on lines +505 to +534
/**
* @brief Calculate logarithm of binomial coefficient C(n,k) using log-gamma function
*
* @param n Total number of items
* @param k Number of items to choose
* @return Natural logarithm of binomial coefficient C(n,k)
* @throws std::invalid_argument if k > n
*/
inline double log_binomial_coef(unsigned n, unsigned k)
{
// Handle edge cases for improved numerical stability
if (k > n)
{
throw std::invalid_argument("k cannot be greater than n in binomial coefficient");
}

if (k == 0 || k == n)
{
return 0.0; // log(1) = 0
}

// Use symmetry to minimize computation for large k
if (k > n / 2)
{
k = n - k;
}

return boost::math::lgamma(n + 1.0) - boost::math::lgamma(k + 1.0) - boost::math::lgamma(n - k + 1.0);
}

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.

🛠️ Refactor suggestion

🧩 Analysis chain

Align error handling with OpenMS and adopt camelCase naming.

Use OpenMS::Exception::InvalidValue (consistent with percentOf) and camelCase (consistent with the rest of Math). Function body is fine.

-  inline double log_binomial_coef(unsigned n, unsigned k) 
+  inline double logBinomialCoef(unsigned n, unsigned k) 
   {
     // Handle edge cases for improved numerical stability
     if (k > n) 
     {
-      throw std::invalid_argument("k cannot be greater than n in binomial coefficient");
+      throw Exception::InvalidValue(
+        __FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
+        "k cannot be greater than n in binomial coefficient",
+        String(k) + " > " + String(n));
     }
@@
-    return boost::math::lgamma(n + 1.0) - boost::math::lgamma(k + 1.0) - boost::math::lgamma(n - k + 1.0);
+    return boost::math::lgamma(n + 1.0)
+         - boost::math::lgamma(k + 1.0)
+         - boost::math::lgamma(n - k + 1.0);
   }

Run to find and update all call sites to the new name:


🏁 Script executed:

#!/bin/bash
rg -nP --type=cpp '\blog_binomial_coef\s*\(' -C2

Length of output: 2669


Rename log_binomial_coef → logBinomialCoef and use OpenMS Exception::InvalidValue

Function body is fine; rename to camelCase, change the thrown exception and Doxygen, and update all call sites.

  • In src/openms/include/OpenMS/MATH/MathFunctions.h (doc @throws at ~line 511; definition at ~line 513): rename function to logBinomialCoef(unsigned n, unsigned k) and change the throw to:
    throw Exception::InvalidValue(FILE, LINE, OPENMS_PRETTY_FUNCTION,
    "k cannot be greater than n in binomial coefficient",
    String(k) + " > " + String(n));
    also update the @throws line to reference Exception::InvalidValue.
  • Update the internal usage in the same file (line ~605): replace log_binomial_coef(N, k) → logBinomialCoef(N, k).
  • Update tests in src/tests/class_tests/openms/source/MathFunctions_test.cpp (around lines 194–209): replace Math::log_binomial_coef(...) → Math::logBinomialCoef(...), and change TEST_EXCEPTION(std::invalid_argument, ...) → TEST_EXCEPTION(Exception::InvalidValue, ...).
🤖 Prompt for AI Agents
In src/openms/include/OpenMS/MATH/MathFunctions.h around lines 505–534, rename
function log_binomial_coef(unsigned n, unsigned k) to logBinomialCoef(unsigned
n, unsigned k), update the Doxygen @throws to reference Exception::InvalidValue,
and replace the throw std::invalid_argument(...) with throw
Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "k cannot be
greater than n in binomial coefficient", String(k) + " > " + String(n));; also
update the internal call in this header (~line 605) to use logBinomialCoef(N, k)
and change all other call sites (including tests in
src/tests/class_tests/openms/source/MathFunctions_test.cpp around lines 194–209)
to use Math::logBinomialCoef(...) and replace
TEST_EXCEPTION(std::invalid_argument, ...) with
TEST_EXCEPTION(Exception::InvalidValue, ...).

Comment on lines +535 to +552
/**
* @brief Log-sum-exp operation for numerical stability
*
* @param x First logarithmic value
* @param y Second logarithmic value
* @return Natural logarithm of (exp(x) + exp(y))
*/
inline double log_sum_exp(double x, double y)
{
// Handle infinite cases
if (std::isinf(x) && x < 0) return y;
if (std::isinf(y) && y < 0) return x;

// Use the maximum value for numerical stability
double max_val = std::max(x, y);
return max_val + std::log(std::exp(x - max_val) + std::exp(y - max_val));
}

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.

🛠️ Refactor suggestion

🧩 Analysis chain

Make log-sum-exp more stable and match naming.

Use log1p on the smaller term and adopt camelCase. Keeps the -inf fast paths.

-  inline double log_sum_exp(double x, double y) 
+  inline double logSumExp(double x, double y) 
   {
     // Handle infinite cases
     if (std::isinf(x) && x < 0) return y;
     if (std::isinf(y) && y < 0) return x;
     
     // Use the maximum value for numerical stability
-    double max_val = std::max(x, y);
-    return max_val + std::log(std::exp(x - max_val) + std::exp(y - max_val));
+    const double max_val = std::max(x, y);
+    const double min_val = std::min(x, y);
+    // max_val + log1p(exp(min - max)) is more stable if x≈y
+    return max_val + std::log1p(std::exp(min_val - max_val));
   }

Update internal references to the new name:


🏁 Script executed:

#!/bin/bash
rg -nP --type=cpp '\blog_sum_exp\s*\(' -C2

Length of output: 2589


Use log1p for numerical stability; update callers if you rename the symbol

Replace the implementation with the log1p variant (keep the -inf fast paths):
const double max_val = std::max(x,y);
const double min_val = std::min(x,y);
return max_val + std::log1p(std::exp(min_val - max_val));

If you also rename to logSumExp, update callers found at:

  • src/openms/include/OpenMS/MATH/MathFunctions.h (definition ~line 542; usage ~line 606)
  • src/tests/class_tests/openms/source/MathFunctions_test.cpp (calls near lines 215, 216, 219, 224)

Alternative: keep the public name log_sum_exp and only change the implementation, or add a thin inline wrapper from log_sum_exp -> logSumExp to avoid breaking API.

🤖 Prompt for AI Agents
In src/openms/include/OpenMS/MATH/MathFunctions.h around lines 535 to 552, the
current log_sum_exp implementation should be changed to use log1p for better
numerical stability while keeping the existing -inf fast paths; replace the
final computation with max_val + std::log1p(std::exp(min_val - max_val)) where
min_val = std::min(x,y) and max_val = std::max(x,y). If you choose to rename the
function to logSumExp, update all callers listed in the review (the definition
~line 542 and usage ~line 606 in this header and tests in
src/tests/class_tests/openms/source/MathFunctions_test.cpp near the indicated
lines) or alternatively keep the public name log_sum_exp and only change the
implementation or add a thin inline wrapper from log_sum_exp -> logSumExp to
avoid breaking API.

Comment on lines +553 to +612
/**
* @brief Calculate binomial cumulative distribution function P(X ≥ n)
*
* Calculates P(X ≥ n) for a binomial distribution with parameters N and p,
* using numerically stable algorithms in the log domain to handle large values.
*
* @param N Total number of trials
* @param n Minimum number of successes
* @param p Probability of success in each trial
* @return Probability P(X ≥ n) for binomial distribution B(N,p)
* @throws std::invalid_argument if parameters are invalid
*/
inline double binomial_cdf_complement(unsigned N, unsigned n, double p)
{
// Input validation
if (p < 0.0 || p > 1.0)
{
throw std::invalid_argument("Probability p must be between 0 and 1");
}

if (n > N)
{
throw std::invalid_argument("n cannot be greater than N");
}

// Edge cases for improved performance
if (n == 0) return 1.0; // P(X ≥ 0) = 1
if (p == 0.0) return (n == 0) ? 1.0 : 0.0;
if (p == 1.0) return 1.0;

// Handle numerical stability for extreme values
if (n == N && N > 1000 && p < 1e-6)
{
return std::pow(p, N); // Approximation for extreme case
}

// For more efficient computation when p is large
if (p > 0.5)
{
return 1.0 - binomial_cdf_complement(N, 0, 1.0 - p) +
boost::math::binomial_coefficient<double>(N, n - 1) *
std::pow(p, n - 1) * std::pow(1.0 - p, N - n + 1);
}

// Compute in log domain for numerical stability
double log_p = std::log(p);
double log_1_minus_p = boost::math::log1p(-p); // Numerically stable log(1-p)
double log_score = -std::numeric_limits<double>::infinity();

// Sum terms efficiently in log domain
for (unsigned k = n; k <= N; ++k)
{
double log_term = log_binomial_coef(N, k) + k * log_p + (N - k) * log_1_minus_p;
log_score = log_sum_exp(log_score, log_term);
}

// Convert back to probability domain with bounds check
double result = std::exp(log_score);
return std::min(1.0, std::max(0.0, result)); // Ensure result is in [0,1]
}

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.

⚠️ Potential issue

🧩 Analysis chain

Critical: wrong formula for p > 0.5 in binomial tail; replace with Boost CDF complement.

The branch for p > 0.5 currently reduces P(X ≥ n) to P(X = n-1), which is incorrect. Replace the whole implementation with Boost’s binomial CDF complement. Also align naming and exceptions.

-  inline double binomial_cdf_complement(unsigned N, unsigned n, double p) 
+  inline double binomialCDFComplement(unsigned N, unsigned n, double p) 
   {
-    // Input validation
-    if (p < 0.0 || p > 1.0) 
-    {
-      throw std::invalid_argument("Probability p must be between 0 and 1");
-    }
-    
-    if (n > N) 
-    {
-      throw std::invalid_argument("n cannot be greater than N");
-    }
-    
-    // Edge cases for improved performance
-    if (n == 0) return 1.0;  // P(X ≥ 0) = 1
-    if (p == 0.0) return (n == 0) ? 1.0 : 0.0;
-    if (p == 1.0) return 1.0;
-    
-    // Handle numerical stability for extreme values
-    if (n == N && N > 1000 && p < 1e-6) 
-    {
-      return std::pow(p, N);  // Approximation for extreme case
-    }
-    
-    // For more efficient computation when p is large
-    if (p > 0.5) 
-    {
-      return 1.0 - binomial_cdf_complement(N, 0, 1.0 - p) + 
-             boost::math::binomial_coefficient<double>(N, n - 1) * 
-             std::pow(p, n - 1) * std::pow(1.0 - p, N - n + 1);
-    }
-    
-    // Compute in log domain for numerical stability
-    double log_p = std::log(p);
-    double log_1_minus_p = boost::math::log1p(-p);  // Numerically stable log(1-p)
-    double log_score = -std::numeric_limits<double>::infinity();
-    
-    // Sum terms efficiently in log domain
-    for (unsigned k = n; k <= N; ++k) 
-    {
-      double log_term = log_binomial_coef(N, k) + k * log_p + (N - k) * log_1_minus_p;
-      log_score = log_sum_exp(log_score, log_term);
-    }
-    
-    // Convert back to probability domain with bounds check
-    double result = std::exp(log_score);
-    return std::min(1.0, std::max(0.0, result));  // Ensure result is in [0,1]
+    if (p < 0.0 || p > 1.0)
+    {
+      throw Exception::InvalidValue(
+        __FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
+        "Probability p must be within [0,1]", String(p));
+    }
+    if (n > N)
+    {
+      throw Exception::InvalidValue(
+        __FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
+        "n cannot be greater than N", String(n) + " > " + String(N));
+    }
+    if (n == 0) return 1.0; // P(X ≥ 0) = 1
+
+    // Robust tail via Boost distributions: P(X ≥ n) = 1 - P(X ≤ n-1)
+    const boost::math::binomial_distribution<double> dist(N, p);
+    const double result = boost::math::cdf(boost::math::complement(dist, static_cast<unsigned>(n - 1)));
+    return std::min(1.0, std::max(0.0, result));
   }

Update all references and includes:


🏁 Script executed:

#!/bin/bash
# Find old name usages
rg -nP --type=cpp '\bbinomial_cdf_complement\s*\(' -C2
# Ensure the distributions header is present and special_functions/binomial removed
rg -nP --type=cpp 'distributions/binomial\.hpp|special_functions/binomial\.hpp' -C1

Length of output: 6319


Critical: p>0.5 branch is wrong — it returns the PMF at n-1 instead of the tail; replace with Boost CDF complement (keep name & std::invalid_argument).

  • Bug: the branch in src/openms/include/OpenMS/MATH/MathFunctions.h (≈lines 590–594) simplifies to C(N,n-1)p^(n-1)(1-p)^(N-n+1) — i.e. P(X==n-1), not P(X≥n).
  • Fix: compute the tail with Boost distributions: create boost::math::binomial_distribution dist(N,p) and return boost::math::cdf(boost::math::complement(dist, static_cast(n-1))) (clamp to [0,1]). Add #include <boost/math/distributions/binomial.hpp> to MathFunctions.h.
  • Do not rename the function or switch the exception type in this PR: callers/tests expect Math::binomial_cdf_complement and std::invalid_argument (see src/tests/class_tests/openms/source/MathFunctions_test.cpp and src/openms/source/ANALYSIS/ID/AScore.cpp:361). If you want to change name/exception type, update all callers/tests in a separate change.
  • Do not remove boost/math/special_functions/binomial.hpp globally — it’s used elsewhere (multiple files in the repo).
🤖 Prompt for AI Agents
In src/openms/include/OpenMS/MATH/MathFunctions.h around lines 553 to 612, the
p>0.5 branch returns a single PMF term (P(X==n-1)) instead of the tail
probability P(X≥n); replace that branch by constructing a
boost::math::binomial_distribution<double> dist(N,p) and return
boost::math::cdf(boost::math::complement(dist, static_cast<unsigned>(n-1)))
(then clamp the result to [0,1]); also add #include
<boost/math/distributions/binomial.hpp> at the top of the file; keep the
function name and std::invalid_argument behavior unchanged and do not remove the
existing special_functions/binomial include elsewhere.

Copilot AI 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.

Pull Request Overview

This PR implements support for PhosphoDecoy modifications in the AScore algorithm for phosphorylation site localization analysis. PhosphoDecoy sites use Alanine (A) residues as decoy phosphorylation sites to enable false localization rate (FLR) calculations. The implementation also includes a rewritten AScore algorithm with improved numerical stability and performance.

Key changes:

  • Added PhosphoDecoy support to AScore with configurable add_decoy parameter
  • Rewrote AScore algorithm with non-recursive permutation generation and numerically stable binomial calculations
  • Enhanced PhosphoScoring tool to use spectrum preprocessing from SimpleSearchEngineAlgorithm

Reviewed Changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/topp/PhosphoScoring.cpp Integrated SimpleSearchEngineAlgorithm preprocessing and added PhosphoDecoy documentation
src/openms/source/ANALYSIS/ID/AScore.cpp Major rewrite with PhosphoDecoy support, improved algorithms, and ProForma output
src/openms/include/OpenMS/ANALYSIS/ID/AScore.h Updated header with new methods, better documentation, and PhosphoDecoy support
src/openms/source/ANALYSIS/ID/SimpleSearchEngineAlgorithm.cpp Made preprocessSpectra method public for reuse
src/openms/include/OpenMS/ANALYSIS/ID/SimpleSearchEngineAlgorithm.h Exposed preprocessSpectra as public API
src/openms/include/OpenMS/MATH/MathFunctions.h Added numerically stable math functions for binomial calculations
src/tests/class_tests/openms/source/AScore_test.cpp Comprehensive test suite with PhosphoDecoy tests and theoretical spectrum generation
src/tests/class_tests/openms/source/MathFunctions_test.cpp Tests for new mathematical functions
src/pyOpenMS/pxds/AScore.pxd Removed unused AScore field from struct
CHANGELOG Documentation of changes
Comments suppressed due to low confidence (1)

src/openms/source/ANALYSIS/ID/AScore.cpp:1

  • Inconsistent variable naming: 'tupel_with_decoy' uses the misspelled 'tupel' instead of 'tuple'. For consistency and correctness, consider renaming to 'sites_with_decoy'.
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin

Comment thread src/topp/PhosphoScoring.cpp Resolved
Comment on lines +736 to +742
{
estimated_permutations = boost::math::binomial_coefficient<double>((unsigned int)sites.size(), (unsigned int)n_phosphorylation_events);
}
catch (std::exception const& /*e*/) // Catch any exception, not just overflow
{
estimated_permutations = std::numeric_limits<double>::max();
}

Copilot AI Sep 18, 2025

Copy link

Choose a reason for hiding this comment

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

Using boost::math::binomial_coefficient in a tight loop for estimation when you already have a log_binomial_coef function available. Consider using exp(log_binomial_coef()) for consistency and to avoid potential differences in overflow handling between the two implementations.

Copilot uses AI. Check for mistakes.
Comment on lines +589 to +594
// For more efficient computation when p is large
if (p > 0.5)
{
return 1.0 - binomial_cdf_complement(N, 0, 1.0 - p) +
boost::math::binomial_coefficient<double>(N, n - 1) *
std::pow(p, n - 1) * std::pow(1.0 - p, N - n + 1);

Copilot AI Sep 18, 2025

Copy link

Choose a reason for hiding this comment

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

This optimization for p > 0.5 appears to have an incorrect formula. The recursive call uses n=0 instead of the complement calculation, and the correction term seems mathematically incorrect for computing P(X ≥ n). This could lead to incorrect probability calculations when p > 0.5.

Suggested change
// For more efficient computation when p is large
if (p > 0.5)
{
return 1.0 - binomial_cdf_complement(N, 0, 1.0 - p) +
boost::math::binomial_coefficient<double>(N, n - 1) *
std::pow(p, n - 1) * std::pow(1.0 - p, N - n + 1);
// For more efficient computation when p is large, use complement: P(X ≥ n) = 1 - P(X ≤ n-1)
if (p > 0.5)
{
return 1.0 - binomial_cdf(N, n - 1, p);

Copilot uses AI. Check for mistakes.
Comment on lines +576 to +578
String unmodified_sequence = phospho.toUnmodifiedString();
vector<Size> tupel(ptr_test->getSitesTest_(unmodified_sequence));
TEST_EQUAL(4, tupel.size())
TEST_EQUAL(4, tupel.size()) // vTqSpSSp

Copilot AI Sep 18, 2025

Copy link

Choose a reason for hiding this comment

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

The variable name 'tupel' is a misspelling of 'tuple'. Consider renaming to 'sites' or 'phospho_sites' for better readability and correctness.

Copilot uses AI. Check for mistakes.
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

close because we do a broader implementation of rescoring algorithms in pyOpenMS. Including proper benchmarking and comparison to existing tools

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.

3 participants