Skip to content

fix: BrukerTimsFile::loadDIAStreaming must sort peaks by m/z (#9134) - #9135

Merged
timosachsenberg merged 3 commits into
developfrom
fix/bruker-dia-streaming-unsorted-peaks
Apr 12, 2026
Merged

timosachsenberg merged 3 commits into
developfrom
fix/bruker-dia-streaming-unsorted-peaks

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9134.

Summary

OpenSwathWorkflow crashes on Bruker .d input with Error: Unexpected internal error (There were not enough bins with the minimal number of peptides) during iRT calibration, while the same dataset converted to .mzML works fine. The .d path produces only ~41% of the chromatograms the .mzML path does, with massive Detected N empty chromatograms warnings (thousands per SWATH window) during Linear Calibration.

Root cause

BrukerTimsFile::loadDIAStreaming() (PR #9129) feeds spectra directly to FullSwathFileConsumer::consumeSpectrum() 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 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

Path Sort step Status
load() → loadDIA_() → in-memory MSExperiment exp.sortSpectra(true) called at end of load() ✅ sorted
transform() → loadDIA_() → consumer exp.sortSpectra(true) called before feeding consumer ✅ sorted
loadBrukerTdf() → loadDIAStreaming() → consumer no sort step ❌ unsorted — this bug

MSExperiment::sortSpectra(true) at MSExperiment.cpp:792-804 calls sortByPosition() on each spectrum, which sorts peaks by m/z and permutes the associated FloatDataArray (IM data) alongside — so the peak ↔ IM mapping is preserved.

Fix

Call spec.sortByPosition() immediately before each consumer.consumeSpectrum() in loadDIAStreaming(), for both the MS1 and MS2 emission loops. Two one-line additions plus comments explaining why. Verified via MSSpectrum.cpp:36-56 that sortByPosition() correctly permutes the FloatDataArray (IM data) alongside the peaks.

Debugging trail

Observations from the user's logs:

Metric .mzML (works) .d (crashes) Ratio
MS1 spectra 2512 2512 1.00
SWATH windows 24 24 1.00
Chromatograms stored (Linear Calibration) 37715 15467 0.41
Peptides analyzed 6287 4084 0.65
Empty chromatograms per Linear Calibration batch 1–2 54–1706 ~1000×

Same input file (both derived from the same acquisition), same iRT library, same SWATH boundaries, but the .d path 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

  • Local build clean on Linux x86_64
  • Existing BrukerTimsFile_test (exercising load() / loadDIA_(), not loadDIAStreaming()) still passes after the fix — 522 s runtime, no regressions
  • End-to-end verification: user re-runs OpenSwathWorkflow on their .d dataset and confirms iRT calibration no longer fails (waiting on user to test)

Follow-up

The existing loadDIAStreaming test (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

    • Ensured consistent peak ordering in DIA streaming so spectra and associated ion-mobility data are position-sorted for reliable downstream range queries.
  • Improvements

    • Added an aggregated QC log after iRT chromatogram extraction that warns when many chromatograms are empty and reports empty/non-empty ratios.
    • Improved iRT calibration failure messages to include detailed, actionable diagnostics and counts for easier troubleshooting.

… 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]>
@coderabbitai

coderabbitai Bot commented Apr 11, 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: d357a7b8-9b3e-4b26-93e6-51f1c90411a1

📥 Commits

Reviewing files that changed from the base of the PR and between ea35c43 and 39d5eb6.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/OPENSWATH/CalibrationWorkflow.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/openms/source/ANALYSIS/OPENSWATH/CalibrationWorkflow.cpp

📝 Walkthrough

Walkthrough

Added 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

Cohort / File(s) Summary
BrukerTimsFile DIA streaming
src/openms/source/FORMAT/BrukerTimsFile.cpp
Inserted spec.sortByPosition() in the DIA MS1 streaming loop (post-centroiding/frameToSpectrum) and in the DIA MS2 raw path (after IM-range filtering and IM array set) to guarantee spectra and IM arrays are position-sorted for downstream range queries.
iRT calibration logging & errors
src/openms/source/ANALYSIS/OPENSWATH/CalibrationWorkflow.cpp
Added aggregated QC log after iRT chromatogram extraction (counts empty chromatograms, warns if >50% empty); replaced two generic iRT-calibration failure exceptions with detailed, parameterized messages (counts before/after outlier removal, required bins/peptides, RT range, and common-cause hints).

Possibly related issues

Possibly related PRs

Suggested reviewers

  • jcharkow
  • jpfeuffer

Poem

🐰 I nibbled through the messy rows,
Sorted peaks where wild wind blows.
iRTs counted, warnings clear,
Errors tell the tale, not fear.
Hop—now data dances near! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 describes the main change: adding m/z sorting to BrukerTimsFile::loadDIAStreaming, which is the primary fix addressing the crash in issue #9134.
Linked Issues check ✅ Passed The PR directly addresses issue #9134 by identifying unsorted peaks as the root cause and implementing the required fix (spec.sortByPosition calls in both MS1 and MS2 loops) to resolve the chromatogram extraction failures.
Out of Scope Changes check ✅ Passed The CalibrationWorkflow.cpp changes (QC logging for empty chromatograms and improved error messages) are complementary improvements that enhance diagnostics for the iRT calibration failures, which directly support the primary fix's validation.

✏️ 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 fix/bruker-dia-streaming-unsorted-peaks

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/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_test case that validates spectra emitted via loadDIAStreaming() 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

📥 Commits

Reviewing files that changed from the base of the PR and between f8f56fd and deb2c1d.

📒 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]>

@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 (2)
src/openms/source/ANALYSIS/OPENSWATH/CalibrationWorkflow.cpp (2)

406-417: Avoid sticky iostream formatting and std::endl in OpenMS logs.

std::fixed/std::setprecision can persist on the log stream and unintentionally affect later numeric logs; also std::endl is 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::String for numeric formatting and parsing (precision and speed)" and "Avoid std::endl for performance reasons; prefer \n in 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, prefer Int/Size over raw int for 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.h instead 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

📥 Commits

Reviewing files that changed from the base of the PR and between deb2c1d and ea35c43.

📒 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"

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.

Sound confusing if it is fixed now..

@timosachsenberg
timosachsenberg merged commit cac0b8a into develop Apr 12, 2026
14 checks passed
@timosachsenberg
timosachsenberg deleted the fix/bruker-dia-streaming-unsorted-peaks branch April 12, 2026 08:34
github-actions Bot pushed a commit that referenced this pull request Apr 13, 2026
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]>
timosachsenberg pushed a commit that referenced this pull request Apr 13, 2026
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]>
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.

OpenSwathWorkflow with .d is crashing (and mzML is fine)

2 participants