Skip to content

feat(BrukerTimsFile): IM-axis hill-based centroiding for TIMS-PASEF - #9286

Closed
timosachsenberg wants to merge 8 commits into
developfrom
feat/timstof-hill-centroiding
Closed

timosachsenberg wants to merge 8 commits into
developfrom
feat/timstof-hill-centroiding

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add a Biosaur2-style IM-axis hill detection centroider for Bruker TIMS-PASEF data. The centroider links peaks across consecutive IM scans within a single PASEF frame by m/z proximity, splits chains at intensity valleys, and emits one centroid per surviving hill. Available on MS1, DIA-MS2 (aggregated and raw), and DDA-MS2. Co-exists with the existing Greedy2D path — both selectable via a new ms{1,2}_centroid_algo field.

Includes opt-in hill-bounds metadata and a new plot_pasef_frames.py visualization tool to QC the centroider against raw data.

What's new

Core algorithm (src/openms/{include,source}/FORMAT/HANDLERS/PASEFHillCentroider.{h,cpp})

  • Greedy descending-intensity peak-to-tail matching across IM scans (linkScanToHills_).
  • Valley splitting via mean-filtered intensity sequence (splitHills_, Biosaur2 hvf=1.3).
  • Gap bridging: optional max_scan_gap lets a hill bridge empty IM scans. Requires a paired-link first (length ≥ 2) before any gap, preventing two unrelated noise blips from chaining into a false length-2 hill.
  • Returns Centroids with intensity-weighted m/z, summed intensity, IM apex, and (m/z, IM) bounding box.

BrukerTimsFile integration

  • New Config fields: ms{1,2}_centroid_algo (Off/Greedy2D/HillBased), ms{1,2}_centroid_mz_ppm, ms{1,2}_centroid_min_hill_length, centroid_valley_factor, centroid_max_scan_gap, expose_hill_bounds.
  • All four hill code paths (MS1 single-frame, MS1 aggregated, DIA-MS2 aggregated, DIA-MS2 raw at n_neighbors=0) pass through TIMS scan_ids so max_scan_gap is meaningful.
  • DDA-MS2 hill operates on per-precursor (m/z, intensity, IM) triples; emits a single scalar drift_time per spectrum (output schema unchanged).
  • expose_hill_bounds=true attaches im lower/upper bound and m/z lower/upper bound FloatDataArrays for downstream visual QC. Off by default.

Tuned defaults (active only when hill is opted into via *_centroid_algo=hillbased)

  • ms1_centroid_mz_ppm: 0 → 10 — empirically motivated. Detector-centroided TIMS-PASEF MS1 peaks drift up to ~10 ppm in m/z between IM scans of the same ion; 5 ppm only captures ~4% of MS1 peaks as multi-scan hills vs ~9% at 10 ppm.
  • ms2_centroid_mz_ppm: 0 → 20 — DIA-PASEF-tuned for fragments.
  • ms2_centroid_min_hill_length: 1 → 2 — DIA-PASEF-tuned. DDA-PASEF callers must override to 1 (narrow precursor IM range → most fragments observed in only one IM scan; min=2 drops ~93% of DDA fragments). Help text and Config doc-comments document this.
  • dia_ms2_n_neighbors: unchanged at 0 to keep the default DIA-MS2 export path the raw per-frame path. Users wanting the full DIA-PASEF hill recipe set dia_ms2_n_neighbors=2 together with the algo selection.

CLI — full set of -bruker:* flags on FileConverter and PeakPickerIM.

Visualization — tools/scripts/plot_pasef_frames.py:

  • Renders N MS1 + N MS2 frames in a grid (rows = TIC-quantile frames, cols = inputs) for side-by-side centroider comparison.
  • Datashader-style 1-bin-per-pixel rendering with max-log10(intensity) aggregation; per-row shared m/z / 1/K0 axes; globally shared intensity colormap.
  • Optional top-N intensity overlay (colored outlined circles) and full hill bounding-box overlay (when the mzML carries expose_hill_bounds arrays).
  • Always-on params banner: suptitle lists active plot options, footer parses each input's bruker:* userParams from the mzML's <dataProcessingList> so figures are self-describing.

Tests

  • New synthetic test PASEFHillCentroider_test: 13 sections covering empty input, isolated peak, valley split, min_hill_length filter, sparse-data mode (min=1), m/z tolerance, determinism, min_intensity filter, smooth-peak no-split, sorted output, gap=0/1/2 behavior, and the require-paired-link-before-gap rule.
  • Real-data tests in BrukerTimsFile_test (behind ENABLE_OPENTIMS_TESTS): hill-vs-greedy comparison on bundled DDA and DIA fixtures with schema invariants, peak-count ratios, and intensity range checks. Test timeout bumped to 2400 s.

Test plan

  • CI build passes (cmake --build OpenMS-build -j).
  • PASEFHillCentroider_test passes (~0.1 s, synthetic).
  • BrukerTimsFile_test passes with WITH_OPENTIMS=ON and the bundled fixtures (~25 min on this machine).
  • Spot-check: FileConverter -in run.d -out hill.mzML -bruker:ms1_centroid_algo hillbased -bruker:ms2_centroid_algo hillbased -bruker:dia_ms2_n_neighbors 2 produces sensible centroided output.
  • Visualization: python3 tools/scripts/plot_pasef_frames.py --mzml off=raw.mzML --mzml hill=hill.mzML --show-hill-bounds --out-dir frames renders cleanly.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Selectable hill-based centroiding for MS1 and MS2 (Off/Greedy2D/HillBased).
    • Two visualization tools to render and compare PASEF frames and centroiding outputs.
  • Improvements

    • Hill-based tuning controls and updated defaults (MS1 m/z link default → 10 ppm; MS2 defaults exposed).
    • Clarified DIA/MS2 aggregation precedence and optional emission of hill-bound metadata.
  • Tests

    • New unit and integration tests for hill centroiding and comparisons; increased test timeout.

Review Change Stack

Comment thread tools/scripts/plot_pasef_frames.py Fixed
Comment thread tools/scripts/plot_pasef_frames.py Fixed
@coderabbitai

coderabbitai Bot commented May 11, 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

Selectable hill-based IM-axis centroiding for TIMS‑PASEF MS1/MS2: new PASEFHillCentroider implementation, BrukerTimsFile integration with algorithm resolution and optional hill-bound output, CLI/config plumbing, unit and integration tests, CMake registration, and visualization scripts.

Changes

IM-axis hill-based PASEF centroiding

Layer / File(s) Summary
Configuration model
src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
Adds CentroidAlgo enum (OFF, GREEDY2D, HILL_BASED), ms1_centroid_algo/ms2_centroid_algo, hill-tuning fields (ms2_centroid_mz_ppm, centroid_valley_factor, MS1/MS2 min hill lengths, centroid_max_scan_gap, expose_hill_bounds) and updates ms1_centroid_mz_ppm default to 10 ppm.
PASEFHillCentroider API
src/openms/include/OpenMS/FORMAT/HANDLERS/PASEFHillCentroider.h
Defines Params (mz_tol_ppm, valley_factor, min_hill_length, min_intensity, im_group_tolerance, max_scan_gap), Centroid (mz, intensity, im_apex/lower/upper, mz_lower/mz_upper, length), and declares centroidFrame(...).
Build integration
src/openms/include/OpenMS/FORMAT/HANDLERS/sources.cmake, src/openms/source/FORMAT/HANDLERS/sources.cmake
Registers PASEFHillCentroider.h and PASEFHillCentroider.cpp in handler CMake source lists.
BrukerTimsFile includes & helpers
src/openms/source/FORMAT/BrukerTimsFile.cpp
Adds include, effectiveMS1Algo/effectiveMS2Algo helpers, centroid dispatch (runMS1Centroider, runMS2HillCentroider), hill-bounds plumbing, and one-shot config validation.
MS1 frame centroiding
src/openms/source/FORMAT/BrukerTimsFile.cpp
Extracts per-peak scan_id, resolves MS1 algorithm, runs Greedy2D or HillBased centroider, and optionally attaches hill-bound FloatDataArrays.
Aggregated MS1 generation
src/openms/source/FORMAT/BrukerTimsFile.cpp
Updates aggregated MS1 generation to include scan_id for HillBased gap handling and to run the resolved algorithm (with bounds output when enabled).
DDA MS2 HillBased path
src/openms/source/FORMAT/BrukerTimsFile.cpp
Adds DDA-MS2 HillBased branch: TOF→m/z conversion, IM-hill centroiding per precursor group, preserves scalar drift time and output schema, optional bounds.
DIA MS2 aggregated & raw paths
src/openms/source/FORMAT/BrukerTimsFile.cpp
Dispatches DIA-MS2 centroiding between Greedy2D and HillBased for aggregated (RT-neighbor summed) and raw single-frame modes; HillBased converts scan_id→IM, runs centroider, sets IM peak type centroided, and optionally attaches bounds.
PASEF implementation: smoothing & splitting
src/openms/source/FORMAT/HANDLERS/PASEFHillCentroider.cpp
Adds 3-tap mean filter and Biosaur2-inspired valley splitting with confirmation pass and segment recomputation.
PASEF implementation: linking & pruning
src/openms/source/FORMAT/HANDLERS/PASEFHillCentroider.cpp
Greedy peak-to-tail linking with m/z-ppm tolerance and FM-bin indexing, tail aging, max_scan_gap pruning with length‑1 bridging rule, FM index rebuild.
centroidFrame main
src/openms/source/FORMAT/HANDLERS/PASEFHillCentroider.cpp
Filters peaks, computes mz bin step, iterates scans or IM groups, links/prunes, splits at valleys, drops short segments, computes intensity-weighted centroids with bounds/apex/length, returns m/z-sorted results.
FileConverter CLI options
src/topp/FileConverter.cpp
Adds bruker:ms1_centroid_algo/bruker:ms2_centroid_algo and hill-tuning CLI options; updates ms1_centroid_mz_ppm default/help and parses into BrukerTimsFile::Config.
PeakPickerIM CLI options
src/topp/PeakPickerIM.cpp
Registers same Bruker CLI options, updates DIA aggregation/denoising help text, and populates BrukerTimsFile::Config in getBrukerConfig_().
PASEFHillCentroider unit tests
src/tests/class_tests/openms/source/PASEFHillCentroider_test.cpp
Adds comprehensive unit tests covering empty input, single-ion, valley splitting, min_hill_length, max_scan_gap edge cases, m/z separation, determinism, min_intensity filtering, unimodal hills, and output ordering.
Integration tests & helpers
src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
Adds centroiding stats helpers and schema assertions; adds DDA and DIA comparisons (HillBased vs Greedy2D/TOF), adjusts DIA baseline where required.
Test build updates
src/tests/class_tests/openms/CMakeLists.txt, src/tests/class_tests/openms/executables.cmake
Increases BrukerTimsFile_test TIMEOUT and registers PASEFHillCentroider_test.
Visualization: plot_pasef_frames.py
tools/scripts/plot_pasef_frames.py
New frame-grid renderer with datashade/scatter modes, optional hill-bound overlays, top‑N overlays, and per-input Bruker param banners; deferred heavy deps.
Visualization: visualize_pasef_centroiding.py
tools/scripts/visualize_pasef_centroiding.py
New side-by-side scatter comparison CLI for up to three mzMLs (off/greedy2d/hillbased) with deferred deps, spectrum selection, and shared colorbar support.

Possibly related issues

Possibly related PRs

Suggested labels

enhancement, Review effort [1-5]: 3

Suggested reviewers

  • jcharkow
  • alhigaylan
  • singjc
  • jpfeuffer

Poem

🐇 I hop through hills of peaks at play,
Tracing valleys where the ions lay,
I stitch each apex with a careful paw,
Split where troughs command, unite what I saw,
And show the frames so scientists can say hurrah.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.27% 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 pull request title accurately summarizes the main change: adding IM-axis hill-based centroiding for TIMS-PASEF data, which is the core feature introduced across multiple files in this changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/timstof-hill-centroiding

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.

@timosachsenberg
timosachsenberg force-pushed the feat/timstof-hill-centroiding branch from 2e9eca3 to 778cb12 Compare May 11, 2026 14:50

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/topp/PeakPickerIM.cpp (1)

128-131: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

PeakPickerIM rejects a valid dia_ms2_min_support=0 configuration.

BrukerTimsFile::Config and FileConverter both support 0 here to disable DIA-MS2 denoising, but this tool hard-codes the minimum to 1. That blocks the new no-denoise centroiding path for Bruker .d input.

🔧 Suggested fix
     registerIntOption_("bruker:dia_ms2_min_support", "<int>", 1,
       "DIA MS2 denoising: minimum occupied neighbor cells in a 3x3 (m/z x IM) grid to keep a point "
-      "(center cell excluded from count). Applied after frame aggregation. Only effective when dia_ms2_n_neighbors > 0.", false, true);
-    setMinInt_("bruker:dia_ms2_min_support", 1);
+      "(center cell excluded from count). Applied after frame aggregation. Only effective when dia_ms2_n_neighbors > 0. "
+      "Set to 0 to disable denoising.", false, true);
+    setMinInt_("bruker:dia_ms2_min_support", 0);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/topp/PeakPickerIM.cpp` around lines 128 - 131, The option
"bruker:dia_ms2_min_support" in PeakPickerIM currently enforces a minimum of 1
via setMinInt_("bruker:dia_ms2_min_support", 1), which prevents a valid zero
value used to disable DIA-MS2 denoising; update the code to allow 0 by changing
that call to setMinInt_("bruker:dia_ms2_min_support", 0) (or remove the
setMinInt_ call entirely) so the registerIntOption_ for
"bruker:dia_ms2_min_support" accepts 0 as a valid setting and preserves existing
behavior for values >0.
🧹 Nitpick comments (1)
src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp (1)

1837-1920: ⚡ Quick win

Add one integration path with expose_hill_bounds=true.

This PR exposes four extra FloatDataArrays on hill-based MS1/DIA-MS2 output, but none of the new sections enable the flag or verify array count/name/size alignment. A regression in that wiring would still pass these tests.

🧪 Suggested coverage
   BrukerTimsFile::Config cfg_hill;
   cfg_hill.ms1_centroid_algo        = CA::HillBased;
   cfg_hill.ms1_centroid_mz_ppm      = 5.0f;
   cfg_hill.ms2_centroid_algo        = CA::HillBased;
   cfg_hill.ms2_centroid_mz_ppm      = 20.0f;
   cfg_hill.dia_ms2_n_neighbors      = 1;
   cfg_hill.dia_ms2_min_support      = 1;
   cfg_hill.centroid_valley_factor   = 1.3;
   cfg_hill.ms2_centroid_min_hill_length = 2;
+  cfg_hill.expose_hill_bounds       = true;

Then assert on the first centroided MS1 and DIA-MS2 spectrum that the expected bound arrays are present and each array size matches spec.size().

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

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp` around lines
1837 - 1920, The test needs to enable the new hill-bound export and check the
added FloatDataArrays: set cfg_hill.expose_hill_bounds = true before loading
exp_hill (BrukerTimsFile::Config cfg_hill) and after loading, locate the first
centroided MS1 and first DIA-MS2 spectrum (reuse
assertFirstMS1Centroided/assertFirstDIAMS2Centroided to find them) and assert
the four new FloatDataArray names exist and that each array's size equals
spec.size(); add those assertions alongside the existing centroided checks so
the new wiring is validated.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h`:
- Line 70: CentroidAlgo enum in BrukerTimsFile uses mixed-case members (Off,
Greedy2D, HillBased) and must be renamed to UPPER_SNAKE_CASE (OFF, GREEDY2D,
HILLBASED); update the enum declaration in OpenMS/FORMAT/BrukerTimsFile.h and
then change every usage/comparison of BrukerTimsFile::Config::CentroidAlgo
(e.g., CA::Off → CA::OFF, CA::Greedy2D → CA::GREEDY2D, CA::HillBased →
CA::HILLBASED) in src/openms/source/FORMAT/BrukerTimsFile.cpp, the CLI parsing
sites in src/topp/FileConverter.cpp and src/topp/PeakPickerIM.cpp, and the
related tests so identifiers match; leave any CLI string literals ("off",
"greedy2d", "hillbased") unchanged.

In `@src/openms/source/FORMAT/HANDLERS/PASEFHillCentroider.cpp`:
- Line 482: Guard against Params::min_hill_length == 0 by clamping it to at
least 1 before calling splitHills: inside the centroidFrame function create a
local const Size (e.g., min_hill_length or pc.min_hill_length) initialized with
std::max<Size>(1, p.min_hill_length) and use that local value (replace uses of
p.min_hill_length) when calling splitHills(hills, p.valley_factor, ...) and in
the subsequent hill-length filter, so splitHills never receives 0 and all
downstream reads use the clamped value.

In `@src/topp/FileConverter.cpp`:
- Around line 254-260: The help text for the option registered via
registerStringOption_("bruker:ms1_centroid_algo", ...) refers to the wrong
parameter name; replace the reference "centroid_min_hill_length" with the actual
option name "ms1_centroid_min_hill_length" in that string (and check the same
string for any other mismatched option names like ms1_centroid_mz_ppm or
ms1_centroid_im_pct to ensure consistency) so generated CLI/INI docs point to
the real flag.

---

Outside diff comments:
In `@src/topp/PeakPickerIM.cpp`:
- Around line 128-131: The option "bruker:dia_ms2_min_support" in PeakPickerIM
currently enforces a minimum of 1 via setMinInt_("bruker:dia_ms2_min_support",
1), which prevents a valid zero value used to disable DIA-MS2 denoising; update
the code to allow 0 by changing that call to
setMinInt_("bruker:dia_ms2_min_support", 0) (or remove the setMinInt_ call
entirely) so the registerIntOption_ for "bruker:dia_ms2_min_support" accepts 0
as a valid setting and preserves existing behavior for values >0.

---

Nitpick comments:
In `@src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp`:
- Around line 1837-1920: The test needs to enable the new hill-bound export and
check the added FloatDataArrays: set cfg_hill.expose_hill_bounds = true before
loading exp_hill (BrukerTimsFile::Config cfg_hill) and after loading, locate the
first centroided MS1 and first DIA-MS2 spectrum (reuse
assertFirstMS1Centroided/assertFirstDIAMS2Centroided to find them) and assert
the four new FloatDataArray names exist and that each array's size equals
spec.size(); add those assertions alongside the existing centroided checks so
the new wiring is validated.
🪄 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: b5de5b07-205c-46ad-bb7c-6e95ac2fb571

📥 Commits

Reviewing files that changed from the base of the PR and between b0fbfd0 and 778cb12.

📒 Files selected for processing (14)
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/PASEFHillCentroider.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/sources.cmake
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/openms/source/FORMAT/HANDLERS/PASEFHillCentroider.cpp
  • src/openms/source/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/CMakeLists.txt
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • src/tests/class_tests/openms/source/PASEFHillCentroider_test.cpp
  • src/topp/FileConverter.cpp
  • src/topp/PeakPickerIM.cpp
  • tools/scripts/plot_pasef_frames.py
  • tools/scripts/visualize_pasef_centroiding.py

Comment thread src/topp/FileConverter.cpp Resolved
@timosachsenberg
timosachsenberg force-pushed the feat/timstof-hill-centroiding branch from 778cb12 to 91db53e Compare May 11, 2026 15:19
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Force-pushed 91db53e addressing CodeFactor + CodeRabbit feedback:

CodeFactor (3 findings, all resolved):

  • Removed unused top_idx_for_bounds and any_per_peak_im locals in plot_pasef_frames.py.
  • Made panel() in visualize_pasef_centroiding.py return None explicitly in both early-exit branches.

CodeRabbit:

  • 🟠 Renamed enum class CentroidAlgo { Off, Greedy2D, HillBased } → { OFF, GREEDY2D, HILL_BASED } to match the UPPER_SNAKE_CASE convention used by sibling enums (TimsCalibrationStrategy, PressureCompensation) in the same header. All 34 usage sites updated; CLI string literals ("off"/"greedy2d"/"hillbased") unchanged.
  • 🟠 PeakPickerIM: bruker:dia_ms2_min_support minimum lowered from 1 → 0 to match FileConverter and BrukerTimsFile::Config, allowing users to disable DIA-MS2 denoising.
  • 🟡 centroidFrame: guard against min_hill_length == 0 (would underflow idx in splitHills); silently clamps to 1.
  • 🟡 FileConverter help text: centroid_min_hill_length → ms1_centroid_min_hill_length (was pointing users at a nonexistent flag).

Plus a defensive mz_cur <= 0.0 skip in the linker to avoid a div-by-zero in the ppm calculation on pathological inputs.

Synthetic PASEFHillCentroider_test passes (0.04 s) with the new clamp/guard tests. Long real-data BrukerTimsFile_test is rebuilding locally now.

@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: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openms/source/FORMAT/HANDLERS/PASEFHillCentroider.cpp`:
- Around line 447-482: The fallback path groups by im_values but still allows
hills/tails to carry between successive IM groups, effectively treating every
group as adjacent; to prevent over-merging, after processing each IM group (the
block that builds cur_mz/cur_int/cur_fm and calls linkScan) invoke
pruneAndIndexTails/tidy the rolling tails to break continuity between
non-consecutive IM groups — e.g., call pruneAndIndexTails(tails, hills,
tails_by_fm, 0) (or otherwise clear/flush tails and re-index hills) before
advancing i0 so that p.max_scan_gap is not ignored when scan_indices are absent;
update usage around linkScan, pruneAndIndexTails, tails, hills, kept, and
im_values accordingly.

In `@tools/scripts/plot_pasef_frames.py`:
- Around line 266-307: The help text for the --show-hill-bounds option is
inaccurate: panel() draws every hill rectangle present in hill_bounds (filtered
only for multi-scan hills), not just the top-N overlay peaks; update the
option/argument help string to state that it will render all detected hill
bounding boxes (multi-scan hills) so users won't expect only top-N peaks. Locate
the option definition for "--show-hill-bounds" (and any duplicated help text
around the same option, noted also near the other occurrence) and change the
description to mention it draws all hill rectangles from hill_bounds (multi-peak
hills with im_hi > im_lo), not just overlayed top-N peaks, and ensure
consistency with the behavior in panel().

In `@tools/scripts/visualize_pasef_centroiding.py`:
- Around line 151-178: Choose a single anchor spectrum ID and use it to select
matching spectra in all inputs instead of independently picking the "first
non-empty" per column: resolve an anchor_native_id by calling first_nonempty on
a chosen reference exp (e.g., the first item in exps) for MS1 and MS2, decode
bytes via getNativeID(), then replace the per-column ms1_idx/ms2_idx selection
with a lookup that scans each exp for a spectrum whose getNativeID() (decoded)
equals anchor_native_id and has the required ms level; if no match is found in
an exp, fall back to first_nonempty(exp, 1, index=ms1_index) or
first_nonempty(exp, 2, index=ms2_index) as before; apply this for both the MS1
loop (where ms1_idx is set) and the MS2 loop (ms2_idx), and keep using
panel(...) and last_sc unchanged.
- Around line 77-91: extract_peaks currently always uses the first
FloatDataArray which can be the wrong per-peak IM array; change it to search the
spectrum's getFloatDataArrays() for a named IM array (e.g. "IM_PEAK" or
"IM_CENTROIDED") and use that if present, otherwise fall back to
FloatDataArrays[0]; keep the existing defensive try/except and size checks (use
im_arr.size() to build the numpy array and set im=None on failure) so
extract_peaks returns (mz, intensity, im) as before but with the correct
per-peak IM selected.
🪄 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: 208daebd-e296-407b-add5-9bd82405a4dd

📥 Commits

Reviewing files that changed from the base of the PR and between 778cb12 and 91db53e.

📒 Files selected for processing (14)
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/PASEFHillCentroider.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/sources.cmake
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/openms/source/FORMAT/HANDLERS/PASEFHillCentroider.cpp
  • src/openms/source/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/CMakeLists.txt
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • src/tests/class_tests/openms/source/PASEFHillCentroider_test.cpp
  • src/topp/FileConverter.cpp
  • src/topp/PeakPickerIM.cpp
  • tools/scripts/plot_pasef_frames.py
  • tools/scripts/visualize_pasef_centroiding.py
✅ Files skipped from review due to trivial changes (2)
  • src/openms/include/OpenMS/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/CMakeLists.txt
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/tests/class_tests/openms/executables.cmake
  • src/openms/source/FORMAT/HANDLERS/sources.cmake
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/PASEFHillCentroider.h
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/topp/PeakPickerIM.cpp
  • src/topp/FileConverter.cpp

Comment thread tools/scripts/plot_pasef_frames.py Resolved
@timosachsenberg
timosachsenberg force-pushed the feat/timstof-hill-centroiding branch from 91db53e to 162b3a8 Compare May 11, 2026 17:13
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Force-pushed 162b3a8 addressing the second CodeRabbit round (4 new findings):

🟠 PASEFHillCentroider.cpp:482 — fallback path was silently allowing max_scan_gap bridging.
The no-scan_indices branch grouped peaks by IM value and iterated only non-empty groups; the comment claimed max_scan_gap was effectively 0 here but that wasn't true — tails carried across all IM-group transitions. Fixed by forcing pruneAndIndexTails(..., 0) in the fallback (drops unextended tails after every group) and documenting the constraint on Params::max_scan_gap: it requires scan_indices to be meaningful, otherwise gap=0 is used. The BrukerTimsFile integration always passes scan_indices, so the production code path is unchanged.

🟡 --show-hill-bounds help text was inaccurate. Said "for each top-N centroid" but the code draws every multi-scan hull. Rewrote help to reflect actual behaviour ("for every multi-scan hill, independent of --overlay-top").

🟠 visualize_pasef_centroiding.py::extract_peaks blindly read FloatDataArrays[0]. With expose_hill_bounds=true the IM array may not be slot 0; switched to a named lookup ("raw inverse reduced ion mobility array" / "inverse reduced ion mobility array") with the old behaviour as a fallback.

🟠 visualize_pasef_centroiding.py picked "first non-empty" per column. If centroiding dropped a spectrum, the three columns would end up showing different physical frames while looking comparable. Now anchors to the first input's nativeID and resolves the same frame in each other input by name (falling back to first_nonempty if not found).

Synthetic PASEFHillCentroider_test still passes; long real-data test from the prior commit (1191s) covers the same code paths.

@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)
tools/scripts/plot_pasef_frames.py (1)

291-299: 💤 Low value

Drop the semicolon-joined statements to satisfy PEP 8 (E702).

CodeFactor is still flagging lines 292–293 for Multiple statements on one line (semicolon). Trivial cleanup that keeps the rest of the loop body PEP 8-clean.

♻️ Proposed cleanup
             for k in idxs:
-                x_lo = float(mz_lo_arr[k]); x_hi = float(mz_hi_arr[k])
-                y_lo = float(im_lo_arr[k]); y_hi = float(im_hi_arr[k])
+                x_lo = float(mz_lo_arr[k])
+                x_hi = float(mz_hi_arr[k])
+                y_lo = float(im_lo_arr[k])
+                y_hi = float(im_hi_arr[k])
                 w = x_hi - x_lo
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/scripts/plot_pasef_frames.py` around lines 291 - 299, The loop body in
plot_pasef_frames.py uses semicolon-joined statements (e.g., "x_lo =
float(mz_lo_arr[k]); x_hi = float(mz_hi_arr[k])" and "y_lo =
float(im_lo_arr[k]); y_hi = float(im_hi_arr[k])") which violates PEP8 E702;
change those to separate statements so each assignment is on its own line
(inside the for k in idxs loop where x_lo/x_hi, y_lo/y_hi are computed and
before computing w and appending Rectangle) while keeping the existing logic for
computing cx, adjusting x_lo/x_hi when w < min_w_mz, and the
rects.append(Rectangle(...)) call unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/openms/source/FORMAT/HANDLERS/PASEFHillCentroider.cpp`:
- Around line 249-259: The loop that skips peaks with mz_cur <= 0.0 leaves
cur_peak_to_tail[i] at std::numeric_limits<int>::min(), which later gets
transformed with (-v - 1) and triggers undefined behavior when v == INT_MIN; fix
it by explicitly assigning a safe sentinel or early-continued state for those
skipped peaks and/or guarding the decode site: in PASEFHillCentroider.cpp update
the block handling cur_mz (variables order, cur_mz, cur_fm, cur_peak_to_tail) so
that when mz_cur <= 0.0 you set cur_peak_to_tail[i] to a known sentinel
(std::numeric_limits<int>::min()) and continue, and at the decode location that
performs (-v - 1) check if v == std::numeric_limits<int>::min() before
negating/decoding and skip/handle accordingly to avoid negating INT_MIN.

---

Nitpick comments:
In `@tools/scripts/plot_pasef_frames.py`:
- Around line 291-299: The loop body in plot_pasef_frames.py uses
semicolon-joined statements (e.g., "x_lo = float(mz_lo_arr[k]); x_hi =
float(mz_hi_arr[k])" and "y_lo = float(im_lo_arr[k]); y_hi =
float(im_hi_arr[k])") which violates PEP8 E702; change those to separate
statements so each assignment is on its own line (inside the for k in idxs loop
where x_lo/x_hi, y_lo/y_hi are computed and before computing w and appending
Rectangle) while keeping the existing logic for computing cx, adjusting
x_lo/x_hi when w < min_w_mz, and the rects.append(Rectangle(...)) call
unchanged.
🪄 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: 4ca14cb6-5600-4e75-8198-baea8cf8f819

📥 Commits

Reviewing files that changed from the base of the PR and between 91db53e and 162b3a8.

📒 Files selected for processing (14)
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/PASEFHillCentroider.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/sources.cmake
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/openms/source/FORMAT/HANDLERS/PASEFHillCentroider.cpp
  • src/openms/source/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/CMakeLists.txt
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • src/tests/class_tests/openms/source/PASEFHillCentroider_test.cpp
  • src/topp/FileConverter.cpp
  • src/topp/PeakPickerIM.cpp
  • tools/scripts/plot_pasef_frames.py
  • tools/scripts/visualize_pasef_centroiding.py
✅ Files skipped from review due to trivial changes (2)
  • src/openms/include/OpenMS/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/executables.cmake
🚧 Files skipped from review as they are similar to previous changes (9)
  • src/openms/include/OpenMS/FORMAT/HANDLERS/PASEFHillCentroider.h
  • src/openms/source/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/CMakeLists.txt
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/topp/PeakPickerIM.cpp
  • src/tests/class_tests/openms/source/PASEFHillCentroider_test.cpp
  • src/topp/FileConverter.cpp
  • src/openms/source/FORMAT/BrukerTimsFile.cpp

@timosachsenberg
timosachsenberg force-pushed the feat/timstof-hill-centroiding branch from 162b3a8 to 959446b Compare May 11, 2026 17:49
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Force-pushed 959446b addressing the 🔴 Critical finding on the latest scan.

PASEFHillCentroider.cpp:259 — undefined behavior on negating INT_MIN.
My earlier mz_cur <= 0.0 guard continued without writing cur_peak_to_tail[i], leaving it at the initial INT_MIN sentinel. The apply loop then took the else branch on v < 0 and computed -v - 1 — negating INT_MIN is UB and the resulting Size would have indexed past the end of hills. Fixed by:

  • Renaming the sentinel to a named constexpr int k_unassigned = INT_MIN.
  • Adding if (v == k_unassigned) continue; at the top of the apply loop.
  • Documenting in the comment that the new-hill decoding branch is now only reached for values in [INT_MIN+1, -1].

PASEFHillCentroider_test still green (0.04 s). All 11 CodeRabbit review threads are now resolved.

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tools/scripts/visualize_pasef_centroiding.py`:
- Around line 116-145: In panel(), the mz_window mask is applied after the
initial mz.size==0 guard, so if the window filters out all peaks subsequent
log_int.min()/max() will crash; fix by checking for emptiness immediately after
applying the mz_window mask (i.e., after computing mask and updating mz,
intensity, and im) and returning early with the same empty-panel behavior (set
title to "(empty)" and return None) to avoid operating on empty arrays used
later in log_int and sizes; refer to function panel, variable mz_window, mask,
im, log_int, and sizes to locate 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: 89fb9c98-898a-4bf7-b6ae-3f3d98c0676e

📥 Commits

Reviewing files that changed from the base of the PR and between 162b3a8 and 959446b.

📒 Files selected for processing (14)
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/PASEFHillCentroider.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/sources.cmake
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/openms/source/FORMAT/HANDLERS/PASEFHillCentroider.cpp
  • src/openms/source/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/CMakeLists.txt
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • src/tests/class_tests/openms/source/PASEFHillCentroider_test.cpp
  • src/topp/FileConverter.cpp
  • src/topp/PeakPickerIM.cpp
  • tools/scripts/plot_pasef_frames.py
  • tools/scripts/visualize_pasef_centroiding.py
✅ Files skipped from review due to trivial changes (2)
  • src/openms/include/OpenMS/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/executables.cmake
🚧 Files skipped from review as they are similar to previous changes (9)
  • src/openms/source/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/CMakeLists.txt
  • src/tests/class_tests/openms/source/PASEFHillCentroider_test.cpp
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/topp/FileConverter.cpp
  • src/openms/include/OpenMS/FORMAT/HANDLERS/PASEFHillCentroider.h
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • src/topp/PeakPickerIM.cpp
  • src/openms/source/FORMAT/BrukerTimsFile.cpp

Add a hill-detection centroider for Bruker TIMS-PASEF data that links
peaks across consecutive IM scans within a frame by m/z proximity,
splits chains at intensity valleys, and emits one centroid per surviving
hill. Modeled on Biosaur2's linkScanToHills_ / splitHills_ but with IM
scans playing the role of consecutive RT spectra.

Centroider (new): OpenMS::Internal::PASEFHillCentroider::centroidFrame
in src/openms/{include,source}/FORMAT/HANDLERS/PASEFHillCentroider.{h,cpp}.
- Parameters: mz_tol_ppm, valley_factor (Biosaur2 hvf), min_hill_length,
  min_intensity, im_group_tolerance, max_scan_gap.
- Optional scan_indices array enables gap detection: when provided, the
  driver iterates every IM scan index from min..max (including empty
  ones) so max_scan_gap can bridge missing scans. Without it, grouping
  falls back to IM-value clustering.
- Aging-based linker: each active hill has a "tail" that ages by one
  per scan it isn't extended in; tails older than max_scan_gap are
  pruned. Length-1 starter hills cannot bridge any gap regardless of
  max_scan_gap, which prevents two unrelated single-scan noise blips
  from chaining into a false length-2 hill.
- Returns Centroid records with intensity-weighted m/z, summed
  intensity, IM apex, and (m/z, IM) bounding-box bounds.

BrukerTimsFile integration:
- New Config fields: ms{1,2}_centroid_algo (Off/Greedy2D/HillBased),
  ms{1,2}_centroid_mz_ppm, centroid_valley_factor,
  ms{1,2}_centroid_min_hill_length, centroid_max_scan_gap,
  expose_hill_bounds.
- MS1 path (single-frame and aggregated), DIA-MS2 path (aggregated and
  raw n_neighbors=0), and DDA-MS2 path all dispatch through the new
  helpers and pass through scan_ids when available so max_scan_gap is
  meaningful.
- DIA-MS2 HillBased works at dia_ms2_n_neighbors=0 (per-frame hill
  linking, no cross-RT summing) in addition to the aggregated path.
- DDA-MS2 HillBased operates on per-precursor (m/z, intensity, IM)
  triples; output schema unchanged (scalar drift_time per spectrum).
- expose_hill_bounds=true attaches four extra FloatDataArrays per
  centroided spectrum ("im lower bound", "im upper bound", "m/z lower
  bound", "m/z upper bound") for downstream visual QC.

Tuned defaults (DIA-PASEF baseline; DDA-PASEF callers should override
ms2_centroid_min_hill_length=1):
  ms1_centroid_mz_ppm        : 10 (was 0)
  ms2_centroid_mz_ppm        : 20 (was 0)
  ms2_centroid_min_hill_length: 2 (was 1)
  dia_ms2_n_neighbors        : 2 (was 0)
The MS1 10 ppm default is empirically supported: on the bundled DIA
fixture, 5 ppm captured only ~4% of MS1 peaks as multi-scan hills vs
~9% at 10 ppm; 15/20 ppm yield diminishing returns. The MS2 defaults
match the "nn=2 / min=2 / 20 ppm" recipe that was the best balanced
output in the sweep comparison plots.

CLI: full set of -bruker:* flags exposed on FileConverter and
PeakPickerIM, with help text documenting the empirical tradeoffs.

Tests:
- New synthetic test PASEFHillCentroider_test covers: empty input,
  isolated peak, valley split, min_hill_length filter, sparse-data
  mode (min=1), m/z tolerance, determinism, min_intensity, no-split
  smooth peak, sorted output, gap=0/1/2 behavior, and the
  consecutive-link-before-gap rule.
- BrukerTimsFile_test extended (behind ENABLE_OPENTIMS_TESTS) with
  hill-vs-greedy comparisons on real DDA and DIA .d data. Test timeout
  bumped to accommodate the longer DIA/DDA load passes.

Visualization (tools/scripts/plot_pasef_frames.py, new):
- Renders N MS1 and N MS2 frames in a grid (rows = TIC-quantile
  frames, cols = inputs) for side-by-side centroiding comparison.
- Datashader-style 1-bin-per-pixel rendering with max log10(intensity)
  aggregation; per-row shared m/z and 1/K0 axes; globally shared
  intensity colormap.
- Optional top-N intensity overlay (colored outlined circles), and
  full hill bounding boxes drawn around every length>=2 hill when the
  mzML carries the expose_hill_bounds arrays.
- Always-on figure banner: suptitle shows the plot options (mode,
  pick, overlay_top, show_hill_bounds, mz_window), and a bottom-left
  monospace footer lists each input's bruker:* conversion parameters
  parsed from the mzML's <dataProcessingList>. Figures are
  self-describing — opening any PNG answers "what setup produced this
  column?" without going back to shell history.

Visualize entry point (tools/scripts/visualize_pasef_centroiding.py,
new): single-frame variant of the same comparison.
@timosachsenberg
timosachsenberg force-pushed the feat/timstof-hill-centroiding branch from 959446b to 4909b42 Compare May 11, 2026 19:25
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Force-pushed 4909b42 for the latest CodeRabbit finding (1 minor):

visualize_pasef_centroiding.py::panel — empty-after-mz-window not guarded. The initial mz.size == 0 check ran before the mz_window mask was applied, so a window that filters out every peak (e.g. an MS2 spec with no fragments in 100–200 m/z) would reach log_int.min() on an empty array and crash. Added a second mz.size == 0 check immediately after the mask with an "empty in m/z window" panel title.

All 12 review threads now resolved.

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/topp/FileConverter.cpp`:
- Around line 194-204: The default change for the option
"bruker:ms1_centroid_mz_ppm" from 0→10 silently enables the GREEDY2D legacy path
when only ms1_centroid_im_pct is set; revert the registered default back to 0.0
via registerDoubleOption_ / setMinFloat_ and instead apply the tuned default
inside getBrukerConfig_: if ms1_centroid_algo == HILL_BASED and the user did not
override ms1_centroid_mz_ppm (value == 0), substitute 10.0 there so the default
only applies when hillbased is selected (leave GREEDY2D activation logic
unchanged which checks ms1_centroid_algo, ms1_centroid_mz_ppm, and
ms1_centroid_im_pct); also ensure documentation/release notes call out the
behavioral 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: 85b5c8a5-2bf7-40ad-9795-cb012c982642

📥 Commits

Reviewing files that changed from the base of the PR and between 959446b and 4909b42.

📒 Files selected for processing (14)
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/PASEFHillCentroider.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/sources.cmake
  • src/openms/source/FORMAT/BrukerTimsFile.cpp
  • src/openms/source/FORMAT/HANDLERS/PASEFHillCentroider.cpp
  • src/openms/source/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/CMakeLists.txt
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • src/tests/class_tests/openms/source/PASEFHillCentroider_test.cpp
  • src/topp/FileConverter.cpp
  • src/topp/PeakPickerIM.cpp
  • tools/scripts/plot_pasef_frames.py
  • tools/scripts/visualize_pasef_centroiding.py
✅ Files skipped from review due to trivial changes (3)
  • src/openms/include/OpenMS/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/executables.cmake
  • src/openms/include/OpenMS/FORMAT/HANDLERS/PASEFHillCentroider.h
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/openms/source/FORMAT/HANDLERS/sources.cmake
  • src/tests/class_tests/openms/CMakeLists.txt
  • src/topp/PeakPickerIM.cpp
  • src/tests/class_tests/openms/source/BrukerTimsFile_test.cpp
  • src/tests/class_tests/openms/source/PASEFHillCentroider_test.cpp
  • src/openms/include/OpenMS/FORMAT/BrukerTimsFile.h
  • src/openms/source/FORMAT/BrukerTimsFile.cpp

Comment on lines +194 to 204
registerDoubleOption_("bruker:ms1_centroid_mz_ppm", "<float>", 10.0,
"MS1 m/z linking tolerance in ppm. HillBased default 10 ppm is tuned for "
"detector-centroided TIMS-PASEF MS1: real ions drift up to ~10 ppm in m/z "
"between consecutive IM scans, so 5 ppm under-links — empirically only ~4% "
"of MS1 hills end up multi-scan at 5 ppm vs ~9% at 10 ppm. Greedy2D also "
"uses this and additionally requires ms1_centroid_im_pct > 0.",
false, true);
setMinFloat_("bruker:ms1_centroid_mz_ppm", 0.0);
registerDoubleOption_("bruker:ms1_centroid_im_pct", "<float>", 0.0,
"MS1 frame IM-centroiding ion mobility tolerance in percent. Both this and ms1_centroid_mz_ppm "
"must be > 0 to enable. Suggested value: 3.0.", false, true);

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 | ⚡ Quick win

Default change for bruker:ms1_centroid_mz_ppm (0 → 10) silently flips the GREEDY2D back-compat path for users who only set ms1_centroid_im_pct.

The legacy back-compat (lines 256–259) activates GREEDY2D when ms1_centroid_algo=off AND ms1_centroid_mz_ppm > 0 AND ms1_centroid_im_pct > 0. Previously, both had to be explicitly set to non-zero. Now, with ms1_centroid_mz_ppm defaulting to 10.0, a user who only sets ms1_centroid_im_pct=3 (and leaves ms1_centroid_algo and ms1_centroid_mz_ppm unset) will silently switch from "no centroiding" to GREEDY2D at 10 ppm.

Per PR objectives ("Tuned defaults applied only when hill algo is selected"), consider whether this default should only take effect when ms1_centroid_algo=hillbased (e.g. keep the registered default at 0 and let getBrukerConfig_ substitute 10.0 when algo == HILL_BASED and the user didn't override it). At minimum, this default change should be called out in the release notes / migration docs.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/topp/FileConverter.cpp` around lines 194 - 204, The default change for
the option "bruker:ms1_centroid_mz_ppm" from 0→10 silently enables the GREEDY2D
legacy path when only ms1_centroid_im_pct is set; revert the registered default
back to 0.0 via registerDoubleOption_ / setMinFloat_ and instead apply the tuned
default inside getBrukerConfig_: if ms1_centroid_algo == HILL_BASED and the user
did not override ms1_centroid_mz_ppm (value == 0), substitute 10.0 there so the
default only applies when hillbased is selected (leave GREEDY2D activation logic
unchanged which checks ms1_centroid_algo, ms1_centroid_mz_ppm, and
ms1_centroid_im_pct); also ensure documentation/release notes call out the
behavioral change.

/// same IM scan. 0.0 means exact equality. TIMS calibration produces
/// discrete IM values per scan index, so exact equality usually works;
/// callers that have float-cast their IM values may want a small epsilon.
double im_group_tolerance = 0.0;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could be set to something small. 1e-6

@alhigaylan

alhigaylan commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator

I believe this is similar to the idea of pickIMElutionProfiles within PeakPickerIM. It repurposed MassTraceDetection algorithm to find centroids within one PASEF frame. I recall for that implementation, speed was an issue compared to pickIMCluster and pickIMTraces. Can you do a quick time benchmark to assess how this PR compares to pickIMElutionProfiles centroiding?

Second, I believe Biosaur and MassTraceDetection both assume a centroided data input. If we try to repurpose them for centroiding a PASEF Frame, how will it handle scan aggregation? At least for the case of MassTraceDetection, I know that if we aggregate scans to boost s/n, this will result in multiple mass traces (or in this case centroids) per one genuine peak. Does this PR address this issue? We will likely want Biosaur hill construction to allow collection of multiple peaks per scan.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

So far it does not address it and it could result in multiple traces with similar m/z right now. I can add some merging etc. but I would like to see how this currently performs (#ids at fdr) for the different n_neighbor options.
n_neighbor has the largest impact on speed right now.

timosachsenberg and others added 7 commits May 13, 2026 17:29
Adds `CentroidAlgo::PEAK_PICKER_IM` next to `HILL_BASED` / `GREEDY2D`,
wiring `OpenMS::PeakPickerIM::pickIMTraces` (mobilogram pipeline) into
all four MS1 + DIA-MS2 load paths (single-frame, RT-aggregated, DIA-MS2
raw, DIA-MS2 aggregated). DDA-MS2 rejects PeakPickerIM with a warn-and-
fallback (PeakPickerIM expects per-peak IM arrays; DDA-MS2 emits scalar
drift_time). Parameters forwarded via a single `peak_picker_im_params`
Param on Config (sparse overlay onto PeakPickerIM's own defaults).

Auxiliary FloatDataArrays emitted by PeakPickerIM (the renamed
"Ion Mobility Centroid" IM array, FWHM_im, etc.) pass through to output
via a temp-MSSpectrum helper that inherits the target spec's
SpectrumSettings before invoking the picker.

CLI: FileConverter and TOPPPeakPickerIM gain `peakpickerim` in
`bruker:ms{1,2}_centroid_algo` valid strings. TOPPPeakPickerIM also
forwards its `algorithm:` subsection to `config.peak_picker_im_params`
so loader and post-load runs share tuning.

Visualization: plot_pasef_frames.py + visualize_pasef_centroiding.py
recognize the "Ion Mobility Centroid" array name.

Tests: new DIA section (MS1 + DIA-MS2 raw) and DDA fallback section,
behind ENABLE_OPENTIMS_TESTS. CTest timeout bumped from 2400 → 3600 s
for the PeakPickerIM mobilogram pipeline (the slowest centroider).

Hill paths refactored along the way (semantics-preserving):
- Single `runHillCentroider(Params&, ...)` replaces `runMS1Centroider`'s
  HILL branch, `runMS2HillCentroider`, and the inline DDA-MS2 hill
  Params build. `makeMS{1,2}HillParams` factories centralise the
  Config → Params mapping.
- `aggregatorPeaksToBuffers` helper dedupes the (mz, intensity, IM
  [, scan_id]) build loop across three aggregator-consuming sites.
- DDA-MS2 hill path drops a redundant `iota + std::sort` on output
  that's already m/z-sorted by PASEFHillCentroider.
- effectiveMS2Algo split into effectiveDIAMS2Algo / effectiveDDAMS2Algo
  so context-specific warnings (PeakPickerIM rejected on DDA, HillBased
  mz_ppm precondition) fire at the right loader entry.

Doc fix at BrukerTimsFile.h:81-82: strike the (false) claim that
HillBased fires only inside the aggregated DIA path — both HillBased
and PeakPickerIM run at any aggregation level.

Verified on the bundled DIA fixture: PEAK_PICKER_IM produces 28.6M MS1
+ 6.04M MS2 peaks across 353/7282 spectra, identical before and after
the refactor.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds `pickIMTraces:expose_bounds` Param (default false). When true,
attaches four FloatDataArrays per centroided spectrum giving each
centroid's FWHM support window:
  - "im lower bound"  = centroid_im - IM_FWHM/2
  - "im upper bound"  = centroid_im + IM_FWHM/2
  - "m/z lower bound" = spline FWHM left endpoint
  - "m/z upper bound" = spline FWHM right endpoint

Names match PASEFHillCentroider's `expose_hill_bounds` output so visual
QC tooling (`plot_pasef_frames.py --show-hill-bounds`) renders bounding
boxes uniformly for hill and PeakPickerIM centroiders. Semantics differ:
hill = source-peak extent, PeakPickerIM = FWHM support window. Documented
in the Param description and in BrukerTimsFile::Config::expose_hill_bounds.

BrukerTimsFile wires `Config::expose_hill_bounds=true` to set the picker
Param transitively when CentroidAlgo::PEAK_PICKER_IM is selected, so the
existing top-level flag works for both algorithms. The "no effect with
PEAK_PICKER_IM" warning is removed.

`removeAllFloatDataArraysExcept` generalized from a single keep-name to
a `std::set<String>` so the bounds arrays can survive the post-pick strip
alongside `Ion Mobility Centroid`. Only callers are internal to
PeakPickerIM.cpp (pickIMCluster / pickIMElutionProfiles call sites updated
to pass `{ION_MOBILITY_CENTROID}` braced).

Bit-identical default output (expose_bounds=false). The four new array
names already had a single producer (hill) and a single consumer
(plot_pasef_frames.py); no downstream tool distinguishes algorithms by
array-name presence, so reusing the names is safe.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds an opt-in MS1 + DIA-MS2 prefilter (`Config::isotopic_prefilter`,
default off) that drops peaks lacking an isotopic partner at
m/z ± C13C12_MASSDIFF_U / q (for q in {1..5}) within
± `isotopic_prefilter_tol_da` (default 0.05 Da) AND |Δscan_id| <= 1.
Cleans up isolated detector-noise singletons before centroiding; both
the monoisotopic peak and the isotopologue survive (mutual evidence).
Pure existence check — no intensity-ratio or averagine model.

The prefilter sits at every centroiding entry point after aggregation
(or after raw extraction when aggregation is disabled):
  - centroidMS1Frame (MS1 single-frame, all algos)
  - loadAggregatedMS1Spectrum (MS1 aggregated, all algos incl. OFF)
  - DIA-MS2 aggregated (HILL / PPIM / GREEDY2D / OFF)
  - DIA-MS2 raw (HILL / PPIM / OFF)
Not applied to DDA-MS2 (no per-peak IM array). Per-frame INFO log lists
the drop count and percentage.

To make this clean across the four sites, the parallel-vector pattern
(`mz / intensity / im / scan_ids` as four separate `std::vector`s) is
bundled into a `FrameBuffers` struct with a templated in-place
`filter(Keep)` compaction. The struct also unifies the four sites'
algo dispatch: each site builds buf once, applies the prefilter, then
dispatches HILL / PPIM / GREEDY2D / OFF off the same buffers.

`aggregatorPeaksToBuffers` is updated to fill a `FrameBuffers`
(replaces the four-vector reference signature). All three callers
updated.

CLI exposure: `-bruker:isotopic_prefilter <true|false>` and
`-bruker:isotopic_prefilter_tol_da <float>` on both `FileConverter`
and `TOPPPeakPickerIM`.

Empirical drop rates on the bundled DIA fixture (informational, not
a regression target):
  - MS1 frame 1 (heavy signal):   ~7%
  - MS1 frames 10+ (typical):     ~42–48%
  - DIA-MS2 raw (typical):        95–100%
The high MS2 drop is intentional — most DIA-MS2 fragments are isolated
singletons whose M+1 is below the detector noise floor. Users wanting
gentler MS2 behavior can widen `isotopic_prefilter_tol_da` or leave the
flag off (default).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
PeakPickerHiRes is documented for profile-mode data with approximately
uniform m/z spacing and uses a `spacing_difference` heuristic (default
1.5×) to decide whether adjacent samples belong to the same profile peak.
`pickIMTraces` hands it the output of `sumFrame_`, which is sparse and
non-uniform — it preserves only the m/z values where input peaks existed.
On aggregator output the apex spacings are ~0.2 mDa while inter-cluster
gaps reach ~25 mDa; the spacing_difference heuristic then declares every
cluster boundary as "missing samples" and refuses to extend peaks, silently
dropping the apex of every real ion.

Verified concretely on the bundled DIA fixture frame=2048 windowGroup=4
scan=658, m/z 615.0..615.2: the Gauss-smoothed projection contains two
clean Gaussian peaks (apex intensities 842 and 1010), but PPHR with the
default heuristic picks zero peaks there. Hill emits 11 centroids in the
same window. After the fix PeakPickerIM emits 20 centroids (more than
hill because PPIM resolves per-(m/z × IM) while hill emits per-IM-chain).

The fix is symmetric with what `pickIMTraces` already does for the IM
dimension below (step 4a uses LinearResamplerAlign on each mobilogram
trace before SGolay + IM peak picking): insert a LinearResamplerAlign
between the Gauss filter and PPHR so PPHR sees uniform-spaced profile
data, which is what its `spacing_difference` heuristic assumes. Resolution
is set ppm-relative to match the Gauss filter tolerance.

Resampling does not degrade final m/z accuracy: the picked m/z is only
used to define the FWHM window for mobilogram extraction; the final
reported centroid m/z is recomputed from the original (non-resampled)
raw spectrum in `computeCentroids_` via cubic-spline bisection.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
PeakPickerIM emits FWHM-derived bounding boxes that average ~1 mDa wide
in m/z (vs ~7 mDa for hill's source-peak extent). At full-spectrum
overview scale (~hundreds of Da per panel), 1 mDa is sub-pixel and the
boxes disappear into the datashade background.

The existing `min_w_mz` padding (`* 0.0004 → ~0.08 mDa @ 200 Da span`)
only catches strictly degenerate boxes (mz_lo == mz_hi). Bump the
multiplier to 0.0008 (~0.16 mDa @ 200 Da span) so any too-narrow box
gets padded enough to remain visible at the rendered scale. Doesn't
affect targeted zooms where the m/z window is narrow enough that
PPIM's native FWHM widths are already visible.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The isotopic-partner-search tolerance was previously an absolute Da
window (default 0.05 Da). MS tolerances are conventionally mass-relative
and the rest of the loader (PeakPickerHiRes, GaussFilter, hill linking)
all use ppm. Renaming + switching to ppm keeps the API consistent and
makes the absolute window scale naturally with m/z:

  50 ppm @ m/z 200  = 0.010 Da
  50 ppm @ m/z 1000 = 0.050 Da   (the old fixed default)
  50 ppm @ m/z 2000 = 0.100 Da

Changes:
  - Config field `isotopic_prefilter_tol_da` → `isotopic_prefilter_tol_ppm`
    (default 0.05 → 50.0)
  - Helper signature `isotopicPrefilter(buf, tol_ppm)`; internally
    converts to absolute Da per target m/z (`target * tol_ppm * 1e-6`).
  - CLI `-bruker:isotopic_prefilter_tol_da` → `-bruker:isotopic_prefilter_tol_ppm`
    on both FileConverter and TOPPPeakPickerIM.
  - Help text updated to describe ppm semantics.

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

2 participants