Skip to content

MTD refactor - #8149

Merged
timosachsenberg merged 51 commits into
developfrom
feature/mtd_refactor
Aug 5, 2025
Merged

timosachsenberg merged 51 commits into
developfrom
feature/mtd_refactor

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Aug 5, 2025 •

Copy link
Copy Markdown
Contributor

Factored out into helper functions. No change in logic.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added experimental support for Bruker Ion Mobility data in MassTraceExtractor (requires ion mobility peak-picked data).
  • Bug Fixes

    • Minor punctuation correction in the Library section of the changelog.
  • Refactor

    • Enhanced mass trace detection with improved peak selection and trace extension strategies.
    • Modularized detection logic for better maintainability and robustness.
    • Unified trace termination and validation criteria, including ion mobility data handling.

Mohammed AlHigaylan and others added 30 commits April 9, 2025 12:32
…1 traces annotated with fwhm_mz_avg. Now all traces are annotated
@coderabbitai

coderabbitai Bot commented Aug 5, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The mass trace detection algorithm was refactored and enhanced to modularize peak finding, selection, and trace extension logic. New internal data structures and helper methods were introduced, and the main extension loop was rewritten for clarity and consistency. Documentation and changelog entries were updated to reflect these changes.

Changes

Cohort / File(s) Change Summary
Changelog and Documentation
CHANGELOG
Updated with a new experimental feature for Bruker Ion Mobility support in MassTraceExtractor and a minor punctuation fix in the Library section.
Header: MassTraceDetection Internal Structures & Methods
src/openms/include/OpenMS/FEATUREFINDER/MassTraceDetection.h
Introduced new enum TraceTerminationCriterion, structs (PeakCandidate, TraceExtensionState), and private methods for peak finding, acceptance, processing, and trace validation. Changed trace_termination_criterion_ member from string to enum. Added mutable member variables for metadata array indices. Included Boost dynamic bitset for peak visitation tracking.
Source: MassTraceDetection Algorithm Refactor
src/openms/source/FEATUREFINDER/MassTraceDetection.cpp
Refactored mass trace detection logic by removing deprecated helper functions and introducing new modular private methods (findBestPeak_, isPeakAcceptable_, processPeak_, isTraceValid_). Rewrote main trace extension loop using TraceExtensionState struct for state tracking. Unified termination and validation criteria based on enum. Improved metadata handling and parameter parsing with error checking. Added validation for consistent presence of metadata arrays across spectra.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MassTraceDetection
    participant Spectrum
    participant Trace

    User->>MassTraceDetection: run_()
    loop For each apex
        MassTraceDetection->>Spectrum: Access spectrum data
        MassTraceDetection->>MassTraceDetection: findBestPeak_()
        alt Peak found and isPeakAcceptable_()
            MassTraceDetection->>Trace: processPeak_()
            MassTraceDetection->>MassTraceDetection: Update centroid, intensity, FWHM, etc.
        else No acceptable peak
            MassTraceDetection->>MassTraceDetection: Increment miss counter
        end
        MassTraceDetection->>MassTraceDetection: Check extension/termination criteria
    end
    MassTraceDetection->>MassTraceDetection: isTraceValid_()
    alt Valid trace
        MassTraceDetection->>User: Add to result
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35 minutes

Poem

A bunny hopped through peaks and scans,
Refactoring code with gentle hands.
New structs and helpers, all in a row,
Modular logic, algorithms in flow.
Ion mobility now joins the chase—
What a hoppy improvement for MassTrace!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ 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/mtd_refactor

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@timosachsenberg timosachsenberg changed the title Feature/mtd refactor MTD refactor Aug 5, 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: 2

🧹 Nitpick comments (1)
src/openms/source/FEATUREFINDER/MassTraceDetection.cpp (1)

458-508: Good initialization updates for ion mobility support.

The changes properly initialize:

  • Metadata array detection via getIMIndices_
  • Ion mobility centroid tracking when available
  • FWHM metadata collection

However, the same concern about direct array access applies here.

Consider using getIMData() method for consistency with OpenMS best practices when accessing ion mobility data at lines 497 and 500-501.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2a8164a and b2046d7.

📒 Files selected for processing (3)
  • CHANGELOG (2 hunks)
  • src/openms/include/OpenMS/FEATUREFINDER/MassTraceDetection.h (4 hunks)
  • src/openms/source/FEATUREFINDER/MassTraceDetection.cpp (6 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: jpfeuffer
PR: OpenMS/OpenMS#7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.
Learnt from: jpfeuffer
PR: OpenMS/OpenMS#7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.
📚 Learning: ms:1000893 in psi-ms controlled vocabulary refers to "peptide group label", not "peptidoform group l...
Learnt from: poshul
PR: OpenMS/OpenMS#8133
File: src/tests/class_tests/openms/data/MRMAssay_uisTransitions_output_4_boost58.TraML:30-30
Timestamp: 2025-07-29T10:06:14.860Z
Learning: MS:1000893 in PSI-MS controlled vocabulary refers to "peptide group label", not "peptidoform group label". There is no official PSI-MS CV term for "peptidoform group label" with accession MS:1003050 as I incorrectly claimed.

Applied to files:

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

Applied to files:

  • src/openms/source/FEATUREFINDER/MassTraceDetection.cpp
  • src/openms/include/OpenMS/FEATUREFINDER/MassTraceDetection.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: 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: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: cppcheck-test
🔇 Additional comments (11)
CHANGELOG (1)

45-45: LGTM! Good punctuation fix.

Adding the period properly completes the sentence and maintains consistency with other changelog entries.

src/openms/source/FEATUREFINDER/MassTraceDetection.cpp (7)

88-90: LGTM! Proper use of constants for metadata array names.

The code correctly uses the new constant names for ion mobility and FWHM metadata arrays, which aligns with the PR's objective of adding ion mobility support.


110-139: Excellent validation logic for metadata consistency.

The lambda function approach for validating metadata arrays is clean and reusable. The validation ensures data integrity by checking that:

  1. Arrays are consistently present/absent across all spectra
  2. Array sizes match spectrum sizes
  3. Clear exception messages are provided for debugging

This is crucial for reliable ion mobility data processing.


322-359: Well-structured peak validation logic.

The method properly validates peak candidates against:

  • m/z tolerance window (±3 standard deviations)
  • Ion mobility tolerance window (when available)
  • Previous usage in other traces

The logic is clear and correctly implements the acceptance criteria.


361-419: Comprehensive peak processing implementation.

The method effectively handles all aspects of peak processing:

  • Correctly adds peaks to trace based on extension direction
  • Updates centroids using intensity-weighted averaging
  • Collects FWHM metadata for quality assessment
  • Implements dynamic m/z tolerance adjustment when enabled

The implementation is thorough and well-structured.


422-446: Clean trace validation implementation.

The method properly validates traces based on:

  • Minimum length requirement
  • Optional maximum length constraint
  • Quality metric (sample rate) with appropriate adjustments for terminal missed scans

The logic is clear and correctly implements the validation criteria.


510-625: Excellent refactoring of the trace extension loop.

The refactored implementation provides significant improvements:

  • Clean state management using TraceExtensionState struct
  • Clear separation of concerns with helper methods
  • Proper handling of empty spectra (they don't affect termination counters)
  • Well-implemented termination criteria for both "outlier" and "sample_rate" modes
  • Improved readability and maintainability

This modular approach makes the code much easier to understand and maintain.


630-645: Clean trace finalization with proper metadata handling.

The implementation correctly:

  • Uses the new isTraceValid_ helper for validation
  • Calculates median FWHM values (appropriate summary statistic)
  • Sets ion mobility centroid when available
  • Maintains all existing trace properties

Good separation of concerns and proper handling of optional metadata.

src/openms/include/OpenMS/FEATUREFINDER/MassTraceDetection.h (3)

17-118: Well-designed data structures for the refactored algorithm.

The new structs provide excellent encapsulation:

  • PeakCandidate: Cleanly represents peak search results with all necessary attributes
  • TraceExtensionState: Effectively manages trace extension state in a single structure

Both have proper default constructors with sensible initial values. The boost dynamic_bitset include is appropriate for efficient peak visitation tracking.


134-173: Clear and well-structured method declarations.

The new private methods are well-designed:

  • findBestPeak_: Focused on peak finding with optional ion mobility
  • isPeakAcceptable_: Clear validation logic separation
  • processPeak_: Handles all peak processing in one place
  • isTraceValid_: Encapsulates trace validation criteria

All methods have appropriate const-correctness and clear documentation.


195-198: Consider thread safety implications of mutable members.

While the mutable metadata indices are useful for caching array positions, they could cause issues in multi-threaded scenarios if the same MassTraceDetection instance is used concurrently.

Are there any multi-threading use cases for MassTraceDetection? If so, consider either:

  1. Making these non-mutable and passing them as parameters
  2. Adding thread synchronization
  3. Documenting that instances are not thread-safe

Comment thread CHANGELOG Resolved
timosachsenberg and others added 4 commits August 5, 2025 11:35
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

@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

♻️ Duplicate comments (2)
src/openms/source/FEATUREFINDER/MassTraceDetection.cpp (2)

266-321: Ion mobility access still uses direct FloatDataArrays indexing.

This code segment continues to use the pattern flagged in previous reviews. According to OpenMS best practices, you should use the getIMData() method instead of directly accessing spectrum.getFloatDataArrays()[ion_mobility_idx_].

Consider refactoring to use the recommended API:

-double im_value = spectrum.getFloatDataArrays()[ion_mobility_idx_][i];
+auto [im_position, im_unit] = spectrum.getIMData();
+double im_value = spectrum.getFloatDataArrays()[im_position][i];

498-503: Ion mobility access pattern needs updating.

Similar to the earlier comment, this code uses direct FloatDataArrays access instead of the recommended getIMData() method.

🧹 Nitpick comments (2)
src/openms/source/FEATUREFINDER/MassTraceDetection.cpp (2)

490-490: Unnecessary redundant call to updateIterativeWeightedMean_.

Line 490 calls updateIterativeWeightedMean_ immediately after the centroid initialization, but the centroid values were already set correctly during initialization. This redundant call doesn't change the values but adds unnecessary computation.

Remove the redundant call:

-updateIterativeWeightedMean_(apex_peak.getMZ(), apex_peak.getIntensity(), centroid_mz, prev_counter, prev_denom);

508-509: FWHM data access uses direct indexing.

While not ion mobility data, these lines also use direct FloatDataArrays access. Consider if there are equivalent helper methods available for FWHM data access to maintain consistency.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4548417 and 8360174.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/FEATUREFINDER/MassTraceDetection.h (5 hunks)
  • src/openms/source/FEATUREFINDER/MassTraceDetection.cpp (8 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: in openms, the proper way to access ion mobility data in msspectrum is to use the `getimdata()` meth...
Learnt from: jpfeuffer
PR: OpenMS/OpenMS#7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.

Applied to files:

  • src/openms/source/FEATUREFINDER/MassTraceDetection.cpp
  • src/openms/include/OpenMS/FEATUREFINDER/MassTraceDetection.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). (5)
  • 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 (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
🔇 Additional comments (18)
src/openms/source/FEATUREFINDER/MassTraceDetection.cpp (12)

18-18: LGTM: Exception handling import added.

Good addition for improved error handling in parameter validation.


89-90: Improved variable naming for clarity.

The renaming from ambiguous indices to more descriptive ion_mobility_idx_ and im_fwhm_idx_ improves code readability.


111-140: Excellent validation logic for metadata consistency.

The new validation ensures metadata arrays are consistently present across all spectra, preventing runtime errors from inconsistent data. The exception messages are clear and informative.


323-360: Well-structured peak acceptance validation.

The isPeakAcceptable_ method properly encapsulates all validation logic including m/z tolerance, ion mobility tolerance, and peak visitation checks. The logic is clear and comprehensive.


362-420: Comprehensive peak processing encapsulation.

The processPeak_ method effectively consolidates peak processing logic, handling both LC-MS and LC-IMS-MS data paths. The intensity-weighted centroid updates and FWHM collection are properly implemented.


423-447: Clean trace validation logic.

The isTraceValid_ method nicely encapsulates trace quality assessment with clear length and sample rate criteria. The adjusted scan calculation properly accounts for consecutive misses.


459-463: Improved variable naming consistency.

The parameter renaming to fwhm_meta_idx_, ion_mobility_idx_, and im_fwhm_idx_ provides better clarity and consistency throughout the codebase.


511-513: Clean state management with TraceExtensionState.

The introduction of TraceExtensionState struct significantly improves code organization by consolidating multiple counters and flags into coherent state objects.


518-625: Excellent refactoring of trace extension logic.

The main extension loop is much cleaner now with the helper methods. The consistent application of termination criteria and state management makes the code more maintainable and easier to understand.


631-632: Simplified trace validation call.

The refactored validation using isTraceValid_ method is much cleaner and easier to understand than the previous inline checks.


644-645: Clean FWHM median calculation.

The conditional FWHM averaging logic is well-structured and handles the case when FWHM data is not available.


674-686: Robust parameter validation with enum mapping.

The new parameter parsing logic with enum mapping and exception handling for invalid values is a significant improvement over string-based comparisons. This prevents runtime errors from configuration mistakes.

src/openms/include/OpenMS/FEATUREFINDER/MassTraceDetection.h (6)

17-17: Appropriate include for boost::dynamic_bitset.

The include is correctly added to support the bitset usage in the implementation.


53-58: Well-designed enum for trace termination criteria.

The TraceTerminationCriterion enum provides better type safety and performance compared to string-based comparisons. The documentation is clear and descriptive.


104-125: Well-structured helper structs for data organization.

Both PeakCandidate and TraceExtensionState structs are well-designed with appropriate default constructors. They effectively encapsulate related data and improve code organization.


141-179: Comprehensive method declarations for modularization.

The new private methods are well-documented and provide clear separation of concerns. The parameter lists are appropriate for their respective functionalities.


194-194: Type-safe parameter with enum.

Replacing the string-based parameter with the enum type improves type safety and prevents invalid configuration values.


202-205: Mutable metadata indices for lazy initialization.

The mutable metadata index members allow for lazy initialization during the run methods, which is a reasonable design choice for this use case.

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