Skip to content

Simplify IDFilter by eliminating code duplication - #8662

Merged
timosachsenberg merged 2 commits into
developfrom
feature/idfilter-kiss-simplification
Jan 15, 2026
Merged

timosachsenberg merged 2 commits into
developfrom
feature/idfilter-kiss-simplification

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jan 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Unify HasMatchingAccession and HasMatchingAccessionUnordered predicates into a single template HasMatchingAccessionImpl with type aliases for backward API compatibility
  • Extract duplicated accession collection logic into helper functions (collectReferencedAccessions, collectProteinAccessions)
  • Extract duplicated evidence filtering into filterPeptideReferences helper
  • Simplify removeUnreferencedProteins and removeDanglingProteinReferences overloads using the new helpers

Net reduction of ~65 lines while preserving the public API.

Test plan

  • Unit tests pass (IDFilter_test)
  • TOPP integration tests pass (23 TOPP_IDFilter_* tests)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Refactor
    • Improved internal code organization in the identification filtering module to reduce duplication and enhance maintainability. Consolidated filtering logic into centralized helper functions, allowing for more flexible handling of protein accession matching across different container types.

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

Apply KISS principle to reduce redundancy in IDFilter class:

- Unify HasMatchingAccession and HasMatchingAccessionUnordered into a
  single template HasMatchingAccessionImpl with type aliases for
  backward API compatibility
- Extract duplicated accession collection logic into helper functions
  (collectReferencedAccessions, collectProteinAccessions)
- Extract duplicated evidence filtering into filterPeptideReferences
- Simplify removeUnreferencedProteins and removeDanglingProteinReferences
  overloads using the new helpers

Net reduction of ~65 lines while preserving the public API.

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

coderabbitai Bot commented Jan 15, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The pull request refactors the IDFilter module by introducing a generic template HasMatchingAccessionImpl to replace hard-coded set implementations, and consolidates duplicate protein/peptide filtering logic into centralized helper functions within an anonymous namespace in the implementation file.

Changes

Cohort / File(s) Summary
Template Refactoring
src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h
Introduced generic HasMatchingAccessionImpl<HitType, SetType> template replacing hard-coded unordered/set implementations. Created two type aliases (HasMatchingAccessionUnordered and HasMatchingAccession) to maintain backward compatibility while enabling container-agnostic predicate usage.
Helper Function Consolidation
src/openms/source/PROCESSING/ID/IDFilter.cpp
Added anonymous namespace with helper functions (collectReferencedAccessions, collectProteinAccessions, filterEvidencesByAccessions, filterPeptideReferences) to centralize repeated filtering and collection logic. Updated call sites in protein/peptide reference filtering methods to use new helpers, reducing code duplication across removeUnreferencedProteins, removeDanglingProteinReferences, and related functions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • singjc
  • jcharkow

Poem

🐰 A template so generic, containers beware,
Accessions now flexible, refactored with care,
Helper functions gather, duplication's no friend,
With clarity and purpose, the code's at its end. 🌟

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Simplify IDFilter by eliminating code duplication' accurately describes the main objective of the PR, which focuses on reducing code duplication through template refactoring and helper function extraction.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

🧹 Recent nitpick comments
src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h (1)

1036-1044: Parameter should be passed by const reference.

Line 1037 passes accessions by value (const std::set<String> accessions) instead of by const reference, causing an unnecessary copy of the entire set on each call. This appears to be a pre-existing issue but worth fixing while refactoring this area.

Suggested fix
     template<class IdentificationType>
-    static void removeHitsMatchingProteins(std::vector<IdentificationType>& ids, const std::set<String> accessions)
+    static void removeHitsMatchingProteins(std::vector<IdentificationType>& ids, const std::set<String>& accessions)
     {
       HasMatchingAccession<typename IdentificationType::HitType> acc_filter(accessions);

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7d594c5 and 17c9e76.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h
  • src/openms/source/PROCESSING/ID/IDFilter.cpp
🧰 Additional context used
📓 Path-based instructions (8)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

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

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

Files:

  • src/openms/source/PROCESSING/ID/IDFilter.cpp
  • src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h
src/openms/**/*.cpp

📄 CodeRabbit inference engine (AGENTS.md)

Use using namespace and using std::... declarations allowed only in implementation files

Files:

  • src/openms/source/PROCESSING/ID/IDFilter.cpp
src/openms/source/**/*.cpp

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/source/**/*.cpp: Each C++ implementation file must have a file preamble containing the $Maintainer:$ marker
File names must match the class name; store one class per file with corresponding .h and .cpp pair
Do not modify files in src/openms/extern/; this directory contains third-party vendored code

Files:

  • src/openms/source/PROCESSING/ID/IDFilter.cpp
src/openms/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.{h,cpp}: Use 2-space indentation (not tabs) with Unix line endings (LF) for C++ files
Use lowerCamelCase for method and function names
Use snake_case for variable and parameter names
Private and protected member variables must end with a trailing underscore (e.g., intensity_)
Use UPPER_SNAKE_CASE for enum values and preprocessor macros
Opening and closing braces must align and be on separate lines; always use braces even for single-line blocks (trivial one-liners may stay on one line)
Add a space after control flow keywords (if, for, while, switch)
Add spaces around binary operators for readability
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h (e.g., Size, SignedSize) for STL container sizes instead of std::size_t
Avoid pointers; prefer references where possible for safer memory management
Use Doxygen documentation with /** */ block comments and @ tags (not backslash); @brief is required
Comments should comprise at least ~5% of code; use // style comments in plain English describing the next few lines
Avoid std::endl for performance; prefer \n when outputting to streams
Use OpenMS logging macros and OpenMS::LogStream instead of std::cout or std::cerr
Exceptions must derive from Exception::Base; throw with file/line/OPENMS_PRETTY_FUNCTION; catch by reference; document possible exceptions in Doxygen
Follow Rule-of-0 (no custom constructors/destructors) or Rule-of-6 (all six special member functions); do not mix partial implementations
Use OPENMS_LOG_WARN, OPENMS_LOG_INFO, OPENMS_LOG_DEBUG and other OpenMS logging macros for all logging output
Prefer String::fromNumber() and String::toDouble() from OpenMS for numeric formatting and parsing over standard C++ methods

Files:

  • src/openms/source/PROCESSING/ID/IDFilter.cpp
  • src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h
src/**

📄 CodeRabbit inference engine (AGENTS.md)

File extensions should be lowercase, except for ML, XML, and mzData which use specific capitalization

Files:

  • src/openms/source/PROCESSING/ID/IDFilter.cpp
  • src/openms/include/OpenMS/PROCESSING/ID/IDFilter.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/PROCESSING/ID/IDFilter.h
src/openms/**/*.h

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.h: Do not add using namespace or using std::... declarations in header files
Use PascalCase for class names, namespaces, and types

Files:

  • src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h
src/openms/include/**/*.h

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/include/**/*.h: Each C++ header file must have a file preamble containing the $Maintainer:$ marker
Export all non-template classes, structs, functions, and global variables using the OPENMS_DLLAPI macro
Do not include OPENMS_DLLAPI on template classes or functions
File names must match the class name; store one class per file with corresponding .h and .cpp pair
Use forward declarations in headers instead of including full definitions when possible; only include base class headers and headers for non-pointer members
Include Doxygen @brief documentation on all public classes and methods with parameter directions [in], [out], or [in,out]
Accessor methods should use get/set pairs for protected/private members; do not use reference getters for primitive types
Include @ingroup Doxygen tags to categorize classes (e.g., @ingroup Analysis_ID, @ingroup Analysis) for documentation organization
Use @todo Doxygen tag with assignee name (e.g., @todo JohnDoe fix this) for tracking pending work

Files:

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

Applied to files:

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

Applied to files:

  • src/openms/source/PROCESSING/ID/IDFilter.cpp
  • src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h
📚 Learning: 2026-01-14T18:52:46.327Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-14T18:52:46.327Z
Learning: Applies to src/openms/**/*.{h,cpp} : Use OpenMS primitive types from `OpenMS/CONCEPT/Types.h` (e.g., `Size`, `SignedSize`) for STL container sizes instead of `std::size_t`

Applied to files:

  • src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h
📚 Learning: 2026-01-14T18:51:46.097Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-01-14T18:51:46.097Z
Learning: Applies to src/pyOpenMS/**/*.py : Use `PeptideIdentificationList` type (not Python list) when calling `setPeptideIdentifications()` in pyOpenMS

Applied to files:

  • src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h
🧬 Code graph analysis (2)
src/openms/source/PROCESSING/ID/IDFilter.cpp (1)
src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h (1)
  • removeUnreferencedProteins (1481-1484)
src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h (1)
src/openms/source/METADATA/PeptideHit.cpp (2)
  • extractProteinAccessionsSet (354-366)
  • extractProteinAccessionsSet (354-354)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: build-wheels-linux-arm
  • GitHub Check: build-wheels-windows
  • GitHub Check: build-wheels-linux
  • GitHub Check: build-wheels-macos
  • GitHub Check: build-and-test (macos-14, xcode, 15.4)
  • GitHub Check: build-and-test (ubuntu-24.04, g++, 13)
  • GitHub Check: build-and-test (windows-2025, cl.exe, 14.44)
  • GitHub Check: build-and-test (ubuntu-24.04, clang++, 17)
  • GitHub Check: build-and-test (ubuntu-24.04-arm, g++, 13)
  • GitHub Check: cppcheck-test
🔇 Additional comments (9)
src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h (2)

264-292: Well-designed generic template with clear semantics.

The HasMatchingAccessionImpl template cleanly abstracts over different set types while maintaining O(1) or O(log n) lookup depending on the container. The explicit constructor and const reference storage are appropriate for predicate usage patterns.

One consideration: the const SetType& member creates a lifetime dependency - the predicate must not outlive the container it references. This is the standard pattern for predicates in STL algorithms (which consume them immediately), so it's appropriate here.


295-301: Clean backward-compatible API via type aliases.

The aliases preserve the existing public API while enabling the new generic implementation. The naming convention (HasMatchingAccessionUnordered for unordered_set) is clear.

src/openms/source/PROCESSING/ID/IDFilter.cpp (7)

17-33: Helper function correctly consolidates accession collection logic.

The collectReferencedAccessions function properly extracts the previously duplicated pattern of gathering protein accessions from peptide hits grouped by run identifier. The implementation is clean and uses appropriate OpenMS data structures.


35-48: Symmetric helper for protein accession collection.

The collectProteinAccessions function mirrors collectReferencedAccessions for protein identifications. Clean implementation that eliminates duplication in removeDanglingProteinReferences variants.


50-58: Evidence filtering helper uses optimized O(1) lookups.

filterEvidencesByAccessions correctly applies HasMatchingAccessionUnordered<PeptideEvidence> to filter peptide evidences, leveraging the unordered_set for O(1) membership testing per evidence.


60-75: Reusable peptide reference filtering with optional hit removal.

The filterPeptideReferences helper cleanly encapsulates the common pattern of filtering evidences and optionally removing hits without remaining references. This eliminates significant code duplication across the removeDanglingProteinReferences overloads.


316-333: Simplified removeUnreferencedProteins using helper function.

The refactored implementation correctly uses collectReferencedAccessions and the new HasMatchingAccessionUnordered alias. The map's operator[] behavior (creating empty set for missing keys) correctly handles cases where no peptides reference a protein run - all proteins would be filtered out, matching the intended semantics.


335-366: Consolidated removeDanglingProteinReferences using helper functions.

All three overloads of removeDanglingProteinReferences now use the centralized filterPeptideReferences helper, significantly reducing code duplication. The lambda captures are safe as they're used immediately within the calling scope.


283-284: Consistent use of HasMatchingAccessionUnordered across the file.

The updated usages at lines 283, 311, and 421 consistently apply HasMatchingAccessionUnordered<ProteinHit> for protein filtering operations, providing O(1) lookups where appropriate.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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.

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 simplifies the IDFilter implementation by eliminating code duplication through template unification and helper function extraction. The refactoring reduces the codebase by approximately 65 lines while maintaining full backward API compatibility.

Changes:

  • Unified HasMatchingAccession and HasMatchingAccessionUnordered into a single template HasMatchingAccessionImpl with type aliases for backward compatibility
  • Extracted duplicated accession collection logic into collectReferencedAccessions and collectProteinAccessions helper functions
  • Created filterEvidencesByAccessions and filterPeptideReferences helpers to consolidate evidence filtering logic
  • Simplified multiple overloads of removeUnreferencedProteins and removeDanglingProteinReferences using the new helper functions
  • Removed unnecessary struct keyword from template instantiations

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h Unified duplicate predicate structs into template with type aliases; removed redundant struct keywords
src/openms/source/PROCESSING/ID/IDFilter.cpp Added anonymous namespace helpers for accession collection and filtering; simplified function implementations using helpers

@timosachsenberg timosachsenberg left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

looks good

@timosachsenberg
timosachsenberg merged commit e3a7963 into develop Jan 15, 2026
@timosachsenberg
timosachsenberg deleted the feature/idfilter-kiss-simplification branch January 15, 2026 17:31
claude Bot pushed a commit that referenced this pull request Jan 18, 2026
Added 19 missing PRs to OpenMS 3.6.0 changelog:

PyOpenMS:
- #8530: Build system modernization with py-build-cmake
- #8633: SpectrumNativeIDParser wrapper
- #8655: Arrow/Parquet export with DataFrame methods (BREAKING: method renames)
- #8661: Build dependency docs
- #8664: Biosaur2Algorithm wrap-inherits
- #8668: wrap-doc documentation
- #8674: Docstring validation tests

TOPP tools:
- #8643: FileInfo FASTA stats
- #8650: FileConverter MSP support
- #8649: PeakPickerHiRes parameter

OpenMS Library:
- #8633: SpectrumNativeIDParser class
- #8655: ArrowExport helper
- #8651, #8656, #8659, #8660, #8662: Performance optimizations

Fixes:
- #8645: DataArray handling in filters
- #8672: Test file correction
- #8678: UniqueIdGenerator seed collision fix

Build System:
- #8675, #8676: Claude CI workflows

Also reorganized misplaced entries from lines 122-129.

Co-authored-by: Timo Sachsenberg <[email protected]>
timosachsenberg added a commit that referenced this pull request Jan 18, 2026
* Add comprehensive changelog for OpenMS 3.6.0

Includes changes from 96 merged PRs since version 3.5.0:

- General: macOS Intel discontinued, Ubuntu 24.04, notarization in CI
- Dependencies: Autowrap >= 0.26.0, Eigen minimum 3.4.0
- PyOpenMS: Pythonic methods (__len__, __str__, __repr__, __hash__),
  DataFrame support, new wrappers, string handling improvements
- TOPP tools: MapAligner spectra transformation, FileInfo improvements,
  IsobaricWorkflow fixes, SageAdapter thread handling
- OpenMS Library: PeakFileOptions, ParamIterator, SpectrumAnnotator
- Breaking changes: Matrix<T> Eigen decoupling, API renames, FileWatcher move
- Bug fixes: NucleicAcidSearchEngine, LogConfigHandler, decoy generation
- Documentation: Targeted Quantitation, parameter annotations, AGENTS.md
- Build: macOS notarization, Parquet support, pytest fixtures

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

* Add missing changelog entries for recently merged PRs

Added 19 missing PRs to OpenMS 3.6.0 changelog:

PyOpenMS:
- #8530: Build system modernization with py-build-cmake
- #8633: SpectrumNativeIDParser wrapper
- #8655: Arrow/Parquet export with DataFrame methods (BREAKING: method renames)
- #8661: Build dependency docs
- #8664: Biosaur2Algorithm wrap-inherits
- #8668: wrap-doc documentation
- #8674: Docstring validation tests

TOPP tools:
- #8643: FileInfo FASTA stats
- #8650: FileConverter MSP support
- #8649: PeakPickerHiRes parameter

OpenMS Library:
- #8633: SpectrumNativeIDParser class
- #8655: ArrowExport helper
- #8651, #8656, #8659, #8660, #8662: Performance optimizations

Fixes:
- #8645: DataArray handling in filters
- #8672: Test file correction
- #8678: UniqueIdGenerator seed collision fix

Build System:
- #8675, #8676: Claude CI workflows

Also reorganized misplaced entries from lines 122-129.

Co-authored-by: Timo Sachsenberg <[email protected]>

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Timo Sachsenberg <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants