Repository navigation
[CHEMISTRY] Deprecate implicit charge handling in isotope pattern generators (#4449) - #9714
Conversation
…4449) CoarseIsotopePatternGenerator and FineIsotopePatternGenerator silently add 'charge'-many hydrogen atoms when an EmpiricalFormula carries a non-zero charge, shifting the isotope pattern (issue #4449). This is counter-intuitive and does not divide by charge, so the result is a proton-shifted mass axis, not m/z. Rather than break behavior silently, this deprecates the implicit path: - run() now logs a one-time OPENMS_LOG_WARN when called with a non-zero charge, pointing users to the explicit replacement, and documents that the charge will be ignored in OpenMS 4.0. Behavior is unchanged for now. - New EmpiricalFormula::addChargeAdduct(count, adduct="H") makes ionization explicit: it folds the adduct atoms into the (neutral) composition, so running the result reproduces the old shifted pattern without the warning and survives the 4.0 change. - Header docstrings updated with @deprecated notes. - Tests: EmpiricalFormula_test covers addChargeAdduct (chaining, default and custom adducts, negative counts); CoarseIsotopeDistribution_test verifies the migration path matches the neutral C6H14O6 pattern. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01HERzGgNSNZRioxjVQ6J3Fz
…#9714) Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01HERzGgNSNZRioxjVQ6J3Fz
|
@timosachsenberg The following names might be missing from the
Please consider applying the following patch: --- AUTHORS 2026-07-08 07:45:04.760038334 +0000
+++ AUTHORS.new 2026-07-08 07:45:10.157280635 +0000
@@ -25,6 +25,7 @@
- Chris Bielow
- Christian Ehrlich
- Christie Mathews
+ - Claude
- Clemens Groepl
- Cornelia Friedle
- Daniel Jameson |
|
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 (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughThis PR adds ChangesExplicit charge adduct migration
Sequence Diagram(s)sequenceDiagram
participant Client
participant EmpiricalFormula
participant CoarseIsotopePatternGenerator
participant FineIsotopePatternGenerator
participant LogStream
Client->>EmpiricalFormula: addChargeAdduct(count, adduct)
EmpiricalFormula->>EmpiricalFormula: add scaled adduct atoms
EmpiricalFormula->>EmpiricalFormula: reset charge to zero
Client->>CoarseIsotopePatternGenerator: run(charged formula)
CoarseIsotopePatternGenerator->>LogStream: OPENMS_LOG_WARN once
CoarseIsotopePatternGenerator->>Client: isotope pattern
Client->>FineIsotopePatternGenerator: run(charged formula)
FineIsotopePatternGenerator->>LogStream: OPENMS_LOG_WARN once
FineIsotopePatternGenerator->>Client: isotope pattern
Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 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: 2
🧹 Nitpick comments (2)
src/tests/class_tests/openms/source/EmpiricalFormula_test.cpp (1)
249-274: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSolid coverage; consider adding a case for a pre-existing non-zero charge.
All new assertions are correct. One gap: there's no test exercising
addChargeAdducton a formula that already has a non-zero charge before the call (verifying it gets unconditionally overwritten to 0, and highlighting the count/charge mismatch pitfall noted in the header).🤖 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/EmpiricalFormula_test.cpp` around lines 249 - 274, Add a test in EmpiricalFormula_test.cpp for EmpiricalFormula::addChargeAdduct that starts from a formula with a non-zero charge before calling the method, then verify the charge is reset to 0 unconditionally and the adduct count changes as expected. Reuse the existing START_SECTION for addChargeAdduct and assert both the resulting composition and the overwritten charge state to cover the count/charge mismatch case described in the header.src/openms/include/OpenMS/CHEMISTRY/EmpiricalFormula.h (1)
215-239: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDocument the possible
ParseErrorand clarify count/charge mismatch risk.
addChargeAdductconstructsEmpiricalFormula add(adduct)internally, which can throwException::ParseErrorfor an invalid adduct string, but this isn't documented. Additionally, the doc example only shows a formula that starts uncharged; it doesn't warn thatcountshould match the formula's actual charge (e.g., viaef.addChargeAdduct(ef.getCharge())) when migrating an already-charged formula — passing a mismatchedcountwill silently produce an inconsistent, incorrect composition since charge is unconditionally reset to 0 regardless of the value passed.📝 Suggested doc addition
`@param` count Number of adducts to add (typically the intended charge); negative values remove adducts. `@param` adduct The adduct added per charge, as an OpenMS formula string (default: "H"). `@return` reference to *this (for chaining) + `@throw` Exception::ParseError if `@p` adduct cannot be parsed as a valid formula string + `@warning` When migrating a formula that already has a non-zero charge, pass that + charge explicitly (e.g. `@c` ef.addChargeAdduct(ef.getCharge()) ), otherwise + the resulting neutral composition will not match the original charge. */ EmpiricalFormula& addChargeAdduct(Int count = 1, const std::string& adduct = "H");🤖 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/include/OpenMS/CHEMISTRY/EmpiricalFormula.h` around lines 215 - 239, Update the `EmpiricalFormula::addChargeAdduct` documentation to mention that constructing the adduct formula can throw `Exception::ParseError` when the `adduct` string is invalid, and clarify that `count` must match the formula’s actual charge when converting an already-charged species (for example, by using `ef.getCharge()`), since `addChargeAdduct` always resets the charge to zero even if the passed count is inconsistent. Keep the guidance near the existing `addChargeAdduct` comment and example so readers can find the behavior quickly.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/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.cpp`:
- Around line 83-99: The one-time deprecation warning in
CoarseIsotopePatternGenerator::run() uses a shared static bool warned_once,
which can race under concurrent calls. Replace that guard with a thread-safe
one-time mechanism such as std::once_flag and std::call_once around the
OPENMS_LOG_WARN block, keeping the warning text and “shown once” behavior
unchanged.
In
`@src/openms/source/CHEMISTRY/ISOTOPEDISTRIBUTION/FineIsotopePatternGenerator.cpp`:
- Around line 30-41: The once-only warning guard in
FineIsotopePatternGenerator::run() is not thread-safe because the local static
warned_once can race under concurrent calls; replace it with a thread-safe
mechanism such as std::atomic<bool> or std::once_flag while preserving the
log-once behavior. Apply the same fix to the matching guard in
CoarseIsotopePatternGenerator::run() so both isotope generators use the same
safe pattern.
---
Nitpick comments:
In `@src/openms/include/OpenMS/CHEMISTRY/EmpiricalFormula.h`:
- Around line 215-239: Update the `EmpiricalFormula::addChargeAdduct`
documentation to mention that constructing the adduct formula can throw
`Exception::ParseError` when the `adduct` string is invalid, and clarify that
`count` must match the formula’s actual charge when converting an
already-charged species (for example, by using `ef.getCharge()`), since
`addChargeAdduct` always resets the charge to zero even if the passed count is
inconsistent. Keep the guidance near the existing `addChargeAdduct` comment and
example so readers can find the behavior quickly.
In `@src/tests/class_tests/openms/source/EmpiricalFormula_test.cpp`:
- Around line 249-274: Add a test in EmpiricalFormula_test.cpp for
EmpiricalFormula::addChargeAdduct that starts from a formula with a non-zero
charge before calling the method, then verify the charge is reset to 0
unconditionally and the adduct count changes as expected. Reuse the existing
START_SECTION for addChargeAdduct and assert both the resulting composition and
the overwritten charge state to cover the count/charge mismatch case described
in the header.
🪄 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: f8c01a41-ad05-4d80-a3df-4f8c31033717
📒 Files selected for processing (9)
CHANGELOGsrc/openms/include/OpenMS/CHEMISTRY/EmpiricalFormula.hsrc/openms/include/OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.hsrc/openms/include/OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/FineIsotopePatternGenerator.hsrc/openms/source/CHEMISTRY/EmpiricalFormula.cppsrc/openms/source/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.cppsrc/openms/source/CHEMISTRY/ISOTOPEDISTRIBUTION/FineIsotopePatternGenerator.cppsrc/tests/class_tests/openms/source/CoarseIsotopeDistribution_test.cppsrc/tests/class_tests/openms/source/EmpiricalFormula_test.cpp
…4449, #9714) - Make the one-time deprecation warning in Coarse/FineIsotopePatternGenerator thread-safe: run() is const and may be called from parallel regions, so the warn-once flag is now std::atomic<bool> guarded by an exchange() instead of a racy plain bool (include <atomic>). - Document that EmpiricalFormula::addChargeAdduct always resets the charge to 0 (pass getCharge() when migrating an already-charged formula), that negative counts can yield negative element counts, and that it throws ParseError on an invalid adduct string. - Add a test covering addChargeAdduct on a formula that already carries a non-zero charge. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01HERzGgNSNZRioxjVQ6J3Fz
…-status-338s0h # Conflicts: # CHANGELOG
|
any concerns? |
cbielow
left a comment
There was a problem hiding this comment.
I would vote for a more thourough behavour change which avoids still existing pitfalls.
I.e.:
- use a new API to avoid confusion with the old behaviour. make them exist side by side and deprecate the old one after 4.0
- allow adding custom anionic charge adducts and infer charge from that, e.g ef.addAnionicCharge("Cl-") to get an additional -1 charge with ADDED Cl internally. Keep the charge non-zero and returns an Isotope pattern in m/z, not mass (fixing the electron correction along the way). if the charge of the ef is truly 0, return mass, not m/z.
- setCharge(n) should be deprecated, since its unclear who carries the charge (or we should make it very clear what the semantics are).
would this work?
| @endcode | ||
|
|
||
| @note Whole hydrogen @b atoms (proton + electron) are added. For a physically exact protonated | ||
| @e m/z you additionally have to divide by the charge and account for the electron mass yourself. |
There was a problem hiding this comment.
we should do this right away when reporting Isotope patterns, not the user
|
|
||
| @warning The charge is always reset to zero, regardless of @p count. When migrating a formula that | ||
| already carries a non-zero charge, pass that charge explicitly (e.g. | ||
| @c ef.addChargeAdduct(ef.getCharge()) ); passing a @p count that does not match the |
There was a problem hiding this comment.
throw an exception if it does not Match, or at least a big warning
| already carries a non-zero charge, pass that charge explicitly (e.g. | ||
| @c ef.addChargeAdduct(ef.getCharge()) ); passing a @p count that does not match the | ||
| existing charge yields a composition inconsistent with the original ion. | ||
| @note A negative @p count subtracts adduct atoms and may drive an element's count below zero |
There was a problem hiding this comment.
this is bad and physically impossible. Proton loss is only possible if you enough of them.
| (e.g. removing an adduct the formula does not contain), mirroring EmpiricalFormula's general | ||
| support for negative element counts. | ||
|
|
||
| @param count Number of adducts to add (typically the intended charge); negative values remove adducts. |
There was a problem hiding this comment.
So we cannot support anion adduct Formation, e.g gaining Cl- in negative Mode.
very common in lipids.
There was a problem hiding this comment.
good catch...
…piricalFormula::addChargeAdduct (#9719) - The CHANGELOG entry for #9453 described non-existent "ONNXRuntime"/"PeptDeep" classes and claimed a vendored ONNX Runtime + bundled model files; the actual classes are ONNXPredictorBase/PeptDeepRTInference/PeptDeepMS2Inference/ PeptDeepCCSInference, ONNX Runtime is an external dependency found via CMake, and PeptDeep models are downloaded (with checksum validation) during configuration, not bundled. Rewrote the entry to match the code. - Documented the previously undocumented PeptDeepInputBuilder static methods and added missing @throws to PeptDeepRTInference::predictRT and PeptDeepCCSInference::predictCCS, matching the sibling predictMS2() docs. - EmpiricalFormula::addChargeAdduct() (added in #9714) had no pyOpenMS binding; added it following the existing setCharge/__iadd__ pattern in bind_chemistry.cpp, plus a unit test. Claude-Session: https://claude.ai/code/session_011WvU2MJPuL6jLSCK9yPVDH Co-authored-by: Claude <[email protected]>
Description
Fixes the non-intuitive behavior reported in #4449: setting a charge on an
EmpiricalFormulasilently changes the isotope pattern produced byCoarseIsotopePatternGenerator(and, since they were reconciled,FineIsotopePatternGeneratortoo).Background
When an
EmpiricalFormulacarries a non-zero chargeq, both generators implicitly addqhydrogen atoms to shift the pattern (to stay consistent withEmpiricalFormula::getMonoWeight(), which seeds the weight withPROTON_MASS_U * charge). This is surprising — changing the charge changes the pattern — and, because nothing is divided by charge, the output is a proton-shifted mass axis, notm/z. Internally the "correct" idiom is already to callsetCharge(0)before generating (e.g.TheoreticalSpectrumGeneratordoes this at five sites), so no internal caller relies on the shift.Approach (non-breaking, staged for 4.0)
Rather than silently changing numeric output, this deprecates the implicit path and gives users an explicit, forward-compatible replacement:
CoarseIsotopePatternGenerator::run()andFineIsotopePatternGenerator::run()now emit a one-timeOPENMS_LOG_WARNwhen called with a non-zero charge, explaining the current behavior, that the charge will be ignored in OpenMS 4.0 (yielding the neutral pattern), and how to migrate. The shift itself is preserved for now, so nothing breaks in 3.x. Thestaticwarn-once guard avoids log spam, and existing internal callers (which zero the charge) never trigger it.EmpiricalFormula::addChargeAdduct(Int count = 1, const std::string& adduct = "H")folds the adduct atoms into the neutral composition and resets the charge to zero. Users who want the old shifted pattern writeef.addChargeAdduct(q); gen.run(ef);— same result, no warning, and 4.0-safe.@deprecatednotes added to bothrun()docstrings.EmpiricalFormula_testcoversaddChargeAdduct(chaining, default and custom adducts, negative counts, mono-weight equivalence);CoarseIsotopeDistribution_testverifies the migration path reproduces the neutralC6H14O6pattern (and matches the deprecatedsetCharge(2)masses to within the electron mass per charge).Backwards compatibility
This PR is fully backwards compatible: it is purely additive (a new method) plus a one-time log line — no signatures, ABI, or numeric outputs change. The actual behavioral change (ignoring charge) is deferred to 4.0, after users have had a release with both a warning and a concrete migration path.
Checklist
🤖 Generated with Claude Code
https://claude.ai/code/session_01HERzGgNSNZRioxjVQ6J3Fz
Generated by Claude Code
Summary by CodeRabbit
EmpiricalFormula::addChargeAdduct(count, adduct="H")to explicitly represent ionization/adduct composition (including custom adducts and negative counts) while keeping formula charge neutral.