Repository navigation
fix(EmgFitter1D): make EMG fit robust to degenerate/edge input - #9682
Conversation
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]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthrough
EMG Fitter Robustness
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
src/tests/class_tests/openms/source/EmgFitter1D_test.cpp (1)
155-157: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
TEST_TRUEfor boolean assertions in these test macros.Please switch these
TEST_EQUAL(expr, true)calls toTEST_TRUE(expr)to match the local test style.As per coding guidelines, "Prefer
TEST_TRUE(expr)andTEST_FALSE(expr)overTEST_EQUAL(expr, true)andTEST_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 winUse
Sizefor the bounded median index.The new bound casts
set.size()toint; keep the index and comparison in OpenMS size types to avoid narrowing and match project conventions. As per coding guidelines, useSizeandSignedSizetypes 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
📒 Files selected for processing (2)
src/openms/source/FEATUREFINDER/EmgFitter1D.cppsrc/tests/class_tests/openms/source/EmgFitter1D_test.cpp
|
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]>
4cb2c7f to
982b9f5
Compare
… (#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]>
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:set[0]before any size check,optimize_()throwUnableToFitstraight into callers,NaN/garbage model parameters, andThis 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 inFeatureFinderIdentification/FeatureFinderAlgorithmMetaboIdent(whereinit_mom=trueis the default), so the robustness holes still matter there.What this PR does (minimal, score-neutral "safety net")
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.0quality sentinel.UnableToFitaroundoptimize_()instead of letting it propagate into scoring.NaN-laden one (previously it returned-1but kept the broken model).build_modellambda 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
FeatureFinderIdentificationSVM (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_testMRMFeatureFinderScoring_test(pinselution_model_fit_score)FeatureFinderIdentificationAlgorithm_test(exercises theinit_mom=trueMoM 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