Skip to content

[FIX] pyOpenMS: ion mobility unit accessors mixed the two IM representations (#9792) - #9809

Merged
timosachsenberg merged 1 commit into
developfrom
fix/pyopenms-im-unit-accessors
Jul 27, 2026
Merged

timosachsenberg merged 1 commit into
developfrom
fix/pyopenms-im-unit-accessors

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Spun out of the discussion on #9808. Independent of that PR and based on develop.

The defect

MSSpectrum stores ion mobility two different ways, and a spectrum may carry either — or, on some vendor readers, both:

  • scalar — the whole spectrum was acquired at one drift time (drift_time_ / drift_time_unit_, via getDriftTime() / getDriftTimeUnit());
  • per-peak — one mobility per peak, in a FloatDataArray whose name is a PSI-MS CV term, via containsIMData() / getIMData().

get_drift_time_unit() guarded on the array but returned the scalar:

if (!self.containsIMData()) return std::nullopt;   // does the ARRAY exist?
return self.getDriftTimeUnit();                     // the SCALAR member

Measured against a build, it was correct only when neither representation was present:

spectrum state truth before after
frame: array 1/K0, scalars unset VSSC DriftTimeUnit.NONE VSSC
IM_SPECTRUM: scalar ms, no array MILLISECOND None None
both, agreeing VSSC VSSC (coincidence) VSSC
both, disagreeing array says VSSC MILLISECOND VSSC
neither none None None

The second row is the sharpest: it returned None, meaning "no ion mobility data", for a spectrum whose drift time unit is set and is exactly the field it returns.

Why it mattered in practice, not just on paper

BrukerTimsFile::frameToSpectrum sets the scalar unit to VSSC and attaches a VSSC array but never sets a scalar drift time (BrukerTimsFile.cpp:1548, :1583), and mzML writes the scalar unit only when the time is set. So on real TIMS data the accessor answered differently before and after a save/load, with the array unchanged:

BEFORE: get_drift_time_unit() = DriftTimeUnit.VSSC   array = (0, VSSC)
AFTER:  get_drift_time_unit() = DriftTimeUnit.NONE   array = (0, VSSC), values identical

That round-trip is now a regression test.

The fix

get_drift_time_array_unit() — array-derived throughout, belonging to the get_drift_time_array() / get_drift_time_array_view() family. get_drift_time_unit() stays for one release as a deprecated alias with the corrected behaviour, following the existing deprecated_mv_aliases.py mechanism; its name was in any case ambiguous against the drift_time_unit scalar property sitting right next to it.

The scalar accessors are untouched and still report the scalar. Where both representations are populated they can legitimately disagree, and each is now reported honestly instead of one masquerading as the other. DriftTimeUnit.NONE and Python None stay distinct: NONE means an array was found but its name did not pin down a unit; None means there is no array.

The same defect twice more, from one cause

The array-derived unit was reachable only as a bare int inside a tuple, so callers reached instead for the scalar accessor that returns a proper enum or string:

  • to_df() / get_data_dict() took the ion_mobility values from the array selected by getIMData() but the ion_mobility_unit column from getDriftTimeUnitAsString() — so that column read '<NONE>' for exactly the frames it exists to describe. It now uses IMTypes.driftTimeUnitToString() on the unit from the same getIMData() call. ('<NONE>' → '1/K0'.)
  • getIMData() downcast the enum to int. It now returns DriftTimeUnit, which removes the incentive that produced the other two.

API change

getIMData()[1] changes from int to DriftTimeUnit. Narrow, because DriftTimeUnit is bound with nb::is_arithmetic() — I measured it:

still works changes
unit == 2, unit in (1,2), int(unit) type(unit) is int
isinstance(unit, int), hash(), dict lookup, json.dumps str(unit) → "DriftTimeUnit.VSSC" not "2"

No in-tree consumer used the value: the three sites that unpack it discard it (addons/msexperiment.py:477, :556, addons/msspectrum.py:89), and test000.py reads only the index.

Tests

21 in test_ion_mobility_unit.py, covering all five combinations of the two representations, the enum/int interop, the deprecated alias, the DataFrame column in both agreeing and disagreeing cases, and the mzML round-trip. 12 fail against the previous behaviour. Full pyOpenMS suite: 5324 passed, 0 failed.

test_MSSpectrum.py:375 previously asserted get_drift_time_unit() is not None, which passes while the value is literally NONE — that is how this survived. It now asserts the actual unit.

Not addressed here

IMDataConverter::getIMUnit() infers the unit from the CV term's allowed units and tries milliseconds first, rather than reading the array's actual unit_accession which mzML does preserve; the term permits seconds too, so a seconds-valued array is reported as milliseconds. That is a core defect and wants its own fix — a binding-level workaround would be wrong.

Design reviewed with Codex, which independently reached the same array-derived conclusion and contributed the round-trip argument, the get_drift_time_array_unit naming, and the NONE-vs-None distinction.

Summary by CodeRabbit

  • New Features
    • Added get_drift_time_array_unit() to report ion mobility units associated with per-peak data.
    • getIMData() now returns a typed DriftTimeUnit enum.
  • Bug Fixes
    • Corrected ion mobility unit reporting after mzML round-trips.
    • DataFrame exports now use the unit corresponding to mobility values.
  • Deprecation
    • get_drift_time_unit() remains available temporarily as a deprecated alias.
  • Tests
    • Added coverage for scalar/array unit combinations, exports, enum behavior, and round-trips.

…tations (#9792)

MSSpectrum stores ion mobility two different ways. A spectrum acquired at a
single drift time keeps its unit in the scalar drift_time_unit_ member; a frame
carrying one mobility per peak keeps it in the *name* of a FloatDataArray, from
which containsIMData()/getIMData() derive it.

get_drift_time_unit() guarded on the per-peak array but returned the scalar, so
it answered DriftTimeUnit.NONE for a frame whose array was perfectly well
labelled, and None -- "no ion mobility here" -- for a spectrum whose scalar unit
was set, which is the very field it returned. It was correct only when neither
representation was present.

Concretely, that made it unstable across a file round-trip on real TIMS data.
BrukerTimsFile::frameToSpectrum sets the scalar unit to VSSC and attaches a VSSC
array but never sets a scalar drift time, and mzML writes the scalar unit only
when the time is set. The same frame therefore reported VSSC in memory and NONE
after a store/load, with the array byte-identical throughout.

It is replaced by get_drift_time_array_unit(), array-derived throughout and
belonging to the get_drift_time_array()/get_drift_time_array_view() family.
get_drift_time_unit() remains for one release as a deprecated alias with the
corrected behaviour; its name was in any case ambiguous against the
drift_time_unit scalar property sitting next to it.

The scalar accessors and properties are unchanged and continue to report the
scalar. Where a vendor reader populates both representations they can
legitimately disagree, and each is now reported honestly rather than one
masquerading as the other. DriftTimeUnit.NONE and Python None stay distinct:
NONE means an array was found but its name did not pin down a unit, None means
there is no array.

The same defect appeared twice more, from one cause: the array-derived unit was
reachable only as a bare int inside a tuple, so callers reached instead for the
scalar accessor that returns a proper enum or string.

- MSSpectrum.to_df()/get_data_dict() took the ion_mobility values from the array
  selected by getIMData() but the ion_mobility_unit column from
  getDriftTimeUnitAsString(), so the column read '<NONE>' for exactly the frames
  it exists to describe. It now uses IMTypes.driftTimeUnitToString() on the unit
  returned by the same getIMData() call.
- The getIMData() binding downcast the DriftTimeUnit enum to a plain int. It now
  returns the enum, which removes the incentive that produced the other two.

That last one is an API change, but a narrow one: DriftTimeUnit is bound with
nb::is_arithmetic(), so equality against an int, int(), isinstance(x, int),
hashing and dict lookup all still work; only str()/repr() and type() identity
differ. No in-tree consumer used the value at all -- the three that unpack it
discard it.

21 regression tests covering all five combinations of the two representations
plus the mzML round-trip; 12 fail against the previous behaviour.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 27, 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 Plus

Run ID: d7cefb93-ff63-4000-be54-ebf9f1ab0b94

📥 Commits

Reviewing files that changed from the base of the PR and between cfc45ae and ae3d78a.

📒 Files selected for processing (6)
  • CHANGELOG
  • src/pyOpenMS/bindings/bind_spectrum.cpp
  • src/pyOpenMS/pyopenms/addons/deprecated_aliases.py
  • src/pyOpenMS/pyopenms/addons/msspectrum.py
  • src/pyOpenMS/tests/unittests/test_MSSpectrum.py
  • src/pyOpenMS/tests/unittests/test_ion_mobility_unit.py

📝 Walkthrough

Walkthrough

Changes

Ion mobility unit reporting

Layer / File(s) Summary
Unit accessors and enum bindings
src/pyOpenMS/bindings/bind_spectrum.cpp
Adds get_drift_time_array_unit() and returns DriftTimeUnit directly from getIMData().
Compatibility alias and export integration
src/pyOpenMS/pyopenms/addons/deprecated_aliases.py, src/pyOpenMS/pyopenms/addons/msspectrum.py
Deprecates get_drift_time_unit() as an alias and derives DataFrame ion mobility units from getIMData().
Regression coverage and release notes
src/pyOpenMS/tests/unittests/test_ion_mobility_unit.py, src/pyOpenMS/tests/unittests/test_MSSpectrum.py, CHANGELOG
Tests scalar/array combinations, enum behavior, exports, aliases, and mzML round-trips, with corresponding changelog documentation.

Suggested reviewers: copilot, satyam102006

Poem

A bunny sorts the units bright,
Array by day and scalar night.
Enum ears twitch, warnings hop,
Round-trips land without a stop.
“None” and “NONE” now know their place!
🐇✨

🚥 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 clearly summarizes the core fix: ion mobility unit accessors mixing scalar and per-peak IM representations.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/pyopenms-im-unit-accessors

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

still not great but that is how they are called in the lib

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.

1 participant