Skip to content

[FIX] PrecursorCorrection: replace exhaustive feature overlap loop with an m/z sweep (#4787) - #9801

Merged
timosachsenberg merged 5 commits into
developfrom
fix/precursorcorrection-overlap-4787
Jul 27, 2026
Merged

timosachsenberg merged 5 commits into
developfrom
fix/precursorcorrection-overlap-4787

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #4787.

PrecursorCorrection::correctToNearestFeature() compared every MS2 precursor against every feature — the 812,631,750 overlap checks in the issue. Two things made that expensive: the Cartesian product itself, and the fact that ConvexHull2D::getBoundingBox() is not memoized (only Feature::getConvexHull() is), so each feature's match region was rebuilt on all ~8e8 evaluations.

Confirmed on a Release build before touching anything, at the issue's own scale — 30,000 MS2 spectra × 27,000 features = 8.1e8 checks: 26.7 s, scaling exactly quadratically. With single-trace features (where getConvexHull() returns the trace hull itself rather than a 4-point merged box, so getBoundingBox() walks the whole polygon) the same work costs ~4× more per check.

What changed

Each feature's extended bounding box is computed once, and candidates come from a sweep line over increasing precursor m/z: a feature is activated when its m/z interval starts and retired once it ends, so a precursor is only compared against features whose m/z interval actually contains it. Candidate search goes from O(F*Q) to O(F log F + Q log Q + K), with K the number of genuinely m/z-overlapping pairs visited.

The match predicate has exactly one definition: the file-local makeFeatureBox() plus FeatureBox::contains().

The only header change is a removal. The protected static helper overlaps_() is gone: the sweep evaluates each feature's pre-computed box directly, which left the helper without a caller anywhere in the tree. It was protected on a class whose entire public API is static, so nothing could reach it short of subclassing an all-static utility class; it was not exposed through pyOpenMS, and the class test has a START_SECTION for every other method but never had one for it. Keeping it would also have been quietly inconsistent — it retained the old per-call warning while the sweep emits a single counted line, so the two paths logged differently for identical input despite agreeing on the result. Removing a protected member is an API break only for a subclass, and there is none in the tree.

Performance

Mean over repeats, hull caches pre-warmed so this times matching rather than cache population:

MS2 × features before after speedup
1 × 1 1.25 µs 1.33 µs 0.94×
10 × 10 14.3 µs 12.6 µs 1.13×
100 × 100 0.43 ms 0.16 ms 2.68×
500 × 500 7.65 ms 0.86 ms 8.95×
2000 × 2000 112.5 ms 3.45 ms 32.7×
10000 × 10000 2.77 s 19.5 ms 142×
30000 × 27000 26.7 s 0.076 s 351×
10 × 20000 39.8 ms 34.8 ms 1.14×
20000 × 10 5.71 ms 3.24 ms 1.76×
2000 × 2000, single-trace hulls 0.45 s 0.76 ms 596×

Break-even is around 10×10; below that the extra sorting and allocation costs ~80 ns, which is why there's no small-input fast path — it isn't worth a second code path. Even in the degenerate case where every feature's m/z interval spans the whole axis (so K really is F*Q and no pruning is possible) it stays ~3.4× ahead, because the box is no longer rebuilt per pair.

Auxiliary memory is 48 bytes per feature and 16 per MS2 spectrum — roughly 1.7 MB at 27k/30k.

Both sorts carry their key alongside the index so the comparator reads plain doubles from contiguous memory. This mattered: comparing via exp[i].getPrecursors()[0].getMZ() instead made the Q >> F shape (20,000 spectra, 10 features) 2× slower than the original loop, because O(Q log Q) expensive comparisons lose to O(Q*F) cheap ones when F is tiny.

Why not the kd-tree the issue suggests

KDTreeFeatureMaps indexes feature centroids (addFeature caches feature->getRT(); KDTreeFeatureNode::operator[] returns centroid RT/m/z), but the match predicate tests the feature's hull bounding box extended by rt_tolerance. Those coincide only if the hull is a point at the centroid. Since HighResPrecursorMassCorrector's feature:rt_tolerance defaults to 0.0, a centroid query loses almost everything.

Demonstrated on this repo's own fixture HighResPrecursorMassCorrector_2538_1091_2: the feature's centroid is at RT 2538.83 while its hull spans [2529.76, 2572.45]. The shipped predicate accepts 2 MS2/feature pairs there and corrects 2 precursors; a centroid window of [rt, rt] retrieves 0. That is why the earlier attempt (#8694) was wrong despite claiming identical results — it would have failed the existing TOPP test.

Correctness

The matching predicate is unchanged, and deliberately so in the details:

  • makeFeatureBox() uses the same DBoundingBox setMin()/setMax() sequence the per-pair check always used, rather than raw scalar arithmetic. Those mutators normalize, so raw arithmetic diverges when rt_tolerance is negative (which the public API and the TOPP option both permit).
  • FeatureBox::contains() is spelled as the negation of "outside", because DBoundingBox::encloses() returns true for a NaN coordinate — neither < min nor > max fires. A naive >=/<= form silently rejects those.
  • Precursors and features whose m/z is not finite go to an exhaustive fallback rather than into std::sort, whose strict-weak-ordering requirement NaN violates (undefined behaviour the old loop never risked).
  • The MSExperiment is never reordered; only (key, index) vectors built from it are sorted.
  • Candidates are collected per scan into an ordered set of feature indices, so they stay ascending regardless of insertion order, and the nearest-feature selection breaks ties with a strict < on the lowest index. That is what makes it safe to visit precursors in m/z order rather than storage order, so it is now called out in a comment: swapping that container for an insertion-ordered one would silently make results depend on traversal order.

Validation. Diffed against a verbatim transcription of the previous implementation over 1500 randomized scenarios — empty hulls, mixed empty/non-empty hulls, ±150 Th wide features, NaN and infinite precursor m/z, NaN hull coordinates, zero and negative rt_tolerance, narrow m/z spans producing many exact ties, interleaved MS1, precursor-less MS2, and every combination of believe_charge / keep_original / all_matching_features / max_trace — comparing both the returned set and the full resulting MSExperiment: no differences. Plus 72,150 boundary probes on exact box edges, zero-width, universal and duplicate boxes. A compact, self-contained version of that differential check is committed as test 4 below, so it can be re-run in CI rather than only being claimed here.

PrecursorCorrection_test, all 6 TOPP_HighResPrecursorMassCorrector_* and all TOPP_OpenNuXL_* (34 tests) pass. cpplint clean under the project's filter.

Tests added

  1. Pins matching to the convex hull rather than the centroid, using the 2538_1091_2 geometry. This passes on the current implementation too, by design — it guards the property both share and that a centroid-based index would break.
  2. Exercises the sweep itself: spectra stored out of m/z order, an interval that must be retired, a charge-mismatched wide feature that must stay active to match a later precursor, and a NaN precursor. Mutation-tested — it fails if the m/z sort is removed, and fails if the charge filter is allowed to retire a feature.
  3. Covers the other fallback: a feature that cannot be placed on the sweep axis at all. That case is narrower than "non-finite hull coordinates" suggests — DBoundingBox only ever absorbs a coordinate through < / > comparisons, neither of which a NaN satisfies, so a NaN hull point can never reach the box and an infinite one is the only way to end up with a non-finite m/z interval. The test builds exactly that feature, asserts it cannot be sorted onto the sweep axis, and checks its precursor is still matched and corrected. It fails if the fallback is removed.
  4. A randomised differential check of the sweep against an exhaustive scan over every (spectrum, feature) pair. The reference is the documented predicate evaluated through the public API, not a copy of the old implementation — so it isolates the candidate pruning and does not freeze behaviour that is deliberately still open (a full transcription would have pinned Feature::getConvexHull() turns mixed empty/non-empty hulls into a full numeric-range bounding box #9802's full-numeric-range box as the spec). mz_tolerance is given in Da and exceeds half an isotope spacing, with max_trace effectively unbounded, so compatible_() accepts every overlapping pair and the returned set is exactly the spectra with at least one overlapping feature; that was verified rather than assumed — it accepts all 2450 candidate pairs the 2000 scenarios generate. m/z values come from a nine-value grid so exact ties and precursors landing exactly on a box edge occur constantly, which is where the activate/retire boundaries are most fragile, and 854 of the 2000 scenarios produce at least one candidate. The generator is a fixed-seed LCG rather than std::uniform_int_distribution, which is not required to be portable across standard library implementations. Non-vacuous against four seeded defects, each of which makes it fail: activation weakened (98 scenarios differ), retirement widened (102), the m/z sort removed (242), and the charge filter allowed to retire a feature (161).

Intended observable changes, all outside the corrected values

  • The hull-less-feature warning is now a single aggregate line emitted while boxes are pre-computed. It previously came from inside the per-pair check, so it printed once per (spectrum, feature) pair reaching it, and only after the believe_charge filter — it can therefore now appear where it did not before, e.g. when every hull-less feature mismatches every precursor charge. (A single hull-less feature used to produce one warning line per MS2 spectrum; a fuzz run of ~15M checks emitted 638,118 of them.) Note the counter behind it reports features with no hull; one empty hull among several is not counted there and produces the full-numeric-range box described below instead.
  • The debug counter reports candidate checks plus what the exhaustive product would have been, rather than the exhaustive count alone.
  • Feature::getConvexHull()'s mutable cache is now populated for every feature once there is any eligible MS2 spectrum; previously a feature filtered out by believe_charge for all precursors was never touched. Same operation and same resulting value, just for more features — worth noting for anyone calling this concurrently on a shared FeatureMap.

Found while working on this, filed as #9802

Feature::getConvexHull() turns a feature with both an empty and a non-empty ConvexHull2D into a full-numeric-range bounding box ([-1.8e308, 1.8e308] in both dimensions), because merging enlarges the box with the empty hull's DBL_MAX/lowest() sentinels. Such a feature overlaps everything. It is deliberately not fixed here so this PR keeps a clean "predicate unchanged" story — the sweep tolerates it (the interval simply spans the axis and contributes one candidate per query). Filed as #9802, since fixing it does change matching behaviour.

Summary by CodeRabbit

  • Performance

    • Improved precursor-to-feature matching by using an m/z sweep with precomputed feature windows to reduce unnecessary overlap checks.
  • Bug Fixes

    • Preserved matching behavior for edge cases, including negative RT tolerances, NaN handling, and non-finite precursor/feature m/z values (with a safe exhaustive fallback).
  • Diagnostics

    • Updated debug reporting to reflect candidate-based overlap checks and consolidated hull-less-feature warnings.
  • Tests

    • Added regression coverage for convex-hull boundary behavior, sweep candidate selection (including non-ascending m/z ordering), and NaN/non-finite precursor handling.

@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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

correctToNearestFeature() precomputes feature bounds and uses an m/z sweep to reduce overlap checks while preserving containment behavior. Non-finite values use exhaustive comparisons, with tests covering hull edges, ordering, charge filtering, and NaN precursors.

Changes

Precursor correction matching

Layer / File(s) Summary
Reusable feature matching bounds
src/openms/source/PROCESSING/CALIBRATION/PrecursorCorrection.cpp, src/openms/include/OpenMS/PROCESSING/CALIBRATION/PrecursorCorrection.h, src/tests/class_tests/openms/source/PrecursorCorrection_test.cpp
FeatureBox centralizes inclusive RT/m/z containment using feature hull extents, the obsolete overlap helper is removed, and hull-edge matching is covered.
m/z sweep and correction validation
src/openms/source/PROCESSING/CALIBRATION/PrecursorCorrection.cpp, src/tests/class_tests/openms/source/PrecursorCorrection_test.cpp, CHANGELOG
Finite precursors use sorted active feature intervals, non-finite values use exhaustive comparisons, diagnostics report candidate checks, and tests validate ordering, charge filtering, fallback behavior, and NaN handling.

Sequence Diagram(s)

sequenceDiagram
  participant MS2Scans
  participant PrecursorCorrection
  participant ActiveFeatures
  participant FeatureBox
  MS2Scans->>PrecursorCorrection: provide precursor scans
  PrecursorCorrection->>ActiveFeatures: process finite scans by increasing m/z
  ActiveFeatures->>FeatureBox: check active feature bounds
  FeatureBox-->>PrecursorCorrection: matching features
  PrecursorCorrection-->>MS2Scans: update corrected precursor values
Loading

Suggested reviewers: cbielow

Poem

I’m a rabbit with bounds in my burrow tonight,
Sweeping m/z from the left to the right.
Hull edges count, and NaNs stay still,
Active features hop by the hill.
Fewer checks sparkle in the moonlit array.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: replacing exhaustive overlap checks with an m/z sweep in PrecursorCorrection.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/precursorcorrection-overlap-4787

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.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

@copilot resolve the merge conflicts in this pull request

Copilot AI commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

@copilot resolve the merge conflicts in this pull request

Resolved. The only conflict was in CHANGELOG — our PrecursorCorrection entry and the three new entries from develop were both kept. Merge commit: 7a079a0.

timosachsenberg and others added 2 commits July 26, 2026 20:51
…th an m/z sweep (#4787)

correctToNearestFeature() compared every MS2 precursor against every feature,
which is the 812,631,750 overlap checks reported in #4787. Two things made it
expensive: the Cartesian product itself, and the fact that ConvexHull2D::
getBoundingBox() is not memoized (only Feature::getConvexHull() is), so the
feature's match region was recomputed on all ~8e8 evaluations.

Each feature's extended bounding box is now computed once, and candidates come
from a sweep line over increasing precursor m/z: a feature is activated when its
m/z interval starts and retired once it ends, so a precursor is only compared
against features whose m/z interval actually contains it. For orderable input the
candidate search becomes O(F log F + Q log Q + K), with K the number of genuinely
m/z-overlapping pairs visited, instead of O(F*Q); on top of that comes one pass
over the hull geometry. Non-finite m/z values fall back to exhaustive comparison
(see below), which reintroduces a product term for those spectra alone.

Measured on a Release build (mean over repeats, hull caches pre-warmed so this
times matching rather than cache population):

  MS2 x features        before         after      speedup
  1 x 1                  1.25 us       1.33 us      0.94x
  10 x 10               14.3  us      12.6  us      1.13x
  100 x 100              0.43 ms       0.16 ms      2.68x
  500 x 500              7.65 ms       0.86 ms      8.95x
  2000 x 2000          112.5   ms       3.45 ms     32.7x
  10000 x 10000          2.77 s        19.5  ms    142x
  30000 x 27000         26.7   s        0.076 s    351x
  10 x 20000            39.8   ms      34.8  ms      1.14x
  20000 x 10             5.71 ms       3.24 ms      1.76x
  2000 x 2000 single-trace  0.45 s      0.76 ms    596x

The break-even point is around ten spectra by ten features; below that the extra
sorting and allocation costs about 80 ns, which is why no small-input fast path
is worth the second code path. Even in the degenerate case where every feature's
m/z interval spans the whole axis - so K really is F*Q and no pruning is possible
- it stays ~3.4x ahead, because the box is no longer rebuilt per pair. Single-
trace features benefit most, since there getBoundingBox() walks the whole hull
polygon instead of a 4-point merged box. Auxiliary memory is 48 bytes per feature
(a 4-double box plus a sort key/index pair) and 16 bytes per MS2 spectrum, so
roughly 1.7 MB at 27k features and 30k spectra, plus the active set.

Both sorts carry their key alongside the index so the comparator reads plain
doubles from contiguous memory; comparing via exp[i].getPrecursors()[0].getMZ()
instead made the Q >> F case (20000 spectra, 10 features) 2x slower than the
original loop.

The matching predicate is unchanged. makeFeatureBox() deliberately uses the same
DBoundingBox setMin()/setMax() sequence the per-pair check always used, so the
region is identical for every input - including the normalisation those mutators
perform for a negative tolerance or a hull-less feature. FeatureBox::contains()
is spelled as the negation of "outside" so a NaN coordinate is accepted exactly
as DBoundingBox::encloses() accepted it. Precursors and features whose m/z is not
finite are routed to an exhaustive fallback instead of being fed to std::sort,
whose strict-weak-ordering requirement NaN violates. The MSExperiment is never
reordered; the two vectors that are sorted hold (key, index) pairs built from it.

Intended observable changes, all outside the corrected values:
- the hull-less-feature warning is now a single aggregate line, emitted while the
  boxes are pre-computed. Previously it came from inside the per-pair check, so it
  was printed once per (spectrum, feature) pair that reached it and only after the
  believe_charge filter; it can therefore now appear in cases where it did not
  before, e.g. when every hull-less feature mismatches every precursor charge.
- the debug counter now reports candidate checks plus what the exhaustive product
  would have been, rather than the exhaustive count alone
- Feature::getConvexHull()'s mutable cache is now populated for every feature
  once there is any eligible MS2 spectrum; previously a feature filtered out by
  believe_charge for all precursors was never touched. Same operation, same
  resulting value, just performed for more features.

Verified against a verbatim transcription of the previous implementation over
1500 randomized scenarios - empty hulls, mixed empty/non-empty hulls (which
Feature::getConvexHull() turns into a full-numeric-range box), +/-150 Th wide
features, NaN and infinite precursor m/z, NaN hull coordinates, zero and
negative rt_tolerance, narrow m/z spans producing many exact ties, interleaved
MS1, precursor-less MS2, and every combination of believe_charge /
keep_original / all_matching_features / max_trace - comparing both the returned
set and the full resulting MSExperiment: no differences. Plus 72,150 boundary
probes on exact box edges, zero-width, universal and duplicate boxes.

Two regression tests are added. The first pins matching to the feature's convex
hull rather than its centroid, using the geometry of the
HighResPrecursorMassCorrector_2538_1091_2 fixture, where feature:rt_tolerance
defaults to 0 and the hull reaches 9.07 s beyond the centroid; a centroid-based
lookup finds nothing there. It passes on the previous implementation too, by
design - it guards the property both share and that a centroid-based index would
break. The second exercises the sweep itself: spectra stored out of m/z order, an
interval that must be retired, a charge-mismatched wide feature that must stay
active to match a later precursor, and a NaN precursor. That one fails if the m/z
sort is removed, and fails if the charge filter is allowed to retire a feature.

Co-Authored-By: Claude Fable 5 <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the fix/precursorcorrection-overlap-4787 branch from 7a079a0 to 2ce2a11 Compare July 26, 2026 20:54

@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 (3)
src/openms/source/PROCESSING/CALIBRATION/PrecursorCorrection.cpp (3)

290-290: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Brace style inconsistent with project convention.

Line 290 omits braces entirely, and lines 317/371 place them on the same line, while the rest of the function uses Allman-style braces on their own lines (e.g. lines 375-378, 392-395). As per coding guidelines, **/*.{h,hpp,cpp,cc,cxx} should use "braces on their own aligned lines" and "always use braces for blocks."

🎨 Proposed brace fixes
-        if (exp[scan].getMSLevel() != 2 || exp[scan].getPrecursors().empty()) continue;
+        if (exp[scan].getMSLevel() != 2 || exp[scan].getPrecursors().empty())
+        {
+          continue;
+        }
-          if (features[f].getConvexHulls().empty()) { ++features_without_hull; }
+          if (features[f].getConvexHulls().empty())
+          {
+            ++features_without_hull;
+          }
-          if (boxes[f].mz_hi < pc_mz) { continue; }
+          if (boxes[f].mz_hi < pc_mz)
+          {
+            continue;
+          }

Also applies to: 317-317, 371-371

🤖 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/openms/source/PROCESSING/CALIBRATION/PrecursorCorrection.cpp` at line
290, Update the conditional statements in the relevant calibration function at
the lines corresponding to the scan-level check and the conditions at 317 and
371 to always use braces, placing each opening and closing brace on its own
aligned line in the project’s Allman style. Preserve the existing condition
logic and statement behavior.

Source: Coding guidelines


336-336: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use \n instead of std::endl in new log statements.

As per coding guidelines, src/**/*.cpp should "Prefer \n over std::endl." Both new OPENMS_LOG_WARN/OPENMS_LOG_INFO calls append endl, which forces an unbuffered flush.

📝 Proposed fix
-                          << " feature(s) have no convex hull - omitting them for matching" << endl;
+                          << " feature(s) have no convex hull - omitting them for matching" << "\n";
-                        << ")" << endl;
+                        << ")" << "\n";

Also applies to: 433-433

🤖 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/openms/source/PROCESSING/CALIBRATION/PrecursorCorrection.cpp` at line
336, Replace std::endl with "\n" in the new log statements around the
feature-without-convex-hull warning and the corresponding log statement near the
second reported location, preserving the existing message text and logging
behavior.

Source: Coding guidelines


343-425: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated match-and-count logic across three loops.

The charge-filter → contains() → insert → ++overlap_checks sequence is repeated almost verbatim in the active-set loop (lines 374-384), the unsorted_features loop (lines 391-400), and the unsorted_scans fallback (lines 415-423). Extracting a small local lambda/helper taking (f, scan, rt, pc_mz, pc_charge) would remove the duplication and reduce the risk of the three copies drifting apart on a future edit.

♻️ Proposed refactor sketch
auto try_match = [&](Size f, Size scan, double rt, double pc_mz, int pc_charge)
{
  if (believe_charge && features[f].getCharge() != pc_charge)
  {
    return;
  }
  if (boxes[f].contains(rt, pc_mz))
  {
    scan_idx_to_feature_idx[scan].insert(f);
  }
  ++overlap_checks;
};

Then replace the three inline blocks with try_match(f, scan, rt, pc_mz, pc_charge);.

🤖 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/openms/source/PROCESSING/CALIBRATION/PrecursorCorrection.cpp` around
lines 343 - 425, Extract the repeated charge-filter, contains-check, feature
insertion, and overlap_checks increment into a local try_match lambda near the
sweep loops, accepting f, scan, rt, pc_mz, and pc_charge. Replace the duplicated
logic in the active-set loop, unsorted_features loop, and unsorted_scans
fallback with calls to try_match while preserving their existing iteration and
active-feature handling.
🤖 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.

Nitpick comments:
In `@src/openms/source/PROCESSING/CALIBRATION/PrecursorCorrection.cpp`:
- Line 290: Update the conditional statements in the relevant calibration
function at the lines corresponding to the scan-level check and the conditions
at 317 and 371 to always use braces, placing each opening and closing brace on
its own aligned line in the project’s Allman style. Preserve the existing
condition logic and statement behavior.
- Line 336: Replace std::endl with "\n" in the new log statements around the
feature-without-convex-hull warning and the corresponding log statement near the
second reported location, preserving the existing message text and logging
behavior.
- Around line 343-425: Extract the repeated charge-filter, contains-check,
feature insertion, and overlap_checks increment into a local try_match lambda
near the sweep loops, accepting f, scan, rt, pc_mz, and pc_charge. Replace the
duplicated logic in the active-set loop, unsorted_features loop, and
unsorted_scans fallback with calls to try_match while preserving their existing
iteration and active-feature handling.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b06b8ddc-54b0-4077-aba8-68391fe6fa70

📥 Commits

Reviewing files that changed from the base of the PR and between 7a079a0 and 2ce2a11.

📒 Files selected for processing (3)
  • CHANGELOG
  • src/openms/source/PROCESSING/CALIBRATION/PrecursorCorrection.cpp
  • src/tests/class_tests/openms/source/PrecursorCorrection_test.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • CHANGELOG
  • src/tests/class_tests/openms/source/PrecursorCorrection_test.cpp

claude added 2 commits July 26, 2026 21:12
Three review findings from the sweep introduced in the parent commit. No
behaviour change; comments and test coverage only.

- Pin the invariant the reordering actually rests on. Visiting precursors in
  m/z order instead of storage order is only safe because the candidate sets
  are std::set<Size>, which keeps feature indices ascending regardless of
  insertion order, while the nearest-feature selection breaks ties with a
  strict '<' on the lowest index. Nothing said so, and swapping that set for
  an insertion-ordered container would silently make results depend on the
  traversal order.

- Correct the hull-less-feature comment. It claimed the aggregated warning
  matched the exhaustive implementation "warning wording included", but the
  wording did change (from "at least one feature has no convex hull" to a
  counted "N feature(s) have no convex hull"); only the matching behaviour is
  unchanged. The message is left as it is, since it is already emitted, and
  the comment now also spells out that such a feature is not literally
  omitted - it takes part in the sweep with a box no precursor can reach.

- Cover the unsorted_features fallback, which had no test. It is narrower
  than "non-finite hull coordinates" suggests: DBoundingBox only ever absorbs
  a coordinate through '<' / '>' comparisons, neither of which a NaN
  satisfies, so a NaN hull point can never reach the box and an infinite one
  is the only way to produce a non-finite m/z interval. The new case builds
  exactly that feature, asserts it cannot be placed on the sweep axis, and
  checks its precursor is still matched and corrected - which fails if the
  fallback is removed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XZPfYGU92TEjdLXfA5869L
The m/z sweep evaluates each feature's pre-computed box directly, so nothing
called overlaps_() any more: a tree-wide search found only its own declaration
and definition. It was protected on a class whose entire public API is static,
so no caller could reach it short of subclassing an all-static utility class;
it was not exposed through pyOpenMS, and the class test has a START_SECTION for
every other method but never had one for it.

Leaving it in place would also have been quietly inconsistent. It kept the old
per-call warning ("at least one feature has no convex hull"), while the sweep
emits a single counted line, so the two paths logged differently for identical
input even though they agreed on the result.

The predicate itself is unaffected - it survives as makeFeatureBox() plus
FeatureBox::contains(), which is what overlaps_() had been delegating to, so
there is still exactly one definition of the match region.

This does change the header, which the original commit deliberately avoided.
Removing a protected member is an API break only for a subclass, and there is
none in the tree.

While here, the warning comment is corrected on two points the removal made
visible: it no longer refers to overlaps_(), it now records that the count is
taken before believe_charge filtering (so the warning can appear where the old
code stayed silent), and it notes that a single empty hull among several is not
counted here but produces a full-numeric-range box instead (#9802).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XZPfYGU92TEjdLXfA5869L

@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/openms/source/PROCESSING/CALIBRATION/PrecursorCorrection.cpp`:
- Around line 341-342: Update the issue reference in the nearby convex-hull
behavior comment from `#9802` to `#9801`, leaving the surrounding explanation
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 Plus

Run ID: 5a38c3ca-c1b8-4089-ba1e-e56dd06e5ed0

📥 Commits

Reviewing files that changed from the base of the PR and between 5ac1fc2 and 0c9621a.

📒 Files selected for processing (3)
  • CHANGELOG
  • src/openms/include/OpenMS/PROCESSING/CALIBRATION/PrecursorCorrection.h
  • src/openms/source/PROCESSING/CALIBRATION/PrecursorCorrection.cpp
💤 Files with no reviewable changes (1)
  • src/openms/include/OpenMS/PROCESSING/CALIBRATION/PrecursorCorrection.h
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG

…sweep

Adds the differential test the sweep was developed against, in a form that is
worth keeping in the tree.

It does not transcribe the previous implementation. The reference is the
documented predicate itself - the convex hull's bounding box extended by
rt_tolerance in RT and 0.01 Th in m/z - evaluated exhaustively over every
(spectrum, feature) pair through the public API. So the comparison isolates the
sweep's candidate pruning, which is the part that was actually introduced, and
it does not pin behaviour that is deliberately still open (a full copy of the
old function would have frozen #9802's full-numeric-range box as the spec).

correctToNearestFeature() is driven so that its returned set is exactly the
spectra with at least one overlapping feature: mz_tolerance is given in Da and
exceeds half an isotope spacing, and max_trace is effectively unbounded, so
compatible_() accepts every overlapping pair. That was verified rather than
assumed - over the 2000 generated scenarios it accepts all 2450 candidate
pairs, so a rejection cannot silently turn into a spurious failure.

m/z values are drawn from a nine-value grid, so exact ties and precursors
landing exactly on a box edge occur constantly; that is where the activate
(<=) and retire (<) boundaries are most fragile. 854 of the 2000 scenarios
produce at least one candidate. The generator is a fixed-seed LCG rather than
std::uniform_int_distribution, which is not required to be portable across
standard library implementations, so the scenarios are identical everywhere.

Checked to be non-vacuous against four seeded defects, each of which makes it
fail: activation <= weakened to < (98 scenarios differ), retirement < widened
to <= (102), the m/z sort removed (242), and the believe_charge filter allowed
to retire a feature from the active set (161).

Non-finite inputs are intentionally left to the two dedicated cases above,
which cover the NaN precursor and the infinite hull coordinate; hull-less
features are excluded here only to keep the aggregated warning from being
emitted 2000 times into the test log.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XZPfYGU92TEjdLXfA5869L
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Looks god to me

@timosachsenberg
timosachsenberg merged commit bbcb00a into develop Jul 27, 2026
40 checks passed
@timosachsenberg
timosachsenberg deleted the fix/precursorcorrection-overlap-4787 branch July 27, 2026 04:26
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.

PrecursorCorrection use our kdtree or other structure for overlap checks

3 participants