Repository navigation
feat: Bruker timsTOF MS1 frame aggregation (DIA + DDA) - #9158
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
🚧 Files skipped from review as they are similar to previous changes (5)
📝 WalkthroughWalkthroughAdds optional MS1 frame-aggregation for Bruker TimsTOF (DIA/DDA) via new Changes
Sequence Diagram(s)sequenceDiagram
participant CLI as FileConverter (CLI)
participant Config as BrukerTimsFile::Config
participant Loader as BrukerTimsFile
participant Agg as FrameAggregator
participant Centroider as FrameCentroider
participant Output as mzML/SwathMap
CLI->>Config: parse bruker:ms1_* flags
CLI->>Loader: call load (with Config)
Loader->>Agg: reserve() and build (stack 2N+1 frames)
Agg->>Agg: filter by ms1_max_rt_distance_sec
Agg->>Centroider: hand aggregated grid (+max_peaks)
Centroider->>Centroider: centroid / cap / report
Centroider->>Output: emit MS1 spectrum (keep center metadata)
Loader->>Output: emit MS2 (denoise-skip uses contributing_frames)
Possibly related issues
Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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.
Actionable comments posted: 4
🧹 Nitpick comments (2)
src/openms/source/FORMAT/BrukerTimsFile.cpp (2)
1348-1348: Consider documenting the empirical reserve size.The magic number
300'000appears in multiple places for MS1 aggregator pre-allocation. A brief comment explaining the empirical basis (e.g., typical peak count per aggregation window) would help future maintainers understand and adjust this value if needed.📝 Example documentation
- if (config.ms1_n_neighbors > 0) ms1_aggregator.reserve(300'000); + // Empirical sizing: typical MS1 aggregation windows contain ~100-200k grid cells + // for a 2N+1 frame sum. Over-reserving avoids rehash cascades; clear() preserves capacity. + if (config.ms1_n_neighbors > 0) ms1_aggregator.reserve(300'000);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/FORMAT/BrukerTimsFile.cpp` at line 1348, The line using the magic number 300'000 (ms1_aggregator.reserve(300'000)) needs a short explanatory comment and ideally a named constant: document why 300000 was chosen (e.g., typical peaks per aggregation window, empirical dataset source or percentile) and replace the literal with a well-named constant like MS1_AGGREGATOR_RESERVE; update the use in the ms1_aggregator.reserve call and add the comment near the declaration of MS1_AGGREGATOR_RESERVE and/or next to config.ms1_n_neighbors to make the empirical basis and adjustability clear for future maintainers.
1139-1145: Minor: redundantframe_contributedtracking.Since the loop is only reached when
nframe.num_peaks > 0(line 1130 continues on empty frames), and all peaks are added unconditionally (no filter condition unlike the MS2 path at line 2095),frame_contributedwill always betrueafter the loop. This could be simplified:♻️ Suggested simplification
- bool frame_contributed = false; for (uint32_t p = 0; p < nframe.num_peaks; ++p) { aggregator.addPeak(mzs[p], intensities[p], scan_ids[p]); - frame_contributed = true; } - if (frame_contributed) ++contributing_frames; + ++contributing_frames; // nframe.num_peaks > 0 is guaranteed by continue above🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/FORMAT/BrukerTimsFile.cpp` around lines 1139 - 1145, Remove the redundant boolean tracking variable `frame_contributed` and its conditional check: since the loop over `p` runs only when `nframe.num_peaks > 0` and all peaks are added via `aggregator.addPeak(mzs[p], intensities[p], scan_ids[p])`, simply increment `contributing_frames` once for that non-empty frame (e.g. replace the `frame_contributed` declaration, loop body, and `if (frame_contributed) ++contributing_frames;` with the same loop that calls `aggregator.addPeak(...)` and then `++contributing_frames;`). This removes the unused `frame_contributed` symbol and keeps behavior identical.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@CHANGELOG`:
- Line 36: The changelog uses an ambiguous option name
`ms1_centroid_mz_ppm/pct`; update the text to use the exact config identifiers
used in code: `ms1_centroid_mz_ppm` and `ms1_centroid_im_pct` (referencing the
BrukerTimsFile::Config options exposed via FileConverter flags) so users can
find the correct knobs without guessing; replace the `/_pct` shorthand with the
literal `ms1_centroid_im_pct` identifier and ensure both option names are
spelled exactly as in the codebase.
In `@src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp`:
- Around line 1319-1328: The test currently picks MS1 via swath_maps.front() and
only checks spectrum count invariant, which doesn't verify streaming
aggregation; instead locate the MS1 map by checking the m.ms1 flag within
swath_maps (e.g., find the element where ms1 == true) and assert
aggregation-specific behavior by comparing its content (such as
sptr->getNrSpectra() or another measurable delta) against the default-streaming
result when cfg.ms1_n_neighbors is set/unset; update the test to compute both
the aggregated and default-streaming spectrum counts (or another
aggregation-visible metric) and assert the expected difference to prove
cfg.ms1_n_neighbors is honored rather than relying on front() or the invariant
meta.nr_ms1_spectra.
- Around line 1189-1203: The test only checks counts (ref_ms1 vs. agg_ms1) but
not per-frame content; update the test to iterate matching MS1 spectra in
exp_ref and exp_agg (use the same ordering used to compute ref_ms1/agg_ms1) and
assert that for each pair the peak count (e.g., spectrum.size() or equivalent)
is equal and that cumulative intensity (sum of peak intensities) matches within
a small tolerance; use the existing symbols exp_ref, exp_agg and the MS-level
check s.getMSLevel() to locate MS1 spectra and add assertions for peak-count
equality and approximate total-intensity equality to ensure FRAME-mode preserves
raw per-frame behavior.
In `@src/topp/FileConverter.cpp`:
- Around line 221-225: The option "bruker:ms1_min_support" currently allows any
non-negative integer but must be clamped to the maximum possible neighbors in a
3x3 grid (8); update the option registration to enforce a maximum of 8 (in
addition to the existing minimum 0) so values >8 cannot be set, by using the
option API (e.g., replace or augment registerIntOption_ / setMinInt_ usage for
"bruker:ms1_min_support" with a corresponding setMaxInt_ (or equivalent) call to
8) so the UI/CLI prevents impossible values and the filter behavior is correct.
---
Nitpick comments:
In `@src/openms/source/FORMAT/BrukerTimsFile.cpp`:
- Line 1348: The line using the magic number 300'000
(ms1_aggregator.reserve(300'000)) needs a short explanatory comment and ideally
a named constant: document why 300000 was chosen (e.g., typical peaks per
aggregation window, empirical dataset source or percentile) and replace the
literal with a well-named constant like MS1_AGGREGATOR_RESERVE; update the use
in the ms1_aggregator.reserve call and add the comment near the declaration of
MS1_AGGREGATOR_RESERVE and/or next to config.ms1_n_neighbors to make the
empirical basis and adjustability clear for future maintainers.
- Around line 1139-1145: Remove the redundant boolean tracking variable
`frame_contributed` and its conditional check: since the loop over `p` runs only
when `nframe.num_peaks > 0` and all peaks are added via
`aggregator.addPeak(mzs[p], intensities[p], scan_ids[p])`, simply increment
`contributing_frames` once for that non-empty frame (e.g. replace the
`frame_contributed` declaration, loop body, and `if (frame_contributed)
++contributing_frames;` with the same loop that calls `aggregator.addPeak(...)`
and then `++contributing_frames;`). This removes the unused `frame_contributed`
symbol and keeps behavior identical.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 32018635-6963-4bfa-8e3b-3d260d804906
📒 Files selected for processing (5)
CHANGELOGsrc/openms/include/OpenMS/FORMAT/BrukerTimsFile.hsrc/openms/source/FORMAT/BrukerTimsFile.cppsrc/tests/class_tests/openms/source/BrukerTimsFile_test.cppsrc/topp/FileConverter.cpp
The FrameCentroider had a hardcoded MAX_CENTROID_PEAKS=10000 cap that silently dropped up to 68% of intensity on aggregated MS1 surveys (flagged by Codex review of PR #9158). Exposing the cap as a knob and raising the default to 100000 makes the loss recoverable. Changes: - New Config::ms1_centroid_max_peaks field (default 100000). - New CLI option -bruker:ms1_centroid_max_peaks (default 100000, min 1). - Plumbed through FileConverter::getBrukerConfig_. - FrameCentroider::centroid() signature accepts max_peaks parameter; default constant renamed to DEFAULT_CENTROID_MAX_PEAKS (=10000). - FrameCentroider tracks cap-hit count + max dropped-peak intensity per load; reportCapSummary() emits ONE summary WARN per load() (not one per spectrum). Warning only fires when dropped peaks are above noise floor (>200 intensity counts). - reportCapSummary() called at the end of loadDIA_, loadDDA_, loadDIAStreaming, and loadFrames_ level-1 loops. On the DIA test fixture: at the 100k default the cap is hit on ~97% of spectra but only noise-floor peaks are dropped, so the summary warning stays silent. Intensity retention jumps from 32% (at 10k) to 70% (at 100k). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
All four comments were Minor but legitimate: 1. CHANGELOG used an ambiguous "ms1_centroid_mz_ppm/pct" shorthand. Spell out both identifiers explicitly, plus the new ms1_centroid_max_peaks knob. 2. FRAME mode test locked only spectrum count. A silent content corruption (e.g. aggregation partially running but writing to per-frame output) would pass. Now also asserts peak count and cumulative intensity equality between ref and agg runs. 3. DIA MS1 streaming aggregation test only asserted the cadence invariant (meta.nr_ms1_spectra), which is independent of whether ms1_n_neighbors is honored at all. Now also runs a non-aggregated streaming baseline and asserts total MS1 peaks(agg) > peaks(ref) — proof that aggregation actually ran. Also replaces swath_maps.front() with a proper m.ms1-flag lookup. 4. -bruker:ms1_min_support accepted any non-negative integer, but in a 3x3 grid with center excluded the max possible neighbors is 8. Added setMaxInt_(..., 8); values >8 are now rejected at the CLI boundary instead of silently dropping every peak. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The aggregator is scope-agnostic (no SWATH assumptions inside; the MS2 scan-window filter lives in the outer loop, not the class). Renaming prepares for reuse from the MS1 aggregation path. Pure refactor: no behavior change. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Lift MZ_BIN_WIDTH from static constexpr to a constructor parameter. Default 0.02 Da preserves existing MS2 behavior; MS1 callers will pass a smaller value (0.01 Da) tuned for timsTOF MS1 mass accuracy. Pure refactor: no behavior change. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…an_id=0 finalize() and finalizeCentroided() compute scan_id + ds and mz_bin + dm with negative offsets. When either axis is 0 and the offset is negative, the unsigned arithmetic wraps to 0xFFFFFFFF and hits phantom cells. Latent in MS2 (edge scans rare), but exposed at MS1 density where peaks at scan_id == 0 are common. Fixed at all five negative-offset lookup sites via a shared neighborKey() helper that returns std::nullopt on wrap. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…r loops Previously skip_denoise was based on the index span (hi - lo), which could run denoising when neighbor frames existed in the range but contributed no peaks after the SWATH-window filter. Now the outer loop counts frames that actually added peaks to the grid, and uses that as the denoise predicate. Closes the pre-existing TODO from #9151 and prepares the same logic for reuse in the upcoming MS1 aggregation path. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The upcoming MS1 aggregation path sums per-peak intensities across adjacent frames into FrameAggregator::Cell::intensity_sum (double). For MS1 with N=2 and a 10^9-intensity base peak, the sum reaches 5*10^9 and overflows uint32_t. Internal storage is already float (ImsPeak::intensity), so the new overload just casts double->float at the entry point. The existing uint32_t overload is untouched; MS2 callers see no change. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Plumb three new knobs for Bruker MS1 frame aggregation through the Config struct and the FileConverter CLI. The library side is wired up in follow-up commits; this commit is purely surface-level and has no runtime effect (defaults 0/0.0 preserve existing behavior). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Locks in the "zero behavior change at defaults" guarantee for the
upcoming MS1 frame aggregation feature. Snapshots MS1 spectrum count,
peak count, and cumulative intensity with Config{} defaults, and
independently reproduces with the new knobs explicitly set to 0 /
0.0 — asserts both paths produce identical numbers.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Asserts that ms1_n_neighbors=1 produces an intensity-boosted MS1 output relative to the raw per-frame path. Fails until loadAggregatedMS1Spectrum is implemented (next task). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add loadAggregatedMS1Spectrum() helper that builds one aggregated MS1 spectrum per center frame from a sliding window of 2N+1 adjacent MS1 frames, using FrameAggregator with a 0.01 Da bin (finer than the MS2 default). Composes with FrameCentroider for within-frame IM centroiding when ms1_centroid_mz_ppm/pct are set. Wires the new helper into loadDIA_ via an explicit branch on config.ms1_n_neighbors > 0, preserving the per-frame code path when aggregation is disabled. Also adds FrameAggregator::reserve() to pre-size the grid bucket array (MS1 grids reach ~300k cells per center at 0.01 Da bins on dense diaPASEF MS1). DIA MS1 aggregation test bounds re-tuned to [2.5, 3.1] — MS1 ion populations are more stable across adjacent frames than MS2 fragments, so 3-frame aggregation gives close to the naive 3x sum (empirical 2.99) rather than MS2's ~1.28x. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Extend the ms1_n_neighbors dispatch to loadDDA_ and add a DDA-specific test section validating both the aggregation intensity boost and the ms1_max_rt_distance_sec cap's ability to truncate the neighbor window on irregular DDA frame cadences. The STATUS line reports cap_reduction so future test-runners can re-tune the cap if the fixture's MS1 cadence changes. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Extend the ms1_n_neighbors dispatch to loadDIAStreaming so OpenSwath consumers see an aggregated MS1 survey when requested. Preserves the per-center-frame cadence invariant that SwathFileConsumer relies on. Adds a streaming-specific test section validating spectrum count equality with the raw MS1 frame count. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Four new test sections exercising every leaf of the MS1 aggregation feature: - DIA MS1 aggregation with centroiding test — confirms composition with FrameCentroider. Centroider caps output at MAX_CENTROID_PEAKS=10000 per frame, so on dense MS1 surveys (~600k aggregated peaks/frame) the top 10k carry ≈0.32 of total intensity. Bounds [0.1, 1.0] accept this. - DIA MS1 aggregation min_support test — confirms denoise works: drop_frac ≈ 0.52, intensity still 1.8× raw (signal peaks survive). - DIA MS1 RT cap test — 0.5s cap at N=2 reduces intensity by 80% (DIA MS1 cadence ~1.5s; tight cap collapses the window to just the center frame, so intensity goes from 5x raw down to 1x raw). - FRAME mode ignores ms1_n_neighbors test — FRAME export emits one spectrum per raw MS1 frame regardless of the aggregation knob. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- loadFrames_: warn when ms1_n_neighbors > 0 in FRAME export mode, proceed per-frame (preserves FRAME's "raw frames" contract). - warnPartialMS1AggregationConfig(): one-shot warnings for three cases: - ms1_min_support > 0 with ms1_n_neighbors == 0 (knob inert) - ms1_max_rt_distance_sec > 0 with ms1_n_neighbors == 0 (knob inert) - 2*N+1 > ms1_frame_count (window clamped at run edges) Called from loadDIA_, loadDDA_, and loadDIAStreaming after ms1_frame_ids is populated. Mirrors the existing isCentroidingEnabled partial-config warn pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The FrameCentroider had a hardcoded MAX_CENTROID_PEAKS=10000 cap that silently dropped up to 68% of intensity on aggregated MS1 surveys (flagged by Codex review of PR #9158). Exposing the cap as a knob and raising the default to 100000 makes the loss recoverable. Changes: - New Config::ms1_centroid_max_peaks field (default 100000). - New CLI option -bruker:ms1_centroid_max_peaks (default 100000, min 1). - Plumbed through FileConverter::getBrukerConfig_. - FrameCentroider::centroid() signature accepts max_peaks parameter; default constant renamed to DEFAULT_CENTROID_MAX_PEAKS (=10000). - FrameCentroider tracks cap-hit count + max dropped-peak intensity per load; reportCapSummary() emits ONE summary WARN per load() (not one per spectrum). Warning only fires when dropped peaks are above noise floor (>200 intensity counts). - reportCapSummary() called at the end of loadDIA_, loadDDA_, loadDIAStreaming, and loadFrames_ level-1 loops. On the DIA test fixture: at the 100k default the cap is hit on ~97% of spectra but only noise-floor peaks are dropped, so the summary warning stays silent. Intensity retention jumps from 32% (at 10k) to 70% (at 100k). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
All four comments were Minor but legitimate: 1. CHANGELOG used an ambiguous "ms1_centroid_mz_ppm/pct" shorthand. Spell out both identifiers explicitly, plus the new ms1_centroid_max_peaks knob. 2. FRAME mode test locked only spectrum count. A silent content corruption (e.g. aggregation partially running but writing to per-frame output) would pass. Now also asserts peak count and cumulative intensity equality between ref and agg runs. 3. DIA MS1 streaming aggregation test only asserted the cadence invariant (meta.nr_ms1_spectra), which is independent of whether ms1_n_neighbors is honored at all. Now also runs a non-aggregated streaming baseline and asserts total MS1 peaks(agg) > peaks(ref) — proof that aggregation actually ran. Also replaces swath_maps.front() with a proper m.ms1-flag lookup. 4. -bruker:ms1_min_support accepted any non-negative integer, but in a 3x3 grid with center excluded the max possible neighbors is 8. Added setMaxInt_(..., 8); values >8 are now rejected at the CLI boundary instead of silently dropping every peak. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1f4a99d to
d4d8e84
Compare
Summary
Adds cross-frame aggregation for Bruker timsTOF MS1 survey frames in
BrukerTimsFile. Sums peaks from 2N+1 adjacent MS1 frames into a sparse(mz_bin, scan_id)grid per center frame, composable with the existing within-frame IM centroiding (FrameCentroider, adapted from Sage). Applies to both DIA-PASEF and DDA-PASEF.Mirrors the existing DIA MS2 aggregation feature (#9129) and reuses the same aggregator class, renamed
DIAFrameAggregator→FrameAggregatorto reflect its true generality.User-facing surface
Three new
-bruker:options inFileConverter(alladvanced):All defaults are 0/0.0 — zero behavior change at defaults (locked in by a dedicated regression test).
Corresponding fields added to
BrukerTimsFile::Configwith the same defaults.Design & review trail
docs/superpowers/specs/2026-04-15-bruker-ms1-frame-aggregation-design.md— went through a 10-agent multi-lens review plus a Codex cross-check; all findings folded in (audit trail at the bottom of the spec).docs/superpowers/plans/2026-04-15-bruker-ms1-frame-aggregation.md— 17 tasks, one commit per task, executed under subagent-driven development.Phase-A shared-code prep (5 commits)
Strictly-additive changes that benefit the pre-existing MS2 aggregation too:
DIAFrameAggregator→FrameAggregatorMZ_BIN_WIDTHvia constructor (default0.02for MS2,0.01for MS1)scan_id/mz_binunsigned wrap in all 5 negative-offset neighbor lookups via a sharedneighborKey()helper (closes a latent MS2 bug exposed more at MS1 density)skip_denoise = (hi - lo) < 1withcontributing_frames <= 1in the MS2 aggregation loop (closes pre-existing TODO flagged on feat: allow Bruker DIA MS2 centroiding without denoising #9151)FrameCentroider::loadFrame(const double*)overload (avoids uint32 overflow on summed MS1 intensities)Phase-B feature (9 commits)
loadAggregatedMS1Spectrum()helperloadDIA_,loadDDA_, andloadDIAStreamingviaif (config.ms1_n_neighbors > 0) { ... } else { loadMS1Spectrum(...) }dispatchCHANGELOGentryEmpirical behavior on fixtures
Test Plan
BrukerTimsFile_testpass on DIA + DDA fixtures (16 new — default-config regression, DIA aggregation, DIA+centroiding, DIA min_support, DIA RT cap, DIA streaming, DDA aggregation + RT cap, FRAME warn-and-ignore — plus 14 pre-existing unchanged)FileConverter --helphelpshows the 3 new options with correct(default: '0') (min: '0')/(max: '50')metadataPASSED🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Behavior