Skip to content

fix(EmgFitter1D): make EMG fit robust to degenerate/edge input - #9682

Merged
timosachsenberg merged 2 commits into
developfrom
fix/6239-emg-fitter-robustness
Jun 30, 2026
Merged

timosachsenberg merged 2 commits into
developfrom
fix/6239-emg-fitter-robustness

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

What

Hardens EmgFitter1D::fit1d() (the exponentially-modified-Gaussian fitter) against degenerate and edge-case input so it can never throw, read out of bounds, or emit non-finite/garbage model parameters.

Why

fit1d() ran an unconstrained Levenberg–Marquardt fit with no guards:

  • it dereferenced set[0] before any size check,
  • it let optimize_() throw UnableToFit straight into callers,
  • it could return NaN/garbage model parameters, and
  • the method-of-moments initializer could read past the end of the input on degenerate weights.

This is the root cause behind #6239 (out-of-range RT reported by the now-removed FeatureFinderMRM). The reporting tool is gone, but the same EMG fit is still live as the elution-model-fit score in OpenSWATH (MRMFeatureFinderScoring) and in FeatureFinderIdentification / FeatureFinderAlgorithmMetaboIdent (where init_mom=true is the default), so the robustness holes still matter there.

What this PR does (minimal, score-neutral "safety net")

  • Guards degenerate input — size < 4, non-finite positions/intensities, zero span, non-positive intensity sum, non-positive interpolation step → returns a stable, in-range fallback model plus the existing -1.0 quality sentinel.
  • Catches UnableToFit around optimize_() instead of letting it propagate into scoring.
  • Rejects non-finite optimizer output / correlation and returns the fallback model rather than a NaN-laden one (previously it returned -1 but kept the broken model).
  • Bounds the method-of-moments median loop against an out-of-bounds read.
  • Extracts a small shared build_model lambda so the normal and fallback paths cannot drift apart on parameter keys.

Well-formed fits go through the unchanged path, so the values feeding the OpenSWATH LDA and the FeatureFinderIdentification SVM (var_elution_model_fit_score) are unchanged. There is deliberately no apex bound and no width cap — the original #6239 width was still far below the data span, so width-bounding wouldn't catch it and would only risk shifting scores.

Testing

New regression cases in EmgFitter1D_test (too-few-points, zero-span, right-truncated edge peak) assert no-throw + finite output. Verified green locally:

  • EmgFitter1D_test (pinned clean-data recovery unchanged + new robustness cases)
  • EmgScoring_test
  • MRMFeatureFinderScoring_test (pins elution_model_fit_score)
  • FeatureFinderIdentificationAlgorithm_test (exercises the init_mom=true MoM path)

Scope / follow-up

This is the robustness half. Making truncated edge-peak fits produce an in-range, meaningful score (instead of -1) is a deliberate follow-up, gated on a paired score-stability benchmark on real OpenSWATH/FFId data, since any change to the fit shifts a distribution that pre-trained classifiers depend on.

Related to #6239.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved EMG fitting robustness for degenerate and truncated inputs (including too few points, zero span, and non-finite inputs), ensuring the fit completes safely without throwing.
    • Added stronger validation to prevent non-finite fitted parameters; correlation post-processing now treats any non-finite result as unusable.
    • Ensured stable fallback model output with a clear failure sentinel when fitting cannot be trusted.
  • Tests
    • Expanded coverage for issue 6239 with edge cases such as NaN positions and right-truncated datasets, verifying non-throwing behavior and finite, well-formed outputs.

EmgFitter1D::fit1d() ran an unconstrained Levenberg-Marquardt fit with no
guards: it dereferenced set[0] before any size check, let optimize_() throw
UnableToFit into callers, and could emit NaN/garbage model parameters. This is
the root cause behind issue #6239 (out-of-range RT from the now-removed
FeatureFinderMRM). The EMG fit is still live as the elution-model-fit score in
OpenSWATH (MRMFeatureFinderScoring) and FeatureFinderIdentification/MetaboIdent.

Minimal, score-neutral safety net:
- guard degenerate input (size < 4, non-finite values, zero span, non-positive
  intensity sum, non-positive interpolation step) -> stable in-range fallback
  model + the existing -1.0 quality sentinel
- catch UnableToFit around optimize_()
- reject non-finite optimizer output / correlation and return the fallback model
  instead of a NaN-laden one
- bound the method-of-moments median loop against an out-of-bounds read
  (init_mom=true is the default in FeatureFinderIdentification/MetaboIdent)

Well-formed fits are handled exactly as before, so the scores feeding the
OpenSWATH LDA and the FeatureFinderIdentification SVM are unchanged. Adds
regression tests for degenerate, zero-span and right-truncated edge-peak input.

Related to #6239. Making truncated edge-peak fits in-range/meaningful (instead
of -1) is a follow-up gated on a score-stability benchmark.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3e626022-77b1-4d32-bc47-adfe6f4c807e

📥 Commits

Reviewing files that changed from the base of the PR and between 4cb2c7f and 982b9f5.

📒 Files selected for processing (2)
  • src/openms/source/FEATUREFINDER/EmgFitter1D.cpp
  • src/tests/class_tests/openms/source/EmgFitter1D_test.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/tests/class_tests/openms/source/EmgFitter1D_test.cpp
  • src/openms/source/FEATUREFINDER/EmgFitter1D.cpp

📝 Walkthrough

Walkthrough

EmgFitter1D::fit1d now validates degenerate and non-finite inputs, catches fit failures, and returns a stable fallback model with quality -1.0 when needed. setInitialParametersMOM_ adds a bounds check, and tests cover several edge cases including NaN input.

EMG Fitter Robustness

Layer / File(s) Summary
fit1d validation and fallback handling
src/openms/source/FEATUREFINDER/EmgFitter1D.cpp
Adds the exception include and shared model builder, switches data access to const references, validates interpolation step and input finiteness, handles N<4 and unusable settings with fallback output, and sanitizes fallback model parameters.
fit1d optimization and result checks
src/openms/source/FEATUREFINDER/EmgFitter1D.cpp
Catches Exception::UnableToFit, validates optimizer output before building the fitted model, and treats any non-finite Pearson correlation as a fallback condition.
setInitialParametersMOM_ bounds check
src/openms/source/FEATUREFINDER/EmgFitter1D.cpp
Bounds the weighted-median index increment in the moment-based initialization loop to avoid out-of-bounds access on degenerate weights.
Degenerate input regression tests
src/tests/class_tests/openms/source/EmgFitter1D_test.cpp
Adds numeric and memory headers and expands fit1d coverage for too-few points, zero-span inputs, right-truncated data, and a NaN leading position while checking sentinel quality and finite fitted values.

🐇 I hopped through the edge cases bright,
Fallbacks now land and stay in sight.
No NaN, no crash, no index astray,
The fitter keeps calm in a safer way.
A tiny hop, and the tests all say: hurray! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: making EmgFitter1D robust to degenerate and edge-case input.
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.
✨ 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/6239-emg-fitter-robustness

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.

@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

🧹 Nitpick comments (2)
src/tests/class_tests/openms/source/EmgFitter1D_test.cpp (1)

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

Use TEST_TRUE for boolean assertions in these test macros.

Please switch these TEST_EQUAL(expr, true) calls to TEST_TRUE(expr) to match the local test style.

As per coding guidelines, "Prefer TEST_TRUE(expr) and TEST_FALSE(expr) over TEST_EQUAL(expr, true) and TEST_EQUAL(expr, false) for boolean assertions."

Also applies to: 170-171, 195-195, 199-202

🤖 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/EmgFitter1D_test.cpp` around lines 155 -
157, Replace the boolean assertions in EmgFitter1D_test with the preferred test
macros: change each TEST_EQUAL(..., true) used for checks like q <= 0.0, m.get()
!= nullptr, and std::isfinite(...) to TEST_TRUE(...), and update the remaining
boolean assertions mentioned in this test file the same way. Keep the existing
non-boolean assertions unchanged and use the local test style consistently
throughout the test case.

Source: Coding guidelines

src/openms/source/FEATUREFINDER/EmgFitter1D.cpp (1)

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

Use Size for the bounded median index.

The new bound casts set.size() to int; keep the index and comparison in OpenMS size types to avoid narrowing and match project conventions. As per coding guidelines, use Size and SignedSize types for STL container .size() values.

♻️ Proposed refactor
-    int weighted_median_idx = 0;
+    Size weighted_median_idx = 0;
@@
-    while (sum > weight_sum/2. && weighted_median_idx + 1 < static_cast<int>(set.size()))
+    while (sum > weight_sum / 2. && weighted_median_idx + 1 < set.size())
🤖 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/FEATUREFINDER/EmgFitter1D.cpp` around lines 315 - 317, Use
OpenMS size types for the bounded median index in EmgFitter1D::fit or the
surrounding median-selection logic: replace the int-based comparison against
set.size() with Size/SignedSize-safe indexing so the guard stays type-consistent
and avoids narrowing. Update weighted_median_idx and the loop condition to
compare against set.size() using the project’s Size conventions, keeping the
out-of-bounds protection while removing the explicit int cast.

Source: Coding guidelines

🤖 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/FEATUREFINDER/EmgFitter1D.cpp`:
- Around line 178-193: The fallback path in EmgFitter1D::build_model still uses
raw set-derived values that can stay invalid, so sanitize them before creating
the sentinel model. In the n > 0 branch, clamp or replace non-finite
positions/intensities before updating lo/hi/apex/height, and ensure the final
height is strictly positive and finite before passing it to build_model. Keep
the fallback range and apex consistent with the observed data when possible
instead of resetting to arbitrary defaults, and apply the same validation in the
later fallback handling around the model construction path.
- Around line 265-274: The fallback in EmgFitter1D::buildModel only rejects
non-finite optimizer output, but still allows finite invalid values like zero or
negative width_ and symmetry_ to reach the EMG model. Add validation in the same
guard to reject any non-positive or otherwise invalid width_ / symmetry_ (and
any other required positive parameters) before calling build_model, and return
the stable fallback model when those values are present.

In `@src/tests/class_tests/openms/source/EmgFitter1D_test.cpp`:
- Around line 155-172: The EMG fitter tests only verify a couple of parameter
fields, so they can miss regressions where other model parameters become
non-finite. Update the EmgFitter1D_test cases around EmgFitter1D::fit1d to
iterate over all returned parameters from m->getParameters() and assert each
value is finite in both the non-empty and zero-span scenarios. Keep the existing
quality and non-null checks, but extend the coverage so emg:height,
emg:symmetry, emg:retention, and any other EMG parameters are all validated.
- Around line 154-170: The degenerate-path assertions in the EmgFitter1D tests
are too loose and should verify the documented fallback sentinel exactly. Update
the checks around EmgFitter1D::fit1d() so the zero-span and other fallback cases
assert the returned quality is the expected sentinel value rather than any
non-positive number, while keeping the existing finite-model and non-null model
assertions intact. Use the fit1d() contract in EmgFitter1D and the corresponding
test cases in EmgFitter1D_test.cpp to tighten the regression coverage.

---

Nitpick comments:
In `@src/openms/source/FEATUREFINDER/EmgFitter1D.cpp`:
- Around line 315-317: Use OpenMS size types for the bounded median index in
EmgFitter1D::fit or the surrounding median-selection logic: replace the
int-based comparison against set.size() with Size/SignedSize-safe indexing so
the guard stays type-consistent and avoids narrowing. Update weighted_median_idx
and the loop condition to compare against set.size() using the project’s Size
conventions, keeping the out-of-bounds protection while removing the explicit
int cast.

In `@src/tests/class_tests/openms/source/EmgFitter1D_test.cpp`:
- Around line 155-157: Replace the boolean assertions in EmgFitter1D_test with
the preferred test macros: change each TEST_EQUAL(..., true) used for checks
like q <= 0.0, m.get() != nullptr, and std::isfinite(...) to TEST_TRUE(...), and
update the remaining boolean assertions mentioned in this test file the same
way. Keep the existing non-boolean assertions unchanged and use the local test
style consistently throughout the test case.
🪄 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: 63d4f006-7a42-4ee9-8d58-6df45295242c

📥 Commits

Reviewing files that changed from the base of the PR and between 8b3a5d4 and 0360004.

📒 Files selected for processing (2)
  • src/openms/source/FEATUREFINDER/EmgFitter1D.cpp
  • src/tests/class_tests/openms/source/EmgFitter1D_test.cpp

@jpfeuffer

Copy link
Copy Markdown
Contributor

Sounds good. Check coderabbit.

…ata copy

Follow-up hardening on the #6239 robustness net (score-neutral):

- Fallback range is now sanitized before building the sentinel model, so a
  non-finite leading position (which leaves min_pos/max_pos stuck via NaN
  comparisons) can no longer emit NaN/Inf model parameters. Fallback height is
  forced > 0. This only touches the -1.0-sentinel fallback path; the returned
  quality and the well-formed path are unchanged.
- EgmFitterFunctor::operator()/df() no longer deep-copy m_data->set on every
  LM residual/Jacobian evaluation (const reference instead). The copy was a
  relic of the original GSL callback carried through the Eigen migration; each
  fit uses a stack-local fitter + Data, so it was never needed for
  concurrency/lifetime/aliasing. Bit-identical results.

Adds a regression case for the non-finite leading position.

NOTE: an earlier draft of this change also rejected finite-but-non-positive
width_/symmetry_ from the optimizer. That guard shifts live elution-model-fit
scores and broke TOPP/pyopenms OpenSwathRTNormalizer feature selection under
g++ 13 (a borderline feature converged to width/symmetry <= 0 there), exactly
the score drift this PR deliberately avoids. It is deferred to the score-gated
Track-B follow-up. Verified: EmgFitter1D/EmgScoring/MRMFeatureFinderScoring/
FeatureFinderIdentificationAlgorithm tests green; OpenSwathRTNormalizer
trafoXML output byte-identical to the pre-change build.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the fix/6239-emg-fitter-robustness branch from 4cb2c7f to 982b9f5 Compare June 29, 2026 13:00
@timosachsenberg
timosachsenberg merged commit 87d3610 into develop Jun 30, 2026
41 checks passed
@timosachsenberg
timosachsenberg deleted the fix/6239-emg-fitter-robustness branch June 30, 2026 08:51
timosachsenberg added a commit that referenced this pull request Jul 1, 2026
… (#9694)

Four recently merged PRs landed on develop without changelog coverage:
the QPXConverter removal was documented but missing its PR reference,
and the QPXFile metavalue-iteration perf fix, the cross-codebase
expensive-copy cleanup, and the EmgFitter1D robustness fix had no
entry at all.


Claude-Session: https://claude.ai/code/session_013oNRGEvcP3d7LMVv2hqAE4

Co-authored-by: Claude <[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