Skip to content

[CHEMISTRY] Deprecate implicit charge handling in isotope pattern generators (#4449) - #9714

Merged
timosachsenberg merged 5 commits into
developfrom
claude/openms-4449-status-338s0h
Jul 9, 2026
Merged

timosachsenberg merged 5 commits into
developfrom
claude/openms-4449-status-338s0h

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes the non-intuitive behavior reported in #4449: setting a charge on an EmpiricalFormula silently changes the isotope pattern produced by CoarseIsotopePatternGenerator (and, since they were reconciled, FineIsotopePatternGenerator too).

Background

When an EmpiricalFormula carries a non-zero charge q, both generators implicitly add q hydrogen atoms to shift the pattern (to stay consistent with EmpiricalFormula::getMonoWeight(), which seeds the weight with PROTON_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, not m/z. Internally the "correct" idiom is already to call setCharge(0) before generating (e.g. TheoreticalSpectrumGenerator does 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:

  • Deprecation warning (behavior unchanged): CoarseIsotopePatternGenerator::run() and FineIsotopePatternGenerator::run() now emit a one-time OPENMS_LOG_WARN when 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. The static warn-once guard avoids log spam, and existing internal callers (which zero the charge) never trigger it.
  • Explicit migration API: new 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 write ef.addChargeAdduct(q); gen.run(ef); — same result, no warning, and 4.0-safe.
  • Docs: @deprecated notes added to both run() docstrings.
  • Tests: EmpiricalFormula_test covers addChargeAdduct (chaining, default and custom adducts, negative counts, mono-weight equivalence); CoarseIsotopeDistribution_test verifies the migration path reproduces the neutral C6H14O6 pattern (and matches the deprecated setCharge(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

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

🤖 Generated with Claude Code

https://claude.ai/code/session_01HERzGgNSNZRioxjVQ6J3Fz


Generated by Claude Code

Summary by CodeRabbit

  • New Features
    • Added EmpiricalFormula::addChargeAdduct(count, adduct="H") to explicitly represent ionization/adduct composition (including custom adducts and negative counts) while keeping formula charge neutral.
  • Bug Fixes
    • None.
  • Documentation
    • Marked charged empirical-formula handling in isotope pattern generators as deprecated; explained OpenMS 4.0 behavior (charge ignored → neutral pattern) and how to preserve the current shifted result.
  • Tests
    • Added regression and API tests validating isotope-distribution equivalence and expected mass-shift.
  • Chores
    • Updated changelog/release notes for the upcoming 4.0 change and deprecation warning behavior.

claude added 2 commits July 8, 2026 07:39
…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
@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

@timosachsenberg The following names might be missing from the AUTHORS file:

  • Claude

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

@coderabbitai

coderabbitai Bot commented Jul 8, 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: ed4b434b-6ff3-44b4-8903-f810027817cf

📥 Commits

Reviewing files that changed from the base of the PR and between f597e8a and 546f9f8.

📒 Files selected for processing (1)
  • CHANGELOG
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG

📝 Walkthrough

Walkthrough

This PR adds EmpiricalFormula::addChargeAdduct(count, adduct), documents the deprecation of implicit charge handling in isotope pattern generators, emits one-time warnings for charged formulas, and expands tests for the explicit ionization migration path.

Changes

Explicit charge adduct migration

Layer / File(s) Summary
addChargeAdduct API and documentation
CHANGELOG, src/openms/include/OpenMS/CHEMISTRY/EmpiricalFormula.h, src/openms/source/CHEMISTRY/EmpiricalFormula.cpp
Adds addChargeAdduct(Int count, const std::string& adduct), which folds scaled adduct atoms into the formula and resets charge to zero, with changelog and public API documentation.
CoarseIsotopePatternGenerator deprecation warning
src/openms/include/OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h, src/openms/source/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.cpp
Updates coarse-generator docs and adds a one-time warning when run() receives a charged formula.
FineIsotopePatternGenerator deprecation warning
src/openms/include/OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/FineIsotopePatternGenerator.h, src/openms/source/CHEMISTRY/ISOTOPEDISTRIBUTION/FineIsotopePatternGenerator.cpp
Updates fine-generator docs and adds a one-time warning when run() receives a charged formula.
Tests for addChargeAdduct and migration path
src/tests/class_tests/openms/source/EmpiricalFormula_test.cpp, src/tests/class_tests/openms/source/CoarseIsotopeDistribution_test.cpp
Adds coverage for addChargeAdduct behavior and compares explicit-ionization output with the legacy charged isotope distribution path.

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
Loading

Possibly related issues

Poem

I hopped through formulas, neat and bright,
with addChargeAdduct in bunny sight.
No hidden Hs now sneak around —
just clear, explicit atoms found.
One warn, one hop, the path is new,
and neutral patterns greet me too. 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: deprecating implicit charge handling in the isotope pattern generators.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/openms-4449-status-338s0h

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
timosachsenberg requested a review from cbielow July 8, 2026 07:49

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

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

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

Solid coverage; consider adding a case for a pre-existing non-zero charge.

All new assertions are correct. One gap: there's no test exercising addChargeAdduct on 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 win

Document the possible ParseError and clarify count/charge mismatch risk.

addChargeAdduct constructs EmpiricalFormula add(adduct) internally, which can throw Exception::ParseError for an invalid adduct string, but this isn't documented. Additionally, the doc example only shows a formula that starts uncharged; it doesn't warn that count should match the formula's actual charge (e.g., via ef.addChargeAdduct(ef.getCharge())) when migrating an already-charged formula — passing a mismatched count will 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

📥 Commits

Reviewing files that changed from the base of the PR and between b14c3ba and cb04cd3.

📒 Files selected for processing (9)
  • CHANGELOG
  • src/openms/include/OpenMS/CHEMISTRY/EmpiricalFormula.h
  • src/openms/include/OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h
  • src/openms/include/OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/FineIsotopePatternGenerator.h
  • src/openms/source/CHEMISTRY/EmpiricalFormula.cpp
  • src/openms/source/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.cpp
  • src/openms/source/CHEMISTRY/ISOTOPEDISTRIBUTION/FineIsotopePatternGenerator.cpp
  • src/tests/class_tests/openms/source/CoarseIsotopeDistribution_test.cpp
  • src/tests/class_tests/openms/source/EmpiricalFormula_test.cpp

claude added 2 commits July 8, 2026 07:54
…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
@timosachsenberg
timosachsenberg requested a review from jpfeuffer July 8, 2026 12:32
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

any concerns?

@timosachsenberg
timosachsenberg enabled auto-merge (squash) July 9, 2026 06:48
@timosachsenberg
timosachsenberg disabled auto-merge July 9, 2026 13:22
@timosachsenberg
timosachsenberg merged commit 26c7001 into develop Jul 9, 2026
41 checks passed
@timosachsenberg
timosachsenberg deleted the claude/openms-4449-status-338s0h branch July 9, 2026 13:22

@cbielow cbielow 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.

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.

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.

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

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.

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

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.

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.

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.

So we cannot support anion adduct Formation, e.g gaining Cl- in negative Mode.
very common in lipids.

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.

good catch...

timosachsenberg added a commit that referenced this pull request Jul 12, 2026
…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]>
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.

3 participants