Skip to content

Fix spectrum/chromatogram filters to properly handle DataArrays - #8645

Merged
timosachsenberg merged 5 commits into
developfrom
fix/issue-2475-dataarray-filter-consistency
Jan 13, 2026
Merged

timosachsenberg merged 5 commits into
developfrom
fix/issue-2475-dataarray-filter-consistency

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #2475 - Spectra filters don't consider DataArrays

When filtering peaks from MSSpectrum or MSChromatogram, the associated DataArrays (FloatDataArrays, StringDataArrays, IntegerDataArrays) were not being updated, causing data inconsistency. This PR ensures all filter code properly maintains DataArray consistency.

Changes

  • MSChromatogram: Add select() method mirroring MSSpectrum::select() to enable DataArray-aware filtering
  • TargetedSpectraExtractor: Replace erase() loops with select() in pickSpectrum() and removeZeroPeaks()
  • MetaboTargetedAssay: Replace erase() with select() for precursor peak removal (both locations)
  • OpenSwathWorkflow: Replace remove_if/erase with select() for chromatogram RT filtering
  • PeakPickerIM: Clear StringDataArrays and IntegerDataArrays before resize when creating averaged peaks (FloatDataArrays were already handled)

Solution Pattern

All filter code now uses the select() method which properly handles all DataArrays:

std::vector<Size> indices_to_keep;
for (Size i = 0; i < spectrum.size(); ++i) {
    if (keep_peak(spectrum[i])) {
        indices_to_keep.push_back(i);
    }
}
spectrum.select(indices_to_keep);  // Handles all DataArrays correctly

Test plan

  • Build OpenMS library
  • Run existing unit tests for affected classes
  • Verify DataArray sizes match peak counts after filtering operations

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added peak filtering capability for chromatograms and spectra with consistent data handling.
  • Bug Fixes

    • Fixed percentile calculations for sequence length statistics in small datasets.
    • Improved data array consistency when filtering peaks across analysis workflows.
  • Tests

    • Added new test cases for sequence length distribution reporting.

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

timosachsenberg and others added 3 commits January 12, 2026 20:57
- Add sequence length distribution (Min, 25%ile, Median, 75%ile, Max)
- Detect nucleic acid vs amino acid sequences automatically
- Use appropriate labels ("nucleotide" vs "amino acid")
- Report IUPAC ambiguity codes for nucleic acid files

Closes #8638

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Add sequence length distribution to expected output files.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
When filtering peaks from MSSpectrum or MSChromatogram, the associated
DataArrays (FloatDataArrays, StringDataArrays, IntegerDataArrays) must
be updated to maintain consistency. This fixes issue #2475.

Changes:
- Add MSChromatogram::select() method mirroring MSSpectrum::select()
- Fix TargetedSpectraExtractor to use select() instead of erase()
- Fix MetaboTargetedAssay to use select() instead of erase()
- Fix OpenSwathWorkflow chromatogram filtering to use select()
- Fix PeakPickerIM to clear non-IM DataArrays when creating new peaks

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

This comment was marked as outdated.

- Guard Q1/Q3 computation for <3 sequences
- Avoid unnecessary select() in TargetedSpectraExtractor
- Add TOPP_FileInfo_20 regression test

@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 (4)
src/openms/source/ANALYSIS/OPENSWATH/TargetedSpectraExtractor.cpp (1)

1061-1078: LGTM! Correctly implements index-based filtering for MS2 peaks.

The combined filtering (mz threshold AND intensity >= 1) with the select() pattern properly maintains DataArray consistency. The reserve() call is a good optimization.

One minor observation: unlike pickSpectrum which explicitly calls clear(true) when indices_to_keep is empty, this code relies on select({}) to clear the spectrum. This is functionally correct but slightly inconsistent. If you want uniform behavior, consider adding the explicit empty check:

Optional: explicit empty case handling
-      if (indices_to_keep.size() != spectrum.size())
+      if (indices_to_keep.empty())
+      {
+        spectrum.clear(true);
+      }
+      else if (indices_to_keep.size() != spectrum.size())
       {
         spectrum.select(indices_to_keep);
       }
src/topp/FileInfo.cpp (3)

894-908: Verify detection behavior for edge cases.

The nucleic acid detection logic classifies a file as amino acid if ANY character is not a valid IUPAC nucleotide code. This is a reasonable heuristic, but note that:

  1. An empty FASTA file would default to is_nucleic_acid = true
  2. Modified amino acid codes (e.g., selenocysteine 'U') could cause false classification as nucleic acid if the sequence contains only characters that happen to also be valid nucleotide codes

Consider adding a comment documenting the detection heuristic.

📝 Suggested documentation
+      // Detect if sequences are nucleic acid (vs amino acid)
+      // Heuristic: If ANY character is not a valid IUPAC nucleotide code, classify as amino acid.
+      // Note: This may misclassify short protein sequences containing only ACGTU residues.
       bool is_nucleic_acid = true;

987-1001: Consider noting when quartiles are approximations for small datasets.

When sequence_lengths.size() < 3, the quartiles fall back to min/max values. For users with small FASTA files (1-2 sequences), the output could be misleading as Q1=Min and Q3=Max without explanation.

📝 Suggested clarification
         os << "Sequence length distribution:\n";
+        if (sequence_lengths.size() < 3)
+        {
+          os << "  (Note: quartiles approximated for < 3 sequences)\n";
+        }
         os << "  Minimum : " << len_min << '\n';

1018-1019: Minor: Direct map access after iteration.

Line 1018 uses residue_counts['N'] and residue_counts['n'] which will insert zero-valued entries if these keys don't exist. This happens after the residue counts are already output (lines 1010-1013), so there's no functional impact. However, for consistency with the safe count_residues lambda used elsewhere (which uses find()), consider using it here too:

♻️ Consistent approach using count_residues
       if (is_nucleic_acid)
       {
-        size_t amb_N = residue_counts['N'] + residue_counts['n'];
+        size_t amb_N = count_residues(residue_counts, "Nn");
         size_t amb_all = count_residues(residue_counts, NA_AMBIGUOUS);
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 709bd1b and 72f4ca3.

📒 Files selected for processing (5)
  • src/openms/source/ANALYSIS/OPENSWATH/TargetedSpectraExtractor.cpp
  • src/tests/topp/CMakeLists.txt
  • src/tests/topp/FileInfo_20_input.fasta
  • src/tests/topp/FileInfo_20_output.txt
  • src/topp/FileInfo.cpp
✅ Files skipped from review due to trivial changes (2)
  • src/tests/topp/FileInfo_20_input.fasta
  • src/tests/topp/FileInfo_20_output.txt
🧰 Additional context used
📓 Path-based instructions (5)
**

📄 CodeRabbit inference engine (AGENTS.md)

File extensions must be lowercase except for ML, XML, and mzData

Files:

  • src/tests/topp/CMakeLists.txt
  • src/topp/FileInfo.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/TargetedSpectraExtractor.cpp
src/tests/topp/**

📄 CodeRabbit inference engine (AGENTS.md)

TOPP tests must be registered in src/tests/topp/CMakeLists.txt and placed alongside test data

Files:

  • src/tests/topp/CMakeLists.txt
**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,cpp}: Use 2-space indentation for C++ and header files; no tabs; Unix line endings (LF)
All non-template exported classes, structs, functions, and variables must use OPENMS_DLLAPI macro; templates are exempt
One class per file; class name must match file name exactly
Always pair .h header files with .cpp implementation files
Class and type names must use PascalCase; methods must use lowerCamelCase; variables must use snake_case
Private and protected member variables must end with trailing underscore _
Enum names and macro definitions must use UPPER_SNAKE_CASE; prefer enum class over C-style enums
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead of standard C++ types
Use Size/SignedSize types for STL .size() values instead of standard integer types
Prefer references over pointers in C++ code
Use Rule-of-0 (no explicit copy/move) or Rule-of-6 (all copy/move/destroy); never use Rule-of-5
Accessor methods must use get/set pairs for protected/private members; do not return references to primitive types
All exceptions must derive from Exception::Base; throw with file, line, and OPENMS_PRETTY_FUNCTION; catch by reference
Code comments must use // style; should comprise at least ~5% of code; describe the next few lines in plain English
Use .clang-format configuration from repository root for code formatting; check with clang-format --dry-run -Werror
Use OpenMS logging macros and OpenMS::LogStream; avoid std::cout and std::cerr
Avoid std::endl; prefer \n for better performance
Prefer OpenMS::String for numeric formatting and parsing
Braces must be on their own lines and aligned; always use braces even for single-line blocks (trivial one-liners may remain single-line)
Space required after keywords (if, for, while) and around binary operators

Files:

  • src/topp/FileInfo.cpp
  • src/openms/source/ANALYSIS/OPENSWATH/TargetedSpectraExtractor.cpp
src/topp/*.cpp

📄 CodeRabbit inference engine (AGENTS.md)

src/topp/*.cpp: Use ProgressLogger in TOPP tools for progress reporting
TOPP tool source files must be registered in src/topp/executables.cmake and added to src/openms/source/APPLICATIONS/ToolHandler.cpp
TOPP tools must define parameters in registerOptionsAndFlags_() and read with getStringOption_ and related helpers

Files:

  • src/topp/FileInfo.cpp
src/openms/**/*.{cpp,h,hpp,cc,cxx}

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

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

Files:

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

Applied to files:

  • src/tests/topp/CMakeLists.txt
📚 Learning: 2026-01-10T13:35:09.486Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-10T13:35:09.486Z
Learning: Applies to src/tests/topp/** : TOPP tests must be registered in `src/tests/topp/CMakeLists.txt` and placed alongside test data

Applied to files:

  • src/tests/topp/CMakeLists.txt
📚 Learning: 2026-01-10T13:35:09.486Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-10T13:35:09.486Z
Learning: Applies to src/topp/*.cpp : TOPP tool source files must be registered in `src/topp/executables.cmake` and added to `src/openms/source/APPLICATIONS/ToolHandler.cpp`

Applied to files:

  • src/tests/topp/CMakeLists.txt
📚 Learning: 2026-01-10T13:35:09.486Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-10T13:35:09.486Z
Learning: Applies to src/tests/class_tests/openms/executables.cmake : Test files must be registered in `src/tests/class_tests/openms/executables.cmake` to be included in the build

Applied to files:

  • src/tests/topp/CMakeLists.txt
📚 Learning: 2026-01-10T13:35:09.486Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-10T13:35:09.486Z
Learning: Applies to doc/doxygen/public/TOPP.doxygen : TOPP tool documentation must be added to `doc/doxygen/public/TOPP.doxygen` where applicable

Applied to files:

  • src/tests/topp/CMakeLists.txt
📚 Learning: 2026-01-10T13:35:09.486Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-10T13:35:09.486Z
Learning: Applies to src/tests/class_tests/openms/source/*_test.cpp : Use `NEW_TMP_FILE(filename)` macro for each output file in tests to avoid side effects

Applied to files:

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

Applied to files:

  • src/tests/topp/CMakeLists.txt
📚 Learning: 2026-01-10T13:35:09.486Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-10T13:35:09.486Z
Learning: Applies to src/tests/class_tests/openms/source/*_test.cpp : Unit tests must be placed in `src/tests/class_tests/openms/source/` with naming pattern `ClassName_test.cpp`

Applied to files:

  • src/tests/topp/CMakeLists.txt
📚 Learning: 2026-01-10T13:35:09.486Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-10T13:35:09.486Z
Learning: Applies to src/tests/class_tests/libs/data/** : Test data files must be placed in `src/tests/class_tests/libs/data/` with names prefixed by class name (e.g., `ClassName_data.mzML`)

Applied to files:

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

Applied to files:

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

Applied to files:

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

Applied to files:

  • src/openms/source/ANALYSIS/OPENSWATH/TargetedSpectraExtractor.cpp
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: cppcheck-test
🔇 Additional comments (5)
src/tests/topp/CMakeLists.txt (1)

717-719: New FileInfo TOPP test is registered correctly (incl. dependency to avoid parallel flakiness).
Good: TOPP_FileInfo_20_out1 depends on TOPP_FileInfo_20, and output paths use ${TESTS_TEMP_DIR} consistently. Based on learnings, this dependency direction is the right way to prevent flaky FuzzyDiff comparisons under parallel CTest runs.

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

459-479: LGTM! Clean implementation of the index-based filtering pattern.

The refactor from backward erase-loop to forward index collection with select() correctly addresses the DataArray consistency issue. The explicit clear(true) for the empty case and conditional select() for the partial case are both appropriate.

src/topp/FileInfo.cpp (3)

858-881: LGTM - Clean generalization of residue counting.

The rename from aacids/count_AAAs to residue_counts/count_residues properly generalizes the code for both amino acids and nucleotides. The lambda using find() avoids unintended map insertions.


947-970: LGTM - Clever ambiguity detection per sequence.

The before/after comparison approach correctly identifies whether each individual sequence contains ambiguous residues without needing separate per-sequence tracking.


1003-1014: LGTM - Clean sequence-type aware output.

The use of C++17 structured bindings and dynamic labels (residue_type, residue_type_cap) makes the output correctly adapt to the detected sequence type.

@OpenMS OpenMS deleted a comment from coderabbitai Bot Jan 13, 2026
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

looks good to me

@timosachsenberg
timosachsenberg enabled auto-merge (squash) January 13, 2026 14:20
@timosachsenberg
timosachsenberg merged commit 2c39aba into develop Jan 13, 2026
@timosachsenberg
timosachsenberg deleted the fix/issue-2475-dataarray-filter-consistency branch January 13, 2026 14:20
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.

spectra filter don't consider DataArrays

1 participant