Skip to content

Add frame ID range filter to BrukerTimsFile - #9387

Merged
timosachsenberg merged 4 commits into
developfrom
claude/optimize-tims-loading-GfYju
May 20, 2026
Merged

timosachsenberg merged 4 commits into
developfrom
claude/optimize-tims-loading-GfYju

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds a frame ID range filter (frame_id_min, frame_id_max) to BrukerTimsFile::Config that allows selective loading of TIMS frames. This enables memory and I/O efficient processing of large files by skipping peak data for frames outside the specified range.

Key Changes

  1. New Config parameters: Added frame_id_min (default 0) and frame_id_max (default UINT32_MAX) to BrukerTimsFile::Config in the header file with comprehensive documentation of behavior and interactions with other knobs.

  2. Helper functions:

    • frameInRange(): Predicate to check if a frame ID falls within the active range
    • warnInvalidFrameRange(): Validates the range against file bounds and emits warnings for invalid configurations (inverted range, non-intersecting range)
  3. Range filtering applied throughout:

    • Frame iteration loops in loadFrames_(), loadDDA_(), loadDIAStreaming(), and loadDIAMetadata()
    • SQL queries in readFrameCounts() and countDDAPrecursors() to count only in-range frames
    • Frame-to-window-group mappings filtered to exclude out-of-range frames
    • DDA precursor entries filtered to remove precursors with MS2 frames outside the range
  4. Warnings and diagnostics:

    • One-shot validation warnings at each top-level entry point
    • Partial reconstruction warning for DDA precursors with source MS2 frames straddling the range boundary
    • Info log for fully dropped precursors
  5. Comprehensive test coverage: Added frame_id range filter test section covering:

    • Default vs. explicit full range equivalence
    • Sub-range filtering in FRAME mode
    • Single frame loading
    • Out-of-range and inverted range edge cases
    • DDA and DIA mode filtering
    • Metadata count consistency with actual spectrum emission

Behavior Notes

  • Frame aggregation (MS1/DIA MS2 neighbors) clamps at range boundaries like file boundaries
  • DDA precursors with MS2 frames straddling the boundary are reconstructed from in-range subset only
  • DDA OLS m/z recalibration uses only in-range precursors
  • All export modes (FRAME, SPECTRUM, DIA) honor the range filter

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.)

https://claude.ai/code/session_01Fx3wbLUovk62F5XxCDv5EG

Summary by CodeRabbit

  • New Features

    • Inclusive frame ID range filtering for Bruker TIMS loading, honored alongside RT windows, streaming vs non-streaming loads, export modes, and DIA/MS1 handling so emitted spectra match requested ranges.
  • Bug Fixes

    • Range-aware counting/reporting; warnings for partially/fully excluded precursors; metadata and prior counts pruned to match actual loaded spectra.
  • Tests

    • Integration tests validating frame-ID and RT-range behaviors across export modes and DIA vs DDA.

Review Change Stack

Avoids loading the whole .d file when only a single frame or a range
of frames is needed. Memory and I/O now scale with the requested
range, not the file size.

Honored by load(), transform(), loadDIAStreaming(), and
readDIAMetadata() across AUTO/SPECTRUM/FRAME export modes:
- MS1/MS2 frame collection loops in loadDDA_/loadDIA_/loadFrames_/
  loadDIAStreaming skip out-of-range frames before peak extraction
- readDIAMetadata's MS1 count and per-WindowGroup MS2 counts match
  what loadDIAStreaming will actually emit (CachedSwathFileConsumer
  sizes its buffers from these)
- transform's expected-size computation uses range-aware SQL counts
- DDA: precursor entries whose MS2 frame is out of range are dropped;
  a one-shot warning reports how many precursors become partial at
  the range boundary

Interplay notes (also documented on the Config field):
- Frame aggregation (ms1/dia_ms2_n_neighbors) clamps at the range
  boundaries the same way it clamps at file boundaries; widen the
  range by n_neighbors for unbiased aggregation throughout
- Centroiding is per-frame, so unaffected beyond fewer frames
- DDA OLS recalibration is fit from in-range precursors only
@OpenMS OpenMS deleted a comment from github-actions Bot May 20, 2026
Lets callers request a retention-time range instead of (or in
addition to) raw frame IDs. The RT range is resolved to a frame_id
range at load time via SQL:

  SELECT MIN(Id), MAX(Id) FROM Frames WHERE Time IN [rt_min, rt_max]

and intersected with frame_id_min/frame_id_max — so downstream code
still only honors a single filter (frame_id), while users get two
intuitive knobs. TIMS frame IDs are monotonic in acquisition time,
so an RT range maps cleanly to a contiguous frame_id sub-range.

Folded the previous warnInvalidFrameRange() helper into
resolveEffectiveConfig(), which now: (a) validates both ranges,
(b) resolves the RT range, (c) returns an effective Config that
downstream loaders consume. All four public entry points
(load, transform, loadDIAStreaming, readDIAMetadata) call it
once and pass the effective Config to internal loaders. The
DDA partial-precursor warning and all interplay caveats apply
identically to either knob.
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 56808dab-2e9e-4e2a-afa0-efc7d78b5c17

📥 Commits

Reviewing files that changed from the base of the PR and between ca27f03 and 20e1c11.

📒 Files selected for processing (1)
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp

📝 Walkthrough

Walkthrough

Adds inclusive frame ID range filtering (Config.frame_id_min/max) and resolution/validation; applies filtering across metadata counting, DIA/DDA loading, and FRAME export, with tests covering frame and RT range interactions.

Changes

Frame ID range filtering

Layer / File(s) Summary
Config API and validation helpers
src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h, src/openms/source/FORMAT/BrukerTimsFile.cpp
Adds frame_id_min (default 0) and frame_id_max (default std::numeric_limits<uint32_t>::max()), includes <limits>, and implements frameInRange() plus resolveEffectiveConfig() which validates/intersects frame and RT inputs.
Frame-count and precursor counting refactor
src/openms/source/FORMAT/BrukerTimsFile.cpp
readFrameCounts() and countDDAPrecursors() now accept the active Config and count only MS1/MS2 frames and distinct DDA precursors whose associated MS2 frame IDs fall within the effective frame ID window.
DIA metadata and streaming adjustments
src/openms/source/FORMAT/BrukerTimsFile.cpp
readDIAMetadata() and loadDIAStreaming() resolve the effective config, count MS1/MS2 only for in-range frames, prune out-of-range frames from window-group mappings, and use effective centroid caps for reporting.
Transform/load entry integration
src/openms/source/FORMAT/BrukerTimsFile.cpp
load() and transform() resolve the effective config up front, recompute expected sizes using range-filtered counts, prune DIA group_to_frames, and dispatch to the appropriate load implementation with the effective config.
DDA loading and precursor pruning
src/openms/source/FORMAT/BrukerTimsFile.cpp
loadDDA_() filters MS1/MS2 frame iteration by frameInRange(), handles partially reconstructed vs fully skipped precursors at range boundaries with WARN/INFO logs, and removes precursors whose MS2 frame IDs are out-of-range.
DIA load pruning and FRAME export
src/openms/source/FORMAT/BrukerTimsFile.cpp
loadDIA_() prunes per-window group_to_frames by frameInRange(); loadFrames_() filters raw frame iteration so FRAME export emits only in-range frames.
Integration tests for frame and RT ranges
src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
Adds tests validating frame_id_min/max and rt_min_sec/rt_max_sec behaviors across export modes, empty/inverted ranges, single-frame bounds, and DIA metadata consistency.

Possibly related PRs

  • OpenMS/OpenMS#9152: Refactors MS1 loading paths that interact with the frame-id gating added here.
  • OpenMS/OpenMS#9129: Overlaps changes to DIA streaming/metadata and the same functions updated here (readDIAMetadata/loadDIAStreaming).
  • OpenMS/OpenMS#9019: Modifies DIA MS2 loading logic in the same area (window->spectrum handling) and may interact with the pruning logic.

Suggested reviewers

  • jcharkow
  • alhigaylan
  • jpfeuffer

Poem

🐰 I nibble frames from min to max with care,
Prune out the edges, leave the middle fair.
DIA and DDA hop in tidy rows,
Spectra follow where the window goes.
A cheerful rabbit cheers—filtered data shows!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.06% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main change: adding a frame ID range filter capability to BrukerTimsFile.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/optimize-tims-loading-GfYju

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.

🧹 Nitpick comments (1)
src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp (1)

557-575: ⚡ Quick win

Add an explicit filtered readDIAMetadata ↔ loadDIAStreaming count-parity assertion.

This block says the counts must match streaming output, but currently only checks meta_sub relative to meta_full. Please assert exact equality against filtered streaming output too.

Proposed test extension
   ExperimentalSettings settings_sub;
   auto meta_sub = f.readDIAMetadata(OPENTIMS_DIA_TEST_DATA, settings_sub, cfg_dia_sub);
   TEST_EQUAL(meta_sub.nr_ms1_spectra <= meta_full.nr_ms1_spectra, true);
   TEST_EQUAL(meta_sub.nr_ms2_spectra.size(), meta_full.nr_ms2_spectra.size());
@@
   TEST_EQUAL(any_smaller, true);
+
+  // Filtered metadata counts must match filtered streaming emission counts.
+  RegularSwathFileConsumer consumer_sub(meta_sub.boundaries);
+  consumer_sub.setExperimentalSettings(settings_sub);
+  f.loadDIAStreaming(OPENTIMS_DIA_TEST_DATA, consumer_sub, cfg_dia_sub);
+
+  std::vector<OpenSwath::SwathMap> maps_sub;
+  consumer_sub.retrieveSwathMaps(maps_sub);
+  Size ms2_idx = 0;
+  for (const auto& m : maps_sub)
+  {
+    if (m.ms1)
+    {
+      TEST_EQUAL(m.sptr->getNrSpectra(), static_cast<size_t>(meta_sub.nr_ms1_spectra));
+    }
+    else
+    {
+      TEST_EQUAL(m.sptr->getNrSpectra(), static_cast<size_t>(meta_sub.nr_ms2_spectra[ms2_idx]));
+      ++ms2_idx;
+    }
+  }
+  TEST_EQUAL(ms2_idx, meta_sub.nr_ms2_spectra.size());
 `#endif`

As per coding guidelines, “Write unit tests for new functionality and ensure existing tests pass before suggesting changes.”

🤖 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/tests/class_tests/openms/source/BrukerTimsFile_test.cpp` around lines 557
- 575, Extend the test to assert parity between readDIAMetadata results and what
loadDIAStreaming would emit when using the same filter: call loadDIAStreaming
(or the streaming loader helper used in tests) with OPENTIMS_DIA_TEST_DATA and
cfg_dia_sub, collect the per-window MS1/MS2 counts it produces, and add
TEST_EQUAL assertions that those counts exactly equal meta_sub.nr_ms1_spectra
and meta_sub.nr_ms2_spectra respectively (in addition to the existing
comparisons against meta_full); reference the existing variables/functions
meta_sub, meta_full, readDIAMetadata, loadDIAStreaming, and cfg_dia_sub so the
new assertions are placed right after the meta_sub creation and the any_smaller
loop.
🤖 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/tests/class_tests/openms/source/BrukerTimsFile_test.cpp`:
- Around line 557-575: Extend the test to assert parity between readDIAMetadata
results and what loadDIAStreaming would emit when using the same filter: call
loadDIAStreaming (or the streaming loader helper used in tests) with
OPENTIMS_DIA_TEST_DATA and cfg_dia_sub, collect the per-window MS1/MS2 counts it
produces, and add TEST_EQUAL assertions that those counts exactly equal
meta_sub.nr_ms1_spectra and meta_sub.nr_ms2_spectra respectively (in addition to
the existing comparisons against meta_full); reference the existing
variables/functions meta_sub, meta_full, readDIAMetadata, loadDIAStreaming, and
cfg_dia_sub so the new assertions are placed right after the meta_sub creation
and the any_smaller loop.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0629811a-f978-4197-847b-138fcaee1dbe

📥 Commits

Reviewing files that changed from the base of the PR and between 2fda096 and 62a9bf1.

📒 Files selected for processing (3)
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp

@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

🤖 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.

Inline comments:
In `@src/openms/source/FORMAT/BrukerTimsFile.cpp`:
- Around line 1907-1913: readDIAMetadata() currently counts all in-range MS1
frames into meta.nr_ms1_spectra regardless of the eff.load_ms1 setting; update
the counting so it honors eff.load_ms1 by skipping MS1 counting when
eff.load_ms1 is false (e.g., return/set meta.nr_ms1_spectra to 0 or skip
incrementation) — modify the loop that uses frameInRange(fid, eff),
handle->has_frame(fid) and handle->get_frame(fid).msms_type to only increment
meta.nr_ms1_spectra when eff.load_ms1 is true.
- Around line 780-796: The intersection code in BrukerTimsFile (around
q.executeStep()) may invert eff.frame_id_min/max silently when the explicit
frame_id_* range and the RT-derived range are each valid but disjoint; detect
this by saving the pre-intersection values of eff.frame_id_min and
eff.frame_id_max, perform the intersection using rt_fid_min/rt_fid_max as you
already do, and if the pre-intersection range was valid (pre_min <= pre_max) but
the post-intersection range is empty (eff.frame_id_min > eff.frame_id_max) emit
a clear warning (use OPENMS_LOG_WARN) that the frame and RT filters do not
intersect (include config.rt_min_sec and config.rt_max_sec and the original
frame_id bounds in the message) so the one-shot diagnostic is produced instead
of silently returning zero spectra; keep the existing fallback (eff.frame_id_min
= 1; eff.frame_id_max = 0) when q.executeStep() is false.

In `@src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp`:
- Around line 594-596: The test currently assumes RT order by using
exp_full[0].getRT() and exp_full[exp_full.size()-1].getRT() for rt_lo/rt_hi;
instead compute the true RT bounds by scanning all spectra in exp_full and
taking the minimum and maximum getRT() values (e.g., using a loop or
std::min_element/std::max_element over exp_full.getRT()), then use those
computed min/max RT values in place of rt_lo/rt_hi to avoid ordering
assumptions.
🪄 Autofix (Beta)

✅ Autofix completed


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 72f3805a-14b1-4593-9740-0bfc81852c2d

📥 Commits

Reviewing files that changed from the base of the PR and between 62a9bf1 and 5074d44.

📒 Files selected for processing (3)
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp

@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Fixes Applied Successfully

Fixed 2 file(s) based on 3 unresolved review comments.

Files modified:

  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp

Commit: ca27f03e540a63263c9d5304d5636037ecedf68d

The changes have been pushed to the claude/optimize-tims-loading-GfYju branch.

Time taken: 3m 54s

Fixed 2 file(s) based on 3 unresolved review comments.

Co-authored-by: CodeRabbit <[email protected]>

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 adds an inclusive frame-ID range filter (frame_id_min, frame_id_max) to BrukerTimsFile::Config to allow loading only a subset of TIMS frames, reducing I/O and memory for large datasets. The range filtering is applied consistently across load paths (DDA, DIA, FRAME, streaming) and metadata/count calculations, with warnings for invalid/disjoint ranges and tests covering key scenarios.

Changes:

  • Added frame_id_min/frame_id_max (and associated docs) plus RT→frame-range resolution/validation to produce an effective config used by all load entry points.
  • Applied frame-range filtering to DDA/DIA/FRAME iteration and to SQL-based counting/metadata so expected counts match emitted spectra.
  • Added class tests for frame-id range filtering across modes (incl. DIA metadata consistency checks).

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h Adds the new config knobs with detailed behavior/interactions documentation.
src/openms/source/FORMAT/BrukerTimsFile.cpp Implements range predicate + effective-config resolution, applies filtering across load/stream/metadata/count code paths.
src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp Adds new test section for frame-id range filtering across export modes and DIA/DDA paths.
Comments suppressed due to low confidence (2)

src/openms/source/FORMAT/BrukerTimsFile.cpp:2272

  • ms2_frame_ids is collected but never used (only ms1_frame_ids and the SQL-derived precursor frame IDs are used later). This will trigger an unused-variable warning and the surrounding comments refer to a filter that isn’t actually applied via ms2_frame_ids. Remove ms2_frame_ids (and the else branch pushing into it) or use it in the downstream MS2/precursor logic.
    std::vector<uint32_t> ms1_frame_ids;
    std::vector<uint32_t> ms2_frame_ids;

    for (uint32_t fid = handle.min_frame_id(); fid <= handle.max_frame_id(); ++fid)
    {
      if (!frameInRange(fid, config)) continue;
      if (!handle.has_frame(fid)) continue;
      TimsFrame& frame = handle.get_frame(fid);
      if (frame.msms_type == 0)
        ms1_frame_ids.push_back(fid);
      else
        ms2_frame_ids.push_back(fid);

src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp:513

  • Similarly, the single-frame range test (frame_id_min == frame_id_max) only asserts <= 1, which would not catch errors like emitting 0 spectra for a valid single-frame range. Prefer asserting exactly 1 spectrum when the fixture contains that frame (or compute the expected presence from the baseline experiment).
  // --- Single frame range: at most one spectrum ---
  BrukerTimsFile::Config cfg_one;
  cfg_one.export_mode = BrukerTimsFile::Config::FRAME;
  cfg_one.frame_id_min = 1;
  cfg_one.frame_id_max = 1;
  MSExperiment exp_one;
  f.load(OPENTIMS_DDA_TEST_DATA, exp_one, cfg_one);
  TEST_EQUAL(exp_one.size() <= 1, true);

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
@timosachsenberg
timosachsenberg merged commit a048267 into develop May 20, 2026
41 checks passed
@timosachsenberg
timosachsenberg deleted the claude/optimize-tims-loading-GfYju branch May 20, 2026 19:48
timosachsenberg pushed a commit that referenced this pull request May 21, 2026
- FeatureFinderMetaboIdent: adduct support via optional TSV column (#9382)
- BrukerTimsImagingFile: new Bruker .d MALDI imaging loader (#9383)
- BrukerTimsFile: frame_id/RT range filter in Config (#9387)
- Fix: SwathMapMassCorrection null-pointer and memory leak (#9386)

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[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.

3 participants