Skip to content

feat: Bruker DDA native ID + load_ms1 toggle + CometAdapter mzParser workaround - #9160

Merged
timosachsenberg merged 10 commits into
developfrom
feat/bruker-dda-native-id-and-ms1-skip
Apr 16, 2026
Merged

timosachsenberg merged 10 commits into
developfrom
feat/bruker-dda-native-id-and-ms1-skip

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Three tightly-related Bruker-pipeline improvements in one PR:

  1. DDA MS2 native IDs now use the PSI-MS CV-compliant format frame=<frame_id> scan=<scan_begin> (MS:1002818 — Bruker TDF nativeID format), matching DIA convention. The TIMS isolation-window scan_begin is physically meaningful for downstream cross-reference. The Bruker Precursors.Id SQL key is preserved as a per-spectrum MetaValue bruker_precursor_id so no information is lost.
  2. New Config::load_ms1 / -bruker:load_ms1 toggle (default true). Skip MS1 loading entirely for MS2-only workflows (peptide database search) — cuts memory and time substantially. CometAdapter automatically sets load_ms1=false for MS2 searches.
  3. CometAdapter workaround for a latent segfault in Comet's bundled mzParser when reading mzML files with mixed frame=... and scan=... native IDs producing overlapping numeric scan-index values — exactly the Bruker DDA case.

Background — the mzParser segfault

Comet ships mzParser which extracts a scan-index sort key via substring match on scan= anywhere in the native ID, then atoi on the following digits. When resulting scanNum values are not monotonic, it falls into std::sort using cindex::compare:

static bool compare(cindex& a, cindex& b) {
  if (a.scanNum > b.scanNum) return false;
  if (a.scanNum < b.scanNum) return true;
  return true;   // ← violates strict-weak-ordering → std::sort UB
}

Bruker MS1s go through mzParser's counter path (values 1..N); DDA MS2s go through atoi with small TIMS scan indices that overlap → compare returns true for equal values → UB → segfault in std::string idRef shuffling. (tdf2mzml sidesteps this by emitting only index=N, which keeps mzParser on the counter path.)

Fix approach

BrukerTimsFile — CV-compliant native ID + precursor as MetaValue

Change DDA MS2 setNativeID("scan=" + String(prec_id)) to:

spec.setNativeID("frame=" + String(first_entry->frame_id)
                 + " scan=" + String(first_entry->scan_begin));
spec.setMetaValue("bruker_precursor_id", static_cast<int>(prec_id));

Strict CV compliance (MS:1002818 mandates frame=<FRAME_ID> scan=<SCAN_ID>), matches DIA MS2 convention, and the SQL key stays accessible.

BrukerTimsFile — load_ms1 toggle

New Config::load_ms1 bool (default true). Wired into loadDIA_, loadDDA_, loadDIAStreaming, and loadFrames_ (level==1). Progress bar totals and reserveSpaceSpectra adjusted accordingly. Partial-config warning fires if load_ms1=false + ms1_n_neighbors>0 (inconsistent).

CometAdapter — rewrite + translate

  1. Before writing the temp mzML: rewrite every native ID to index=N (monotonic counter). Original ID preserved as spec.setMetaValue("original_native_id", ...).
  2. Comet reads/writes index=N consistently — mzParser takes the counter path, no sort, no UB.
  3. addMissingIMToPeptideIDs etc. run normally (both exp and pep.xml use the rewritten IDs, so the lookup still matches).
  4. After all annotation: translate PSM spectrum_reference back to original Bruker IDs via a one-pass hash map built from exp's original_native_id meta values.

CometAdapter sets bruker_config.load_ms1 = false for MS2 searches — Comet only needs MS2, loading MS1 was a waste.

Test Plan

  • BrukerTimsFile_test — 32/32 sections pass (two new):
    • DDA native ID format test — asserts native ID starts with frame=, contains scan=, does NOT contain precursor= (CV pattern compliance), and bruker_precursor_id exists as a MetaValue. Example: frame=2 scan=529 + bruker_precursor_id=3.
    • Bruker load_ms1=false test — DDA: raw 740/11172 MS1/MS2 → skipped 0/11172. DIA + FRAME also verified.
  • CometAdapter builds cleanly.
  • All 4 Unix CI jobs passed on the earlier push (Linux g++/clang++/arm, macOS xcode). Windows failed at Set Up Build Tools (chocolatey infra flake) — not code-related.
  • End-to-end verification with an actual .d DDA fixture through CometAdapter (requires Bruker SDK + .d file — not in CI, needs manual smoke test).

Review notes

CodeRabbit correctly flagged the initial frame=F scan=S precursor=P format as violating MS:1002818; fixed by moving the third component to a MetaValue. Commit 5b9fd0f79a addresses that review.

Upstream follow-up

Separately file an upstream bug on UWPR/Comet pointing at cindex::compare's strict-weak-ordering violation. The patch is trivial (return true → return false in the equal branch), but our workaround here is proactive until that merges.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • New Bruker option to skip MS1 loading for MS2-only workflows (bruker:load_ms1, CLI flag); MS2 searches auto-disable MS1.
    • Bruker MS2 native IDs now use PSI‑MS style frame/scan/precursor and store original precursor ID as spectrum metadata.
    • Native ID parsing extended to recognize frame= formats.
  • Bug Fixes

    • Prevent Comet crashes with mixed native ID formats by remapping IDs during search and restoring references.
  • Tests

    • Added integration tests and a regression check to verify native ID formatting, MS1‑skipping behavior, and PSM yield floors.

timosachsenberg and others added 3 commits April 16, 2026 16:44
Two related BrukerTimsFile changes:

1. DDA MS2 native IDs change from "scan=<precursor_id>" to
   "frame=<frame_id> scan=<scan_begin> precursor=<precursor_id>".
   Matches the DIA MS2 convention and carries all three physical
   identifiers (source frame, TIMS isolation-window start, Bruker
   Precursors.Id). Unblocks downstream cross-referencing and is the
   format mzParser/Comet require a workaround for (handled in
   CometAdapter).

2. New Config::load_ms1 bool (default true) + -bruker:load_ms1 CLI
   toggle. When false, MS1 spectra are not emitted to the MSExperiment
   or streaming consumer; applies to loadDIA_, loadDDA_, loadDIAStreaming,
   and loadFrames_ level==1. Partial-config warning fires if
   load_ms1=false combined with ms1_n_neighbors>0 (inconsistent).

Two new test sections:
- "DDA native ID format test" — asserts native ID carries frame=,
  scan=, precursor= components and starts with frame=.
- "Bruker load_ms1=false test" — asserts zero MS1 and unchanged MS2
  count for DDA, DIA, and FRAME export modes.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comet's bundled mzParser (MSToolkit/saxmzmlhandler.cpp) grep-matches
native IDs for "scan=" and uses atoi of the following digits as its
spectrum-index sort key. When Bruker DDA MS2 IDs of the form
"frame=F scan=S precursor=P" are written alongside MS1s that take
the counter path ("frame=F"), scanNum values can collide — and
cindex::compare() in MSToolkit/include/mzParser.h returns true for
equal elements, violating std::sort's strict-weak-ordering invariant.
The resulting UB manifests as a segfault during std::string shuffling
in the sort.

Workaround (upstream fix for cindex::compare should still be filed
against UWPR/Comet separately):

1. Before writing the temp mzML fed to Comet, rewrite every native ID
   to "index=N" (monotonic counter). mzParser routes these through
   its counter path — no sort, no UB. Original ID is preserved as a
   per-spectrum MetaValue.
2. Let Comet run normally; it emits pep.xml with the rewritten IDs.
3. After IM/FAIMS annotation (which operates on the rewritten IDs in
   both pep.xml and exp), translate PSM spectrum_reference values
   back to the original Bruker IDs via a rewritten→original map.

Also: default bruker_config.load_ms1=false when searching MS2. Comet
only needs MS2; loading MS1 just wastes memory and time. Can be
overridden via -bruker:load_ms1=true if the caller needs MS1 available
in `exp` for custom post-processing.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Bruker TimsTOF: MS2 nativeIDs now use PSI-MS-style frame=<frame_id> scan=<scan_begin> precursor=<precursor_id> with typed MetaValue bruker_precursor_id. Added BrukerTimsFile::Config::load_ms1 to optionally skip MS1 loading; CometAdapter rewrites nativeIDs to monotonic index=N for Comet and restores originals afterward.

Changes

Cohort / File(s) Summary
Bruker TimsTOF Core
src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h, src/openms/source/FORMAT/BrukerTimsFile.cpp
Added Config::load_ms1 (default true); gate MS1 emission/progress in DDA/DIA/streaming paths; change DDA MS2 nativeID to frame=… scan=… precursor=… and add typed MetaValue bruker_precursor_id; skip MS1 frames when load_ms1==false.
Tooling / Adapters
src/topp/FileConverter.cpp, src/topp/CometAdapter.cpp
Expose CLI bruker:load_ms1 and pass to BrukerTimsFile::Config; CometAdapter sets load_ms1=false for MS2-only runs, rewrites Bruker nativeIDs to monotonic index=N (stores original_native_id), runs Comet on index-based mzML, then remaps PSM spectrumReferences back to original nativeIDs.
Native ID Parsing
src/openms/source/METADATA/SpectrumNativeIDParser.cpp
Recognize frame=-prefixed nativeIDs as scan-bearing; add MS:1002818 accession support for scan extraction and regex construction.
Algorithmic tweak
src/openms/source/ANALYSIS/ID/ProSEAlgorithm.cpp
Swapped calculation for calibrated precursor error bounds in runCalibrationPass_ (reordered combination of shift/spread into raw lower/upper).
Tests & CI scripts
src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp, src/tests/topp/CMakeLists.txt, src/tests/topp/check_psm_floor.cmake
Added tests verifying new DDA nativeID format, bruker_precursor_id, uniqueness of MS2 nativeIDs, and load_ms1=false behavior; added PSM-floor CTest script and new guarded checks for FDR/ProSE DDA outputs.
Miscellaneous
src/topp/FileConverter.cpp (option plumbing), small comment/whitespace and progress reporting changes in multiple files
Plumbed new CLI option; adjusted progress/expected-size computations so MS1 contribution respects load_ms1; minor comment/whitespace updates.

Sequence Diagram

sequenceDiagram
    rect rgba(220,240,255,0.5)
    participant Loader as BrukerTimsFile Loader
    end
    rect rgba(200,255,220,0.5)
    participant Adapter as CometAdapter
    end
    rect rgba(255,230,220,0.5)
    participant Comet as Comet (mzParser)
    participant PSMs as PeptideIdentifications
    end

    Loader->>Adapter: Emit spectra (nativeIDs with frame/scan/precursor)
    Adapter->>Adapter: If Bruker .d & MS2 path:\nset load_ms1=false\nrewrite nativeID -> index=N\nstore original_native_id meta
    Adapter->>Comet: Run Comet on index-based mzML
    Comet->>PSMs: Return PSMs referencing index=N
    Adapter->>Adapter: Build map index→original_native_id
    Adapter->>PSMs: Translate PSM.spectrumReference → original_native_id
    Adapter->>Loader: Return corrected PSMs/results
Loading

Possibly related issues

Possibly related PRs

Suggested labels

Review effort 2/5, codex

Suggested reviewers

  • jcharkow
  • jpfeuffer

Poem

🐇
I hop through frames and scans so bright, a tiny metadata knight,
I tuck the precursor safe and sound where lookups find delight.
Skip MS1 when you ask me, I’ll keep MS2 on track,
I map indices back to truth, then nibble on a snack. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.41% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly summarizes the three main changes: Bruker DDA native ID format update, load_ms1 toggle feature, and CometAdapter mzParser workaround.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/bruker-dda-native-id-and-ms1-skip

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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/topp/CometAdapter.cpp (1)

702-714: Either expose bruker:load_ms1 here or drop the override claim.

This branch hard-forces load_ms1=false for MS2 runs, but registerOptionsAndFlags_() never defines bruker:load_ms1, and Line 714 erases all non-target MS levels anyway. So the “can be overridden via -bruker:load_ms1=true” comment is currently impossible in practice.

As per coding guidelines, define TOPP tool parameters in registerOptionsAndFlags_() method and read with getStringOption_() and related helpers.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/topp/CometAdapter.cpp` around lines 702 - 714, The comment claims
`-bruker:load_ms1=true` can override the forced MS1 drop, but no option is
registered; fix by adding a boolean option in registerOptionsAndFlags_ (e.g.,
"bruker:load_ms1") and read it when building the BrukerTimsFile config instead
of unconditionally forcing bruker_config.load_ms1=false in the MS2 branch;
update getBrukerConfig_() or the code that calls it to honor that option (use
getFlagOption_/getStringOption_/getBoolOption_ as appropriate), or alternatively
remove the misleading comment if you choose not to expose the flag; refer to
registerOptionsAndFlags_(), getBrukerConfig_(), and the bruk er_config.load_ms1
assignment and the subsequent std::erase_if on exp.getSpectra() when making the
change.
src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp (1)

298-366: LGTM! Comprehensive coverage of the load_ms1 toggle.

The test correctly validates:

  1. Baseline behavior with default config (MS1 + MS2 present)
  2. load_ms1=false results in zero MS1 while preserving MS2 count
  3. Conditional DIA testing when OPENTIMS_DIA_TEST_DATA is defined
  4. FRAME export mode also honors the load_ms1 flag

One minor style note on line 362:

for (const auto& s : exp_frame) if (s.getMSLevel() == 1) ++frame_ms1;

As per coding guidelines, "Always use braces for code blocks in C++, even for single-line blocks." Consider expanding this to:

♻️ Suggested fix
-  for (const auto& s : exp_frame) if (s.getMSLevel() == 1) ++frame_ms1;
+  for (const auto& s : exp_frame)
+  {
+    if (s.getMSLevel() == 1) ++frame_ms1;
+  }

,

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp` around lines 298
- 366, Single-line summary: the for-loop at the end of the test uses a
single-line if without braces; update it to use braces per coding guidelines.
Locate the loop that iterates over exp_frame (the statement currently written as
"for (const auto& s : exp_frame) if (s.getMSLevel() == 1) ++frame_ms1;") in
BrukerTimsFile_test.cpp and expand it into a proper block using braces so the
increment of frame_ms1 is inside a braced if body (keep the same condition using
s.getMSLevel() and the same variable frame_ms1).
🤖 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`:
- Around line 38-39: The nativeID string produced by BrukerTimsFile no longer
matches the advertised PSI-MS CV MS:1002818 (which requires "frame=<FRAME_ID>
scan=<SCAN_ID>"), so fix the generation and downstream translation: in
BrukerTimsFile (where spectrum nativeIDs are built) restore the nativeID to only
"frame=<frame_id> scan=<scan_begin>" and move the precursor value into a
separate metadata key (e.g., "Bruker:precursor_id" or a Spectrum meta field)
while leaving BrukerTimsFile::Config and load_ms1 behavior unchanged; update
CometAdapter's rewrite/translate logic (the code that rewrites to "index=N" and
maps PSM references back) to read/write the new separate precursor metadata key
instead of assuming a three-field nativeID, and ensure the source metadata CV
term/accession remains MS:1002818 (or if you choose to advertise a different CV,
update that assignment in the same BrukerTimsFile code path in lockstep).

---

Nitpick comments:
In `@src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp`:
- Around line 298-366: Single-line summary: the for-loop at the end of the test
uses a single-line if without braces; update it to use braces per coding
guidelines. Locate the loop that iterates over exp_frame (the statement
currently written as "for (const auto& s : exp_frame) if (s.getMSLevel() == 1)
++frame_ms1;") in BrukerTimsFile_test.cpp and expand it into a proper block
using braces so the increment of frame_ms1 is inside a braced if body (keep the
same condition using s.getMSLevel() and the same variable frame_ms1).

In `@src/topp/CometAdapter.cpp`:
- Around line 702-714: The comment claims `-bruker:load_ms1=true` can override
the forced MS1 drop, but no option is registered; fix by adding a boolean option
in registerOptionsAndFlags_ (e.g., "bruker:load_ms1") and read it when building
the BrukerTimsFile config instead of unconditionally forcing
bruker_config.load_ms1=false in the MS2 branch; update getBrukerConfig_() or the
code that calls it to honor that option (use
getFlagOption_/getStringOption_/getBoolOption_ as appropriate), or alternatively
remove the misleading comment if you choose not to expose the flag; refer to
registerOptionsAndFlags_(), getBrukerConfig_(), and the bruk er_config.load_ms1
assignment and the subsequent std::erase_if on exp.getSpectra() when making the
change.
🪄 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: 0b5303a5-e905-432a-90f9-94d6aa82c730

📥 Commits

Reviewing files that changed from the base of the PR and between 96ce775 and d7789ef.

📒 Files selected for processing (6)
  • CHANGELOG
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • src/topp/CometAdapter.cpp
  • src/topp/FileConverter.cpp

Comment thread CHANGELOG Resolved
CodeRabbit review flagged that "frame=F scan=S precursor=P" violates the
PSI-MS CV term MS:1002818 ("Bruker TDF nativeID format"), which mandates
exactly "frame=<FRAME_ID> scan=<SCAN_ID>" — and BrukerTimsFile advertises
that accession at BrukerTimsFile.cpp:1297-1298.

Revert to the strict pattern and move the Bruker Precursors.Id SQL key
out of the nativeID into a per-spectrum MetaValue "bruker_precursor_id".
Downstream code that needs the SQL key reads the MetaValue; the native
ID stays CV-compliant and mzParser-stable.

Test updated to assert the CV pattern (frame= prefix, no precursor= in
ID) and that bruker_precursor_id is present as a MetaValue.

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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/openms/source/FORMAT/BrukerTimsFile.cpp (1)

1397-1399: Use Size for the new spectrum-count locals.

ms1_to_emit is new OpenMS count/state, so it should follow the local Size convention instead of introducing more size_t here.

Suggested cleanup
-    const size_t ms1_to_emit = config.load_ms1 ? ms1_frame_ids.size() : 0;
+    const Size ms1_to_emit = config.load_ms1 ? ms1_frame_ids.size() : 0;

As per coding guidelines, "Use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead of standard C++ types" and "Use Size/SignedSize types for STL .size() values in OpenMS".

Also applies to: 1656-1657, 2058-2059

🤖 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 1397 - 1399, The
new spectrum-count locals (e.g., ms1_to_emit and the similar locals at the other
locations) use size_t but must follow OpenMS conventions and be declared as Size
(from OpenMS/CONCEPT/Types.h). Change the type of ms1_to_emit (and the
corresponding locals at the other locations referenced) from size_t to Size and
adjust any dependent code (the startProgress call and the for-loop index
declarations) so the loop index and API arguments use Size as well.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/openms/source/FORMAT/BrukerTimsFile.cpp`:
- Around line 1397-1399: The transform(const String&,
Interfaces::IMSDataConsumer*, const Config&) path computes an expected spectra
count that includes MS1 frames even when config.load_ms1 is false, causing
consumers to receive an inflated setExpectedSize; update the expected count
calculation to conditionally subtract or omit MS1 frames based on
config.load_ms1 so that the startProgress / setExpectedSize calls (and related
loops at the spots around the ms1_frame_ids usage) match the actual emitted
spectra; adjust the logic wherever expected is computed (refer to transform, the
expected variable, and the sections managing ms1_frame_ids and
startProgress/setExpectedSize) so FRAME/DIA/DDA modes respect config.load_ms1.

---

Nitpick comments:
In `@src/openms/source/FORMAT/BrukerTimsFile.cpp`:
- Around line 1397-1399: The new spectrum-count locals (e.g., ms1_to_emit and
the similar locals at the other locations) use size_t but must follow OpenMS
conventions and be declared as Size (from OpenMS/CONCEPT/Types.h). Change the
type of ms1_to_emit (and the corresponding locals at the other locations
referenced) from size_t to Size and adjust any dependent code (the startProgress
call and the for-loop index declarations) so the loop index and API arguments
use Size as well.
🪄 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: 0c704eca-1884-4140-b5d1-defdb57a2168

📥 Commits

Reviewing files that changed from the base of the PR and between d7789ef and 5b9fd0f.

📒 Files selected for processing (3)
  • CHANGELOG
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
✅ Files skipped from review due to trivial changes (2)
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • CHANGELOG

- BrukerTimsFile::transform(): respect config.load_ms1 when computing the
  consumer's expected spectrum count, so setExpectedSize matches what the
  underlying loadFrames_/loadDIA_/loadDDA_ paths actually emit
- CometAdapter: drop the misleading claim that -bruker:load_ms1=true can
  override the forced MS1 skip (the option isn't registered here)
- BrukerTimsFile_test: brace single-line if per OpenMS coding guidelines

Co-Authored-By: Claude Opus 4.7 (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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/topp/CometAdapter.cpp (1)

723-736: Update the nativeID workaround comments to match the new Bruker format.

Both comments still describe the original ID as frame=... scan=... precursor=..., but this PR moved the precursor SQL key into bruker_precursor_id and made the nativeID itself frame=... scan=.... Keeping the old form here is misleading for the next person touching this workaround.

Based on learnings: the mandated nativeID string pattern for MS:1002818 is frame=<FRAME_ID> scan=<SCAN_ID>.

Also applies to: 851-855

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/topp/CometAdapter.cpp` around lines 723 - 736, Update the explanatory
comment in CometAdapter.cpp that describes the Bruker nativeID format: change
the outdated "frame=F scan=S precursor=P" wording to the current mandated
MS:1002818 pattern "frame=<FRAME_ID> scan=<SCAN_ID>" and note that the precursor
ID was moved to the SQL key bruker_precursor_id; apply the same wording update
to the other occurrence of the comment (previously around lines 851-855) so the
nativeID workaround and rationale accurately reflect the new format.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/openms/source/FORMAT/BrukerTimsFile.cpp`:
- Around line 1397-1399: The ms1_aggregator.reserve(300'000) is currently
executed even when config.load_ms1 is false (ms1_to_emit == 0), causing
unnecessary memory allocation for MS2-only streaming; update the logic around
ms1_aggregator.reserve to only call reserve when config.load_ms1 is true (and
optionally when ms1_n_neighbors > 0) so the large reservation is skipped for the
MS2-only path—find the ms1_aggregator.reserve call and gate it with the same
condition used to compute ms1_to_emit (config.load_ms1) or combine with
ms1_n_neighbors > 0 before reserving.

In `@src/topp/CometAdapter.cpp`:
- Around line 702-706: The code currently disables Bruker MS1 loading only when
ms_level == 2; update the guard so MS1 loading is also disabled for MS3 searches
(i.e., any non-MS1 Comet search). Change the condition around
getBrukerConfig_()/bruker_config.load_ms1 to disable load_ms1 when ms_level is
>= 2 (or ms_level != 1) so both MS2 and MS3 skip MS1 loading.

---

Nitpick comments:
In `@src/topp/CometAdapter.cpp`:
- Around line 723-736: Update the explanatory comment in CometAdapter.cpp that
describes the Bruker nativeID format: change the outdated "frame=F scan=S
precursor=P" wording to the current mandated MS:1002818 pattern
"frame=<FRAME_ID> scan=<SCAN_ID>" and note that the precursor ID was moved to
the SQL key bruker_precursor_id; apply the same wording update to the other
occurrence of the comment (previously around lines 851-855) so the nativeID
workaround and rationale accurately reflect the new format.
🪄 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: 267b1ecc-8579-4a11-9d78-b8c4fba2eb1e

📥 Commits

Reviewing files that changed from the base of the PR and between 5b9fd0f and 38f368c.

📒 Files selected for processing (3)
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • src/topp/CometAdapter.cpp
✅ Files skipped from review due to trivial changes (1)
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp

Comment on lines +1397 to +1399
const size_t ms1_to_emit = config.load_ms1 ? ms1_frame_ids.size() : 0;
startProgress(0, ms1_to_emit, "Streaming DIA-PASEF MS1 frames");
for (size_t i = 0; i < ms1_to_emit; ++i)

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.

⚠️ Potential issue | 🟡 Minor

Skip the MS1 aggregator reservation when load_ms1 is off.

ms1_to_emit drops to 0 here, but the ms1_aggregator.reserve(300'000) just above still runs whenever ms1_n_neighbors > 0. That keeps a fairly large allocation in the exact MS2-only streaming path this change is trying to slim down.

Suggested change
-    if (config.ms1_n_neighbors > 0) ms1_aggregator.reserve(300'000);
+    if (config.load_ms1 && 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` around lines 1397 - 1399, The
ms1_aggregator.reserve(300'000) is currently executed even when config.load_ms1
is false (ms1_to_emit == 0), causing unnecessary memory allocation for MS2-only
streaming; update the logic around ms1_aggregator.reserve to only call reserve
when config.load_ms1 is true (and optionally when ms1_n_neighbors > 0) so the
large reservation is skipped for the MS2-only path—find the
ms1_aggregator.reserve call and gate it with the same condition used to compute
ms1_to_emit (config.load_ms1) or combine with ms1_n_neighbors > 0 before
reserving.

Comment thread src/topp/CometAdapter.cpp
Comment on lines +702 to +706
// Load .d via BrukerTimsFile. Skip MS1 loading for MS2 searches since
// Comet only searches MS2 — cuts load time substantially.
auto bruker_config = getBrukerConfig_();
if (ms_level == 2)
bruker_config.load_ms1 = false;

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.

⚠️ Potential issue | 🟡 Minor

Disable MS1 loading for MS3 Bruker searches too.

ms_level is constrained to 2 or 3, and Comet does not need MS1 in either case. With the current guard, .d inputs searched at MS3 still pay the extra MS1 load/memory cost this change is meant to avoid.

Suggested change
-      if (ms_level == 2)
-        bruker_config.load_ms1 = false;
+      if (ms_level > 1)
+      {
+        bruker_config.load_ms1 = false;
+      }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/topp/CometAdapter.cpp` around lines 702 - 706, The code currently
disables Bruker MS1 loading only when ms_level == 2; update the guard so MS1
loading is also disabled for MS3 searches (i.e., any non-MS1 Comet search).
Change the condition around getBrukerConfig_()/bruker_config.load_ms1 to disable
load_ms1 when ms_level is >= 2 (or ms_level != 1) so both MS2 and MS3 skip MS1
loading.

Three confirmed correctness bugs surfaced during the PR review:

1. BrukerTimsFile::transform() computed the DIA expected-spectrum count
   as counts.ms2 * windows.size(), but each MS2 frame belongs to exactly
   ONE WindowGroup. Actual emit count is the per-group sum
   Σ (frames_in_group × windows_in_group), identical to loadDIA_'s
   total_work formula. With multiple WindowGroups the previous formula
   overcounted by a factor proportional to the number of groups.

2. DDA MS2 nativeID collisions. This reader aggregates all
   PasefFrameMsMsInfo rows sharing the same Precursors.Id (potentially
   across multiple frames) into ONE spectrum — a timsrust-style design
   pwiz does NOT use (pwiz emits per-mobility-scan, where (frame, scan)
   is inherently unique). Under our per-precursor aggregation,
   first_entry->(frame_id, scan_begin) is NOT guaranteed unique across
   distinct precursors (PASEF co-isolation with different IsolationMz,
   multi-cycle precursors colliding on their first entry). Restore the
   trailing "precursor=<P>" token to the nativeID. This matches pwiz's
   combined-mode convention ("merged=N frame=F scanStart=A scanEnd=B"
   under the same MS:1002818 accession) and OpenMS's own DIA path
   ("frame=F windowGroup=G scan=S"). The CV accession MS:1002818 stays;
   Comet/Sage dispatch on nativeID content, not the CV accession, so
   downstream compatibility is preserved. Precursors.Id remains
   duplicated as a typed MetaValue "bruker_precursor_id" for direct
   lookup. Test adds a uniqueness assertion on the full set of DDA MS2
   native IDs.

3. SpectrumNativeIDParser did not recognize MS:1002818 (accession-based
   overload returned -1; content-based overload didn't recognize the
   "frame=" prefix). Downstream tools relying on scan-number extraction
   (SpectrumLookup, USI, PepXMLFile, PercolatorInfile, IDMapper,
   ConsensusMapArrowExport) silently produced -1 or used the bare-int
   fallback for Bruker .d output. Add MS:1002818 to the "scan=" accession
   bucket and "frame=" to the prefix map; both route to the existing
   scan=(\d+) regex which picks up the scan_begin integer.

CometAdapter's existing comments at :725 and :853 already described the
"frame=F scan=S precursor=P" format and are now correct again without
modification. CHANGELOG updated to document the real format and the
downstream parser work. rationale for the nativeID format is documented
inline in BrukerTimsFile::loadDDA_.

Co-Authored-By: Claude Opus 4.7 (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 (1)
src/openms/source/FORMAT/BrukerTimsFile.cpp (1)

384-389: Minor: Prefer \n over std::endl for performance.

Per coding guidelines, std::endl should be avoided for performance reasons. Consider using "\n" instead.

Suggested change
     if (!config.load_ms1 && config.ms1_n_neighbors > 0)
     {
       OPENMS_LOG_WARN << "Warning: ms1_n_neighbors (=" << config.ms1_n_neighbors
                       << ") ignored: load_ms1=false disables MS1 loading entirely."
-                      << std::endl;
+                      << "\n";
     }
🤖 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 384 - 389, Replace
the use of std::endl in the warning log inside BrukerTimsFile.cpp with a "\n" to
avoid flushing the stream unnecessarily: in the block that checks
config.load_ms1 and config.ms1_n_neighbors (the OPENMS_LOG_WARN statement),
change the trailing std::endl to "\n" so the warning message is terminated
without forcing a flush.
🤖 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 384-389: Replace the use of std::endl in the warning log inside
BrukerTimsFile.cpp with a "\n" to avoid flushing the stream unnecessarily: in
the block that checks config.load_ms1 and config.ms1_n_neighbors (the
OPENMS_LOG_WARN statement), change the trailing std::endl to "\n" so the warning
message is terminated without forcing a flush.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0710dedc-249d-439e-a492-6b8eb0ffe35f

📥 Commits

Reviewing files that changed from the base of the PR and between 38f368c and 00b076a.

📒 Files selected for processing (4)
  • CHANGELOG
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/openms/source/METADATA/SpectrumNativeIDParser.cpp
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
✅ Files skipped from review due to trivial changes (1)
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG

timosachsenberg and others added 4 commits April 16, 2026 20:38
ProSEAlgorithm::runCalibrationPass_ was reflecting the calibration
window around zero. Given the (lower, upper) schema established at
ProSEAlgorithm.cpp:1615-1617 (theoretical ∈ [observed - lower,
observed + upper] ⇔ signed error e ∈ [-upper, +lower]), mapping the
intended window [shift - spread, shift + spread] requires:

  cal_lower = spread + shift  // was: spread - shift
  cal_upper = spread - shift  // was: spread + shift

The filter at lines 1624-1625 already uses the correct convention; only
the write-back at 1667-1668 was inverted.

Impact on the Bruker DDA fixture (PR #9160's opentims integration test):
on a precursor error distribution biased +3.57 ppm with 6.02 ppm spread,
the bug made FragmentIndex accept e ∈ [-9.59, +2.44] (hard-capped,
opposite-sign) instead of [-2.44, +9.59]. 1% FDR PSMs went from 1441
(buggy) to 4537 (fixed) — uncalibrated baseline is 4373, so calibration
now correctly improves ID yield by ~4% instead of degrading it 3x.

Bug introduced in commit 7445cd6 (PR #9132, "asymmetric precursor
tolerance window"). Pre-existing on develop; surfaced because PR #9160
added a Bruker DDA integration test that exposes the signed precursor
bias through which this swap becomes visible.

Also adds floor-only PSM-count regression tripwires for the three DDA
pipelines (SimpleSearchEngine, ProSE, ProSE calibrated). Floors sit ~5%
below observed yields, catching real regressions while tolerating small
algorithmic drift. The calibrated floor specifically guards the swap
fix — a regression would drop PSMs back to ~1441 and trigger the floor.
The check is a pure-CMake -P script (file(READ) + string(REGEX MATCHALL)
since file(STRINGS) silently undercounts on large idXML files).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Original floors were ~5% below observed counts, too loose to catch a
subtle regression (e.g., a partial nativeID or IM-annotation break that
drops 2% of PSMs). Tighten to ~0.5%:
  SimpleSearchEngine DDA: 3900 -> 4170  (current 4187)
  ProSE DDA:              4100 -> 4350  (current 4373)
  ProSE DDA calibrated:   4300 -> 4510  (current 4537)

If a legitimate change raises yield, the floor should be raised in the
same commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The calibration asymmetry check in the "calibration preserves asymmetric
bias - normal case" section was matched to the previous buggy ordering
(cal_upper > cal_lower for positive bias). After fixing the swap in
runCalibrationPass_, the correct inequality is cal_lower > cal_upper:
under (lower, upper) where signed error e ∈ [-upper, +lower], a positive
bias widens +lower and tightens -upper.

The order-invariant downstream uses (std::min(cal.cal_lower, cal.cal_upper)
on line 1299) are unaffected.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Previous version used tautological checks (cal_lower < 20.0 is trivially
true because the code does std::min(raw, 20.0)) and a way-too-loose 5 ppm
tolerance on the shift, so it couldn't actually catch a regression of the
sign convention. Replace with:

- Direction check: shift > 0 and spread > 0 for this positive-biased fixture
- |shift| < spread precondition stated explicitly
- Load-bearing functional identities binding the writeback mapping:
    cal_lower = spread + shift  (upper endpoint of signed-e window)
    cal_upper = spread - shift  (|lower endpoint| of signed-e window)
  These directly encode the (lower, upper) <-> [-upper, +lower] convention
  and would fail simultaneously if the swap bug were re-introduced.
- Asymmetry check (cal_lower > cal_upper for positive bias) as a cross-check
  against mislabeled shift/spread producing consistent-but-wrong identities.
- Keep the "< 20, < 30" checks only as a witness that the std::min cap is
  inactive (so the identities above are unconstrained), NOT as primary
  behavior assertions.

Dropped the hardcoded shift=7.0 / spread=8.5 / cal_lower=15.5 / cal_upper=1.5
literals: the search pipeline doesn't include every synthetic shift in the
calibration set, so those specific numbers depend on search-side filtering
details. The functional identities are immune to that.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@timosachsenberg
timosachsenberg merged commit 8cce740 into develop Apr 16, 2026
18 of 19 checks passed
@timosachsenberg
timosachsenberg deleted the feat/bruker-dda-native-id-and-ms1-skip branch April 16, 2026 19:46
timosachsenberg added a commit that referenced this pull request Apr 17, 2026
The mzParser segfault workaround from #9160 only fired when CometAdapter
received a .d directory directly. When users converted .d → mzML via
FileConverter first, the mzML contained Bruker-format native IDs
(frame=F scan=S, CV term MS:1002818) that triggered the same
cindex::compare strict-weak-ordering UB in Comet's mzParser.

Fix: detect Bruker-originated mzML by probing the first spectrum's
native ID for "frame=". When detected, take the full-data path (load
with peaks → rewrite IDs to index=N → write temp mzML → clear peaks),
matching the direct .d branch exactly. Non-Bruker mzML keeps the
original fast path (metadata-only load + pass-through).

The post-Comet translation block (index=N → original ID) is also
generalized: it now fires whenever original_native_id MetaValues are
present, regardless of whether the input was .d or .mzML.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
timosachsenberg added a commit that referenced this pull request Apr 17, 2026
The mzParser segfault workaround from #9160 only fired when CometAdapter
received a .d directory directly. When users converted .d → mzML via
FileConverter first, the mzML contained Bruker-format native IDs
(frame=F scan=S, CV term MS:1002818) that triggered the same
cindex::compare strict-weak-ordering UB in Comet's mzParser.

Fix: detect Bruker-originated mzML by probing the first spectrum's
native ID for "frame=". When detected, take the full-data path (load
with peaks → rewrite IDs to index=N → write temp mzML → clear peaks),
matching the direct .d branch exactly. Non-Bruker mzML keeps the
original fast path (metadata-only load + pass-through).

The post-Comet translation block (index=N → original ID) is also
generalized: it now fires whenever original_native_id MetaValues are
present, regardless of whether the input was .d or .mzML.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
timosachsenberg added a commit that referenced this pull request Apr 17, 2026
The mzParser segfault workaround from #9160 only fired when CometAdapter
received a .d directory directly. When users converted .d → mzML via
FileConverter first, the mzML contained Bruker-format native IDs
(frame=F scan=S, CV term MS:1002818) that triggered the same
cindex::compare strict-weak-ordering UB in Comet's mzParser.

Fix: detect Bruker-originated mzML by probing the first spectrum's
native ID for "frame=". When detected, take the full-data path (load
with peaks → rewrite IDs to index=N → write temp mzML → clear peaks),
matching the direct .d branch exactly. Non-Bruker mzML keeps the
original fast path (metadata-only load + pass-through).

The post-Comet translation block (index=N → original ID) is also
generalized: it now fires whenever original_native_id MetaValues are
present, regardless of whether the input was .d or .mzML.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
timosachsenberg added a commit that referenced this pull request Apr 17, 2026
The mzParser segfault workaround from #9160 only fired when CometAdapter
received a .d directory directly. When users converted .d → mzML via
FileConverter first, the mzML contained Bruker-format native IDs
(frame=F scan=S, CV term MS:1002818) that triggered the same
cindex::compare strict-weak-ordering UB in Comet's mzParser.

Fix: detect Bruker-originated mzML by probing the first spectrum's
native ID for "frame=". When detected, take the full-data path (load
with peaks → rewrite IDs to index=N → write temp mzML → clear peaks),
matching the direct .d branch exactly. Non-Bruker mzML keeps the
original fast path (metadata-only load + pass-through).

The post-Comet translation block (index=N → original ID) is also
generalized: it now fires whenever original_native_id MetaValues are
present, regardless of whether the input was .d or .mzML.

Co-authored-by: Claude Opus 4.6 (1M context) <[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.

1 participant