Repository navigation
fix: BrukerTimsFile::loadDIAStreaming must sort peaks by m/z (#9134) - #9135
Conversation
… by m/z Discovered while debugging issue #9134: OpenSwathWorkflow crashes on .d input with "not enough bins with the minimal number of peptides" during iRT calibration, while the same dataset converted to .mzML works fine. The .d path produced only ~41% of the chromatograms the mzML path did, with massive "Detected N empty chromatograms" warnings during Linear Calibration (thousands per SWATH window). Root cause: loadDIAStreaming() feeds spectra directly to the FullSwathFileConsumer without sorting each spectrum's peaks by m/z. TIMS save_to_buffs() returns peaks in (scan_id, m/z-within-scan) order, which is NOT globally m/z-sorted — across scan_ids the m/z values oscillate. OpenSwath's chromatogram extraction uses lower_bound / upper_bound on each spectrum's peak list for m/z range queries (standard mzML convention assumes sorted peaks), so unsorted input silently returns no matches, producing empty chromatograms across iRT peptides and breaking the iRT calibration's minimum-bin check. The in-memory load() path (used by loadDIA_()) dodged this by calling MSExperiment::sortSpectra(true) at the end of load(), which sorts each spectrum's peaks via MSSpectrum::sortByPosition(). The transform() path (consumer-based but non-streaming) also calls sortSpectra(true) before feeding to the consumer. Only loadDIAStreaming() — the path used by SwathFile::loadBrukerTdf() for OpenSwathWorkflow with .d input — bypassed the sort entirely. Fix: call spec.sortByPosition() immediately before consumer.consumeSpectrum() in both the MS1 and MS2 emission loops. sortByPosition() correctly permutes the associated FloatDataArray (IM data) alongside the peaks (MSSpectrum.cpp:36-56), so the peak ↔ IM mapping stays intact. Existing BrukerTimsFile_test still passes (the DIA MS2 aggregation test exercises loadDIA_, not loadDIAStreaming — the existing test coverage doesn't catch this bug because loadDIAStreaming's own test only checks spectrum counts and metadata, not m/z ordering). End-to-end verification will come when the user re-runs OpenSwathWorkflow on their .d dataset. Fixes #9134. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
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 (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdded spectrum position-sorting in BrukerTimsFile DIA streaming to ensure m/z/position-ordered peaks and aligned IM arrays; added aggregated iRT chromatogram extraction QC logs and more detailed, parameterized exception messages in iRT calibration paths. Changes
Possibly related issues
Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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.
🧹 Nitpick comments (1)
src/openms/source/FORMAT/BrukerTimsFile.cpp (1)
1133-1141: Add a regression test for DIA streaming peak ordering.The fix is correct, but this exact failure mode is still unguarded. Please add a
BrukerTimsFile_testcase that validates spectra emitted vialoadDIAStreaming()are m/z-sorted (and IM array length remains aligned with peaks) before downstream extraction.🤖 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 1133 - 1141, Add a regression test named BrukerTimsFile_test that loads a DIA streaming file via BrukerTimsFile::loadDIAStreaming (or the test harness that exercises the streaming path), iterates emitted spectra passed to the consumer (the same callback used by loadDIAStreaming), and asserts for each spectrum that peaks are globally m/z-sorted (monotonic non-decreasing m/z) and that the IM float array length matches the number of peaks; reuse the existing behavior where spec.sortByPosition() was added as the expected outcome and fail the test if any spectrum violates sorted order or misaligned IM array lengths.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/openms/source/FORMAT/BrukerTimsFile.cpp`:
- Around line 1133-1141: Add a regression test named BrukerTimsFile_test that
loads a DIA streaming file via BrukerTimsFile::loadDIAStreaming (or the test
harness that exercises the streaming path), iterates emitted spectra passed to
the consumer (the same callback used by loadDIAStreaming), and asserts for each
spectrum that peaks are globally m/z-sorted (monotonic non-decreasing m/z) and
that the IM float array length matches the number of peaks; reuse the existing
behavior where spec.sortByPosition() was added as the expected outcome and fail
the test if any spectrum violates sorted order or misaligned IM array lengths.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f6e45bf9-cf9a-4cb1-a830-f643c7cd5c48
📒 Files selected for processing (1)
src/openms/source/FORMAT/BrukerTimsFile.cpp
The error message "There were not enough bins with the minimal number of
peptides" gives users no diagnostic value — they can't tell whether the
problem is the library, the data, or a loading bug.
Two improvements:
1. The error message now includes all diagnostic state available at the
throw point: chromatogram count, iRT peptide matches before and after
outlier removal, binning requirements (NrRTBins, MinPeptidesPerBin,
MinBinsFilled), RT range, and a checklist of common causes. Example:
iRT calibration failed: insufficient RT coverage after outlier removal.
Chromatograms extracted: 15467
iRT peptides matched: 4084 (before outlier removal)
After outlier removal: 312 (exp_RT, theor_RT) pairs
Binning requires: 80/100 RT bins with >= 5 peptides each
RT range: 120.3 - 3600.1 s
Common causes:
- Too few iRT/CiRT peptides in the transition library
- Low data quality (check the 'Detected N empty chromatograms' warnings)
- Input spectra with unsorted m/z peaks (e.g. Bruker .d via streaming)
- Wrong SWATH window boundaries
2. A summary log line after iRT chromatogram extraction in
performRTNormalization() reports the non-empty/total ratio:
[OpenSwath] iRT chromatogram extraction: 15467/37715 non-empty (41.0%).
Over half are empty - iRT calibration may fail. Common causes: ...
This fires BEFORE the calibration attempts to use the chromatograms,
giving users an immediate signal that something is wrong with the
chromatogram extraction — without having to scroll through dozens of
per-batch "Detected N empty chromatograms" warnings.
Also improves the "less than 2 iRT normalization peptides" error (line 571)
with the same diagnostic numbers.
Part of #9134 (OpenSwathWorkflow .d crash).
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/openms/source/ANALYSIS/OPENSWATH/CalibrationWorkflow.cpp (2)
406-417: Avoid sticky iostream formatting andstd::endlin OpenMS logs.
std::fixed/std::setprecisioncan persist on the log stream and unintentionally affect later numeric logs; alsostd::endlis discouraged in this codebase.♻️ Proposed fix
+ const double nonempty_pct = 100.0 * static_cast<double>(nr_nonempty) / static_cast<double>(nr_total); + const String nonempty_pct_str(nonempty_pct, 1); if (nr_total > 0 && nr_empty > nr_total / 2) { OPENMS_LOG_WARN << "[OpenSwath] iRT chromatogram extraction: " << nr_nonempty << "/" - << nr_total << " non-empty (" << std::fixed << std::setprecision(1) - << (100.0 * nr_nonempty / nr_total) << "%). " + << nr_total << " non-empty (" << nonempty_pct_str << "%). " << "Over half are empty - iRT calibration may fail. " << "Common causes: wrong SWATH boundaries, poor data quality, " - << "or unsorted m/z peaks in the input spectra." << std::endl; + << "or unsorted m/z peaks in the input spectra.\n"; } else if (nr_total > 0) { OPENMS_LOG_INFO << "[OpenSwath] iRT chromatogram extraction: " << nr_nonempty << "/" - << nr_total << " non-empty (" << std::fixed << std::setprecision(1) - << (100.0 * nr_nonempty / nr_total) << "%)" << std::endl; + << nr_total << " non-empty (" << nonempty_pct_str << "%)\n"; }As per coding guidelines, "Prefer
OpenMS::Stringfor numeric formatting and parsing (precision and speed)" and "Avoidstd::endlfor performance reasons; prefer\nin C++".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/OPENSWATH/CalibrationWorkflow.cpp` around lines 406 - 417, Replace the iostream manipulators and std::endl in the OPENMS_LOG_WARN / OPENMS_LOG_INFO messages inside CalibrationWorkflow (the block that logs "[OpenSwath] iRT chromatogram extraction...") by formatting the percentage and any decimals with OpenMS::String::number (specify precision there) and use '\n' instead of std::endl; in other words, compute a String percent = OpenMS::String::number(100.0 * nr_nonempty / nr_total, 1) and insert that into the OPENMS_LOG_* stream, and remove all std::fixed/std::setprecision and std::endl so no sticky stream state is left behind.
593-595: Use OpenMS integral types for newly introduced calibration counters.In
src/openms, preferInt/Sizeover rawintfor consistency with OpenMS type conventions.♻️ Proposed fix
- const int nr_bins = irt_detection_param.getValue("NrRTBins"); - const int min_pep = irt_detection_param.getValue("MinPeptidesPerBin"); - const int min_filled = irt_detection_param.getValue("MinBinsFilled"); + const Int nr_bins = irt_detection_param.getValue("NrRTBins"); + const Int min_pep = irt_detection_param.getValue("MinPeptidesPerBin"); + const Int min_filled = irt_detection_param.getValue("MinBinsFilled");As per coding guidelines, "Use OpenMS primitive types from
OpenMS/CONCEPT/Types.hinstead of standard C++ types".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/OPENSWATH/CalibrationWorkflow.cpp` around lines 593 - 595, The three new calibration counter variables (nr_bins, min_pep, min_filled) are declared as raw int; change them to OpenMS primitive types to follow project conventions: use Size for non-negative counts like nr_bins and min_filled and use Int for MinPeptidesPerBin (min_pep). Update the declarations of nr_bins, min_pep, and min_filled to use OpenMS::Size and OpenMS::Int respectively (or the unscoped typedefs Size/Int), and ensure OpenMS/CONCEPT/Types.h is included if not already.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/openms/source/ANALYSIS/OPENSWATH/CalibrationWorkflow.cpp`:
- Around line 406-417: Replace the iostream manipulators and std::endl in the
OPENMS_LOG_WARN / OPENMS_LOG_INFO messages inside CalibrationWorkflow (the block
that logs "[OpenSwath] iRT chromatogram extraction...") by formatting the
percentage and any decimals with OpenMS::String::number (specify precision
there) and use '\n' instead of std::endl; in other words, compute a String
percent = OpenMS::String::number(100.0 * nr_nonempty / nr_total, 1) and insert
that into the OPENMS_LOG_* stream, and remove all std::fixed/std::setprecision
and std::endl so no sticky stream state is left behind.
- Around line 593-595: The three new calibration counter variables (nr_bins,
min_pep, min_filled) are declared as raw int; change them to OpenMS primitive
types to follow project conventions: use Size for non-negative counts like
nr_bins and min_filled and use Int for MinPeptidesPerBin (min_pep). Update the
declarations of nr_bins, min_pep, and min_filled to use OpenMS::Size and
OpenMS::Int respectively (or the unscoped typedefs Size/Int), and ensure
OpenMS/CONCEPT/Types.h is included if not already.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 4f07ab22-bab5-4d34-a831-273b50fda54b
📒 Files selected for processing (1)
src/openms/source/ANALYSIS/OPENSWATH/CalibrationWorkflow.cpp
| "Common causes:\n" | ||
| " - Too few iRT/CiRT peptides in the transition library for the LC gradient\n" | ||
| " - Low data quality (check the 'Detected N empty chromatograms' warnings above)\n" | ||
| " - Input spectra with unsorted m/z peaks (e.g. Bruker .d loaded via streaming)\n" |
There was a problem hiding this comment.
Sound confusing if it is fixed now..
Add missing entries for changes merged after last changelog sync (#9131): - BREAKING: ProSE tool renamed from PeptideDataBaseSearchFI (#9137) - Add #9132 reference to asymmetric precursor tolerance entry (#9108, #9132) - Fix: BrukerTimsFile::loadDIAStreaming m/z sort for OpenSwath DIA streaming (#9135) Co-authored-by: Copilot <[email protected]>
Add missing entries for changes merged after last changelog sync (#9131): - BREAKING: ProSE tool renamed from PeptideDataBaseSearchFI (#9137) - Add #9132 reference to asymmetric precursor tolerance entry (#9108, #9132) - Fix: BrukerTimsFile::loadDIAStreaming m/z sort for OpenSwath DIA streaming (#9135) Co-authored-by: GitHub Copilot <[email protected]> Co-authored-by: Copilot <[email protected]>
Fixes #9134.
Summary
OpenSwathWorkflow crashes on Bruker
.dinput withError: Unexpected internal error (There were not enough bins with the minimal number of peptides)during iRT calibration, while the same dataset converted to.mzMLworks fine. The.dpath produces only ~41% of the chromatograms the.mzMLpath does, with massiveDetected N empty chromatogramswarnings (thousands per SWATH window) during Linear Calibration.Root cause
BrukerTimsFile::loadDIAStreaming()(PR #9129) feeds spectra directly toFullSwathFileConsumer::consumeSpectrum()without sorting each spectrum's peaks by m/z. TIMSsave_to_buffs()returns peaks in(scan_id, m/z-within-scan)order, which is not globally m/z-sorted — across scan_ids the m/z values oscillate.OpenSwath's chromatogram extraction uses
lower_bound/upper_boundon each spectrum's peak list to perform m/z-range queries (standard mzML convention assumes sorted peaks). Unsorted input silently returns no matches → empty chromatograms across iRT peptides → iRT calibration's minimum-bin check fails → crash.Why the other paths don't hit this
load()→loadDIA_()→ in-memoryMSExperimentexp.sortSpectra(true)called at end ofload()transform()→loadDIA_()→ consumerexp.sortSpectra(true)called before feeding consumerloadBrukerTdf()→loadDIAStreaming()→ consumerMSExperiment::sortSpectra(true)atMSExperiment.cpp:792-804callssortByPosition()on each spectrum, which sorts peaks by m/z and permutes the associatedFloatDataArray(IM data) alongside — so the peak ↔ IM mapping is preserved.Fix
Call
spec.sortByPosition()immediately before eachconsumer.consumeSpectrum()inloadDIAStreaming(), for both the MS1 and MS2 emission loops. Two one-line additions plus comments explaining why. Verified viaMSSpectrum.cpp:36-56thatsortByPosition()correctly permutes theFloatDataArray(IM data) alongside the peaks.Debugging trail
Observations from the user's logs:
.mzML(works).d(crashes)Same input file (both derived from the same acquisition), same iRT library, same SWATH boundaries, but the
.dpath loses ~59% of chromatograms because downstream m/z-range queries on unsorted spectra miss their targets. The spectrum COUNT is correct; each SwathMap receives its full complement of spectra. Only the peak ORDER inside each spectrum is wrong.Test plan
BrukerTimsFile_test(exercisingload()/loadDIA_(), notloadDIAStreaming()) still passes after the fix — 522 s runtime, no regressionsOpenSwathWorkflowon their.ddataset and confirms iRT calibration no longer fails (waiting on user to test)Follow-up
The existing
loadDIAStreamingtest (added in PR #9129) only checks spectrum counts and basic metadata, not m/z ordering — which is why this bug wasn't caught by CI. Worth adding a regression test that asserts spectrum peaks are monotonically m/z-sorted after streaming, but that's a small follow-up rather than a blocker.🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Improvements