Repository navigation
Fix data array misalignment in sort/select operations - #9799
timosachsenberg wants to merge 5 commits into
Conversation
Both classes carry float/string/integer data arrays that are parallel to
the peaks, but neither kept them in sync when the peaks were permuted or
dropped.
MSChromatogram::sortByPosition() guarded its metadata-ignoring fast path
on float_data_arrays_.empty() alone, ignoring string and integer arrays.
MSChromatogram::sortByIntensity() guarded on an inverted condition:
float_data_arrays_.empty() && !string_data_arrays_.empty() && !integer_data_arrays_.empty()
i.e. it took the fast path precisely when string and integer arrays were
present, and the slow path when no metadata existed at all.
The sortByPosition() case is reachable on the mzML load path: MzMLHandler
populates chromatogram integer/string binary data arrays and then calls
sortByPosition() when 'sort_chromatograms_by_rt' is set, so a chromatogram
with integer/string arrays but no float array had its peaks reordered while
the arrays stayed in file order -- and the mismatch was written back out on
store.
Mobilogram::sortByIntensity()/sortByPosition() were a bare stable_sort over
the peaks and never touched any array family. No in-tree caller sorts a
Mobilogram, but both sorts and all three array accessors are exposed via
pyOpenMS, whose docstring already promised the arrays would follow.
Both classes now permute peaks and all three array families together,
reusing the select()-based approach MSSpectrum already uses. MSChromatogram
already had select() -- the sorts simply never called it. Mobilogram gains
the select() and sort(Predicate) members it was missing; its class test
already contained a placeholder section for the latter, now a real test.
Also fixes clear(): Mobilogram::clear() and MSChromatogram::clear(false)
retained the data arrays while dropping the peaks, leaving the container
internally inconsistent. Both now clear the arrays and ranges, matching
MSSpectrum::clear(); for MSChromatogram the 'clear_meta_data' flag now
governs only ChromatogramSettings and the name. This also removes a latent
accumulation bug in PeakPickerMobilogram, which does clear() -> resize() ->
push_back and would have appended to stale entries on reuse of its output.
Behaviour changes: MSChromatogram sorting is now stable (std::sort ->
std::stable_sort), and a data array whose size does not match the peak
count now throws Exception::Precondition instead of silently corrupting
the association.
Verified by rebuilding with only the buggy logic restored: 18 assertions
fail in MSChromatogram_test and 19 in Mobilogram_test, all passing with
the fix.
Part of #9792
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01APConSDbHrNux6qmuP4oVh
…allers Review follow-ups on the data-array sync fix. Headers: the new sort(Predicate) template calls std::stable_sort but the headers only included <numeric>, relying transitively on another header for <algorithm>. Both now include it directly. select() validated data array sizes only after it had already permuted the peaks, so the advertised Exception::Precondition left the container half-permuted. Both MSChromatogram::select() and Mobilogram::select() now validate every index and every non-empty data array size up front, so a rejected call leaves the container exactly as it was. Out-of-range indices are rejected as well; MSChromatogram::select previously documented that "indices are NOT checked for validity", which the rewritten sorts now rely on. Also switched the string arrays from std::move to copy: duplicate indices previously yielded an empty string for the second occurrence, because the source entry had already been moved from. Three callers rebuilt a container with clear() + push_back and so relied on the data arrays surviving clear(): - PeakPickerMobilogram::filterPeakIntensities_ (both overloads) and the GUI helper filterChrom now use select() instead, which subsets the arrays alongside the peaks. Previously the arrays survived but with a stale size; after the clear() change they would have been dropped. select() is correct under either semantics. - MSDataCachedConsumer's comment claimed string arrays were preserved by its destructive clear. That was already untrue for spectra -- MSSpectrum::clear has always cleared all three families -- so the stale comment is corrected rather than the behaviour. Documented that select() does not recompute cached ranges: a permutation preserves them, but selecting a subset can leave them too wide. Also corrected an overstated claim in the CHANGELOG: a sort that short-circuits because the peaks are already in order does not inspect the data arrays, so a size mismatch is only rejected when the sort actually permutes. New tests: duplicate indices, out-of-range indices, container state after a rejected call, and reverse intensity sort with float arrays present. Part of #9792 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01APConSDbHrNux6qmuP4oVh
- sort(Predicate): validate data-array sizes up front via a new shared checkDataArraySizes_() helper, so a mis-sized array throws Exception::Precondition *before* the user predicate can index it out of bounds. select() now reuses the same helper and drops its now-redundant per-lane size checks. (MSChromatogram, Mobilogram) - sort() docs: converted from /// to Doxygen /** */ with @brief/@tparam/@param/@exception. - PeakPickerMobilogram::filterPeakIntensities_ (both overloads): reject empty/inverted/out-of-range [left,right] before building the keep list. An empty mobilogram made findHighestPeak_ return right_index == SIZE_MAX (size()-1 underflow), which underflowed the reserve and spun the fill loop. - LayerStoreData::filterChrom: call updateRanges() after select() so a filtered chromatogram's cached RT/intensity bounds reflect only the retained peaks. - Tests: tied-key stable-order fixtures for MSChromatogram and Mobilogram (assert full peak + string + integer array order for ascending and descending sorts, from a start order that defeats every sort short-circuit) plus a direct sort(lambda) malformed-array precondition test. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01NBHPFbi3DC2mFxeRK6VXXU
…795-review-vaqdlr # Conflicts: # CHANGELOG
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
💤 Files with no reviewable changes (1)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughThe change keeps chromatogram and mobilogram peaks aligned with float, string, and integer data arrays during sorting and selection. It adds size validation, clears parallel arrays consistently, updates filtering callers, and adds regression coverage. ChangesPeak data alignment
Sequence Diagram(s)sequenceDiagram
participant PeakPickerMobilogram
participant Mobilogram
participant DataArrays
PeakPickerMobilogram->>Mobilogram: build selection indices
PeakPickerMobilogram->>Mobilogram: select(indices)
Mobilogram->>DataArrays: subset aligned float/string/integer arrays
Mobilogram-->>PeakPickerMobilogram: filtered mobilogram
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp (1)
50-57: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe explicit
setFloatDataArrays({})/setIntegerDataArrays({})calls are now redundant.
clear(false)drops all three parallel array families after this PR, so these two setters no longer do anything. Dropping them keeps a single source of truth for the invariant (the postconditions below still assert it).Also applies to: 68-75
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp` around lines 50 - 57, Update the clearData_ blocks in the affected consumer paths to rely solely on s.clear(false), removing the redundant setFloatDataArrays({}) and setIntegerDataArrays({}) calls while preserving the existing postcondition assertions.src/openms/source/KERNEL/MSChromatogram.cpp (1)
115-147: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win
MSChromatogram::sortByIntensity()has no already-sorted short-circuit, which also makes the CHANGELOG claim inaccurate.sortByPosition()(Line 151) andMobilogram::sortByIntensity()both return early when the peaks are already ordered; the chromatogram intensity sort always permutes, so it always runscheckDataArraySizes_()and throws on a mis-sized array even for already-sorted input.
src/openms/source/KERNEL/MSChromatogram.cpp#L115-L147: add anstd::is_sortedearly return (ascending and reverse comparators) before the fast path, mirroringMobilogram::sortByIntensity().CHANGELOG#L20: the sentence "a sort that short-circuits because the peaks are already in order does not inspect the arrays" only holds once the guard above is added — otherwise reword it to excludeMSChromatogram::sortByIntensity().🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/openms/source/KERNEL/MSChromatogram.cpp` around lines 115 - 147, Add an std::is_sorted early return at the start of MSChromatogram::sortByIntensity(bool reverse), using comparators for both ascending and reverse intensity order, before the fast-path/data-array handling. Update CHANGELOG line 20 to ensure its statement about already-ordered sorts not inspecting arrays is accurate, either by reflecting the new chromatogram guard or excluding MSChromatogram::sortByIntensity() if appropriate.src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp (1)
265-285: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider logging when the bounds guard skips filtering.
Both overloads now silently leave the mobilogram unfiltered on empty/inverted/out-of-range bounds, so the caller gets the full mobilogram back with no indication that top-peak filtering did not happen. An
OPENMS_LOG_DEBUGline here would make that diagnosable;std::iotawould also replace the manualkeeploop.Also applies to: 287-307
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp` around lines 265 - 285, Update both mobilogram filtering overloads to emit an OPENMS_LOG_DEBUG message when the empty, inverted, or out-of-range bounds guard returns without filtering, including enough context to diagnose the skipped top-peak selection. Preserve the existing untouched-mobilogram behavior, and replace the manual keep-index loop with std::iota where applicable.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cpp`:
- Around line 265-285: Update both mobilogram filtering overloads to emit an
OPENMS_LOG_DEBUG message when the empty, inverted, or out-of-range bounds guard
returns without filtering, including enough context to diagnose the skipped
top-peak selection. Preserve the existing untouched-mobilogram behavior, and
replace the manual keep-index loop with std::iota where applicable.
In `@src/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cpp`:
- Around line 50-57: Update the clearData_ blocks in the affected consumer paths
to rely solely on s.clear(false), removing the redundant setFloatDataArrays({})
and setIntegerDataArrays({}) calls while preserving the existing postcondition
assertions.
In `@src/openms/source/KERNEL/MSChromatogram.cpp`:
- Around line 115-147: Add an std::is_sorted early return at the start of
MSChromatogram::sortByIntensity(bool reverse), using comparators for both
ascending and reverse intensity order, before the fast-path/data-array handling.
Update CHANGELOG line 20 to ensure its statement about already-ordered sorts not
inspecting arrays is accurate, either by reflecting the new chromatogram guard
or excluding MSChromatogram::sortByIntensity() if appropriate.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 25ad9462-1af3-4065-b114-d45a0d6be3a5
📒 Files selected for processing (10)
CHANGELOGsrc/openms/include/OpenMS/KERNEL/MSChromatogram.hsrc/openms/include/OpenMS/KERNEL/Mobilogram.hsrc/openms/source/ANALYSIS/OPENSWATH/PeakPickerMobilogram.cppsrc/openms/source/FORMAT/DATAACCESS/MSDataCachedConsumer.cppsrc/openms/source/KERNEL/MSChromatogram.cppsrc/openms/source/KERNEL/Mobilogram.cppsrc/openms_gui/source/VISUAL/VISITORS/LayerStoreData.cppsrc/tests/class_tests/openms/source/MSChromatogram_test.cppsrc/tests/class_tests/openms/source/Mobilogram_test.cpp
…ers, filter-skip logging
- MSChromatogram::sortByIntensity(): add the already-sorted std::is_sorted
short-circuit that sortByPosition() and Mobilogram::sortByIntensity() already
have. All four sort entry points now skip the permutation (and thus the
data-array validation) when the peaks are already ordered, which also makes the
CHANGELOG's "a short-circuiting sort does not inspect the arrays" statement
accurate for this method.
- MSDataCachedConsumer: drop the now-redundant setFloatDataArrays({}) /
setIntegerDataArrays({}) calls after clear(false), which already drops all
parallel arrays -- clear() is the single source of truth. The postconditions
still assert the invariant.
- PeakPickerMobilogram::filterPeakIntensities_ (both overloads): log at DEBUG when
the bounds guard skips filtering (the caller otherwise gets the unfiltered
mobilogram back with no indication), and build the keep list with std::iota.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NBHPFbi3DC2mFxeRK6VXXU
Description
This PR fixes a critical bug where
MSChromatogramandMobilogramsilently mis-associated per-peak metadata during sorting and selection operations. The data arrays (FloatDataArray, StringDataArray, IntegerDataArray) are parallel to the peaks and must be permuted together, but several code paths failed to do so.Issues Fixed
sortByPosition() / sortByIntensity(): When data arrays were present, peaks were permuted but the arrays were left in their original order, causing metadata to be associated with the wrong peaks.
sortByIntensity() fast path bug: The condition guarding the fast path was incorrect (
float_data_arrays_.empty()alone), causing string/integer arrays to be silently ignored even when present.sort(lambda) template: Was not implemented; now properly permutes all data arrays alongside peaks using a generic index-based approach.
select(): Improved validation and handling of duplicate indices (which must duplicate values, not leave moved-from holes).
clear(): Now properly clears data arrays alongside peaks, preventing inconsistent state where arrays survived after peaks were dropped.
Key Changes
sortByPosition()andsortByIntensity()to use a unifiedsort(lambda)implementation that permutes all data arrays together with peaks.sort(lambda)template: Validates data array sizes up front, then uses index-based stable sort to permute peaks and all arrays together.checkDataArraySizes_()helper: Validates that non-empty data arrays match the peak count before any mutation.select(): Validates indices and array sizes before modifying state; handles duplicate indices correctly by copying (not moving) string data.clear(): Now clears data arrays alongside peaks to maintain consistency.select()instead ofclear()+push_back()to preserve data arrays.select()for proper subsetting.Testing
Comprehensive regression tests added to both
Mobilogram_test.cppandMSChromatogram_test.cpp:select()produce correct duplicatessort(lambda)with custom predicatesAll existing tests pass; new tests ensure the bug does not regress.
Checklist
https://claude.ai/code/session_01NBHPFbi3DC2mFxeRK6VXXU
Summary by CodeRabbit
Bug Fixes
New Features
Documentation / Tests