Skip to content

[pyOpenMS] Pythonic snake_case properties for Peak1D and MSSpectrum (#9760) - #9777

Merged
timosachsenberg merged 3 commits into
OpenMS:developfrom
aliviahossain:pyopenms-pythonic-properties-9760
Jul 23, 2026
Merged

timosachsenberg merged 3 commits into
OpenMS:developfrom
aliviahossain:pyopenms-pythonic-properties-9760

Conversation

@aliviahossain

@aliviahossain aliviahossain commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Description:

Applies the existing def_prop_rw binding pattern consistently to the core kernel classes, so pyOpenMS objects can be accessed the Pythonic way.

Properties added (additive):

  • Peak1D: mz, intensity (pos is skipped since it is just an alias of mz)
  • MSSpectrum: rt, ms_level, drift_time, drift_time_unit, name, comment, native_id

The getMZ()/setMZ(), getRT()/setRT(), etc. methods are untouched, so nothing breaks. Only clean no-arg scalar get/set pairs are exposed; container accessors (getPrecursors, ...) and argument-taking ones (getType(query_data)) stay as methods.

One intentional behavior change (please review):
MSSpectrum.__getitem__ now returns a reference instead of a copy, so spectrum[i].mz = x mutates the peak in place. This matches how Mobilogram, FeatureMap and ConsensusMap already index. A held reference is invalidated if the spectrum reallocates (push_back/resize/set_peaks), same as C++ iterator invalidation. This is the only non-additive part of the PR.

Not a constructor: MSSpectrum(n_peaks=3, rt=205.20s, ms_level=2) is only the __repr__ output, so it is deliberately not shown in the docs as a way to build a spectrum.

Tests: new test_snake_case_properties.py covers round-trip, getter/property agreement, the reference semantics, invalidation, and that the legacy methods still exist.

Docs: pyOpenMS user guide examples (ms_data.rst, first_steps.rst) updated to the property syntax with a short note that both styles are equivalent.

Verified locally against a nanobind build (pyopenms 3.6.0-pre-develop).

Verification

Screenshot 2026-07-21 210710

Baseline (before): properties absent, indexing returns a copy.

Screenshot 2026-07-21 211147

After: properties read/write and spectrum[0].mz = x sticks (reference).

Screenshot 2026-07-21 211728

Tests: 7/7 passing.

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.)

Closes #9760

@jcharkow , @timosachsenberg Please review the PR. Thanks !

Summary by CodeRabbit

  • New Features
    • Added Pythonic snake_case read/write properties for MSSpectrum metadata and Peak1D values (e.g., rt, ms_level, drift_time, mz, intensity).
    • Kept legacy get*/set* methods available alongside the new properties (including enum-backed drift time units).
  • Documentation
    • Updated user-guide examples to use property-based access in iteration and peak/spectrum workflows.
  • Tests
    • Added pytest coverage for property synchronization/round-trips and peak access behavior (indexing returns a copy; updates use assignment).

OpenMS#9760)

Apply the existing def_prop_rw binding pattern consistently to the kernel
classes so core objects can be accessed the Pythonic way, additively:

- Peak1D:     mz, intensity  (pos omitted as an alias of mz)
- MSSpectrum: rt, ms_level, drift_time, drift_time_unit, name, comment,
              native_id

The getMZ()/setMZ(), getRT()/setRT(), ... methods are unchanged, so nothing
breaks.

MSSpectrum.__getitem__ now returns a reference instead of a copy, so
spectrum[i].mz = x mutates the peak in place (matching Mobilogram, FeatureMap
and ConsensusMap). A held reference is invalidated if the spectrum reallocates
(push_back/resize/set_peaks), like a C++ iterator.

Adds tests (round-trip, getter/property agreement, reference semantics,
invalidation, additivity) and updates the pyOpenMS user guide examples to the
property syntax.
@coderabbitai

coderabbitai Bot commented Jul 21, 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: 1be7d7e6-ad76-47ab-ac72-49592a630aba

📥 Commits

Reviewing files that changed from the base of the PR and between 27c2617 and 4a30f1a.

📒 Files selected for processing (3)
  • CHANGELOG
  • src/pyOpenMS/bindings/bind_spectrum.cpp
  • src/pyOpenMS/tests/unittests/test_snake_case_properties.py

📝 Walkthrough

Walkthrough

Changes

pyOpenMS API enhancement

Layer / File(s) Summary
Binding properties
src/pyOpenMS/bindings/bind_kernel.cpp, src/pyOpenMS/bindings/bind_spectrum.cpp
Adds writable snake_case properties for Peak1D and MSSpectrum, while retaining existing getter/setter methods and omitting pos.
API compatibility and behavior tests
src/pyOpenMS/tests/unittests/test_snake_case_properties.py
Tests property synchronization, enum handling, legacy accessors, alias behavior, and copy-based spectrum indexing with __setitem__ updates.
User guide and release-note updates
doc/pyopenms/docs/source/user_guide/*.rst, CHANGELOG
Updates examples and documents the new property syntax and its equivalence to existing methods.

Suggested reviewers: timosachsenberg, cbielow

Poem

A rabbit hops through bindings bright,
With mz and rt set just right.
Old getters remain in their burrow below,
While new Pythonic properties glow.
Docs and tests cheer: “Away we go!” 🐇

🚥 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 is concise and accurately summarizes the main change: adding snake_case pyOpenMS properties to Peak1D and MSSpectrum.
Linked Issues check ✅ Passed The PR adds the requested additive snake_case properties for Peak1D and MSSpectrum, keeps legacy getters/setters, and updates docs/tests accordingly.
Out of Scope Changes check ✅ Passed No clear out-of-scope code changes are shown; the docs, tests, and bindings all support the requested pyOpenMS property additions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

🧹 Nitpick comments (2)
src/pyOpenMS/tests/unittests/test_snake_case_properties.py (2)

60-64: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider asserting the remaining legacy getters for completeness.

The tests verify most legacy getters to ensure the roundtrip stays in sync, but getDriftTime() and getComment() checks could be added for exhaustive coverage.

💡 Proposed additions
     # agreement with the legacy getters
     assert s.getRT() == pytest.approx(205.2)
     assert s.getMSLevel() == 2
+    assert s.getDriftTime() == pytest.approx(25.5)
     assert s.getName() == "scan=1"
+    assert s.getComment() == "hello"
     assert s.getNativeID() == "controllerType=0 scan=1"
🤖 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/pyOpenMS/tests/unittests/test_snake_case_properties.py` around lines 60 -
64, Add assertions alongside the existing legacy getter checks in the snake-case
properties test for getDriftTime() and getComment(), using the corresponding
expected values from the test fixture to verify complete roundtrip agreement.

130-132: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider verifying the presence of drift_time legacy methods.

For thoroughness, you could also assert the presence of getDriftTime, setDriftTime, getDriftTimeUnit, and setDriftTimeUnit alongside the other legacy methods.

💡 Proposed additions
     for name in ("getRT", "setRT", "getMSLevel", "setMSLevel", "getName", "setName",
-                 "getNativeID", "setNativeID", "getComment", "setComment"):
+                 "getNativeID", "setNativeID", "getComment", "setComment",
+                 "getDriftTime", "setDriftTime", "getDriftTimeUnit", "setDriftTimeUnit"):
         assert hasattr(MSSpectrum, name)
🤖 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/pyOpenMS/tests/unittests/test_snake_case_properties.py` around lines 130
- 132, Extend the legacy-method names in the MSSpectrum check within
test_snake_case_properties.py to include getDriftTime, setDriftTime,
getDriftTimeUnit, and setDriftTimeUnit, so the existing hasattr assertions
verify these drift-time methods as well.
🤖 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.

Nitpick comments:
In `@src/pyOpenMS/tests/unittests/test_snake_case_properties.py`:
- Around line 60-64: Add assertions alongside the existing legacy getter checks
in the snake-case properties test for getDriftTime() and getComment(), using the
corresponding expected values from the test fixture to verify complete roundtrip
agreement.
- Around line 130-132: Extend the legacy-method names in the MSSpectrum check
within test_snake_case_properties.py to include getDriftTime, setDriftTime,
getDriftTimeUnit, and setDriftTimeUnit, so the existing hasattr assertions
verify these drift-time methods as well.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e6d94833-bbf5-404f-bf3f-3b51f8d9848d

📥 Commits

Reviewing files that changed from the base of the PR and between c7d7e2e and 6f33fa5.

📒 Files selected for processing (6)
  • CHANGELOG
  • doc/pyopenms/docs/source/user_guide/first_steps.rst
  • doc/pyopenms/docs/source/user_guide/ms_data.rst
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/bindings/bind_spectrum.cpp
  • src/pyOpenMS/tests/unittests/test_snake_case_properties.py

@jpfeuffer

jpfeuffer commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Hmm not sure if suddenly defaulting to references is a good idea without syntax change.

what happens if you do:

s = MSSpectrum(...)
peak = s[0]
del s
print(peak.mz)

If you want to allow this then only via specifically new "View" wrappers please.

@jpfeuffer

Copy link
Copy Markdown
Contributor

The above may work with specific ownership models in nanobind that support keep_alive and parent references etc.

But what probably will never work with just one class type is this:

s = MSSpectrum(...)
peak = s[0]
s.sort() # or anything else that reallocates the underlying std::vector
print(peak.mz)

I dont think this is what python users are expecting.

@aliviahossain

Copy link
Copy Markdown
Contributor Author

@jpfeuffer Nice catch, thanks. I tested all three: del s survives (reference_internal keeps the parent alive), but push_back reallocation is a use-after-free and sort() silently makes the peak alias a different element. So you're right, a plain reference can't hold up.

My plan: drop the getitem change from this PR and keep it purely additive (just the snake_case properties). The in-place spectrum[i].mz = x case can come later as a proper index-based View wrapper. Does that sound right to you?

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
CHANGELOG (1)

24-24: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Add reordering to the invalidation note. MSSpectrum can reorder peaks in place via sortByPosition(), sortByIntensity(), sortByIonMobility(), and sort(...), so a retained spectrum[i] reference may point at a different peak even without reallocation. CHANGELOG:24

🤖 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 `@CHANGELOG` at line 24, Update the MSSpectrum reference-invalidation note in
the changelog to state that retained spectrum[i] references can also become
invalid or refer to different peaks after in-place reordering via
sortByPosition(), sortByIntensity(), sortByIonMobility(), or sort(...), in
addition to reallocation operations. Keep the existing reallocation examples and
iterator-like caveat intact.
🤖 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.

Outside diff comments:
In `@CHANGELOG`:
- Line 24: Update the MSSpectrum reference-invalidation note in the changelog to
state that retained spectrum[i] references can also become invalid or refer to
different peaks after in-place reordering via sortByPosition(),
sortByIntensity(), sortByIonMobility(), or sort(...), in addition to
reallocation operations. Keep the existing reallocation examples and
iterator-like caveat intact.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0c56db1f-5cb8-43f9-a08f-c3545fd09226

📥 Commits

Reviewing files that changed from the base of the PR and between 6f33fa5 and 27c2617.

📒 Files selected for processing (1)
  • CHANGELOG

@jpfeuffer

Copy link
Copy Markdown
Contributor

I personally would prefer this.

Maybe there were even some experiments on Views when @timosachsenberg moved it to nanobind?

@aliviahossain

Copy link
Copy Markdown
Contributor Author

@jpfeuffer Alright, I'll pull getitem out and keep this PR additive.

Nothing View-related landed on develop, @timosachsenberg anything worth building on?

Note that iter already hands out references today (reference_internal, bind_spectrum.cpp:169), so for p in spectrum: p.setMZ(x) already mutates in place with the same sort/reallocation fragility, hence reverting getitem alone doesn't fully remove it. I'll open a follow-up issue later, for a proper index-based View that covers iteration too.

@timosachsenberg

Copy link
Copy Markdown
Contributor

We have a few views in the context of exposing internal data in numpy

@aliviahossain

Copy link
Copy Markdown
Contributor Author

@jpfeuffer Pushed the commit in this PR. Reverted getitem back to copy semantics so this PR is now purely additive (snake_case properties only). Now shows spectrum[i].mz = x no longer sticks (copy), while the properties and setitem work as expected.

Screenshot 2026-07-22 023821

@aliviahossain

Copy link
Copy Markdown
Contributor Author

@timosachsenberg Alright, that makes sense. get_peaks_struct() already returns a mutable zero-copy structured array (arr['mz'][i] = x / arr['intensity'][i] = x write through), so it covers the in-place case. I've kept this PR additive and just document that path in the follow-up rather than adding a per-element view.

@jpfeuffer

Copy link
Copy Markdown
Contributor

hmm interesting. I also think that a random "get_peak_struct" that suddenly returns a reference instead of a copy can be a bit confusing.
I think this whole distinction could use an overhaul.
I think a lot can be done with docs and function docstrings but we should think about if it can be solved better by more invasive changes.

E.g. we could say we work like pandas and eveything returns a view by default and if you want to make sure it stays safe you need to use .copy()

Or we have two methods for everything (one suffixed with _view) or the notorious copy=True parameter in a method.
Then we can think about actually having different return types that signal that distinction. Should be possible for our own objects.

I wonder what @timosachsenberg and @jcharkow and Claude have to say.

@timosachsenberg

Copy link
Copy Markdown
Contributor

I think @jpfeuffer, get_peak_struct is the one that can be memory-mapped. Because of the C++ internal storage layout. Others require copies. I agree that this needs quite some thought and is probably not an easy throw at Claude.
Currently don't really have the capacity for that...

@jcharkow

Copy link
Copy Markdown
Collaborator

Although memory mapping can be dangerous, I always run into with issues with pyopenms with large data is because there is a copy of everything. I think returning a reference instead of a copy is one of the major changes required for making python "a first class citizen language"

I think being able to return a reference is advantageous (and maybe even an advantageous default). Having said that we need the proper checks in place. We might need to do something like pandas where if an operation is done that might be questionable, a warning message pops up by default.

@aliviahossain as a new user and going through the documentation, what type of behaviour would you expect?

The other option is to create a library ontop of pyopenms for more "pythonic behaviour" however that just creates another library to maintain.

@timosachsenberg

timosachsenberg commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

I think being able to return a reference is advantageous (and maybe even an advantageous default). Having said that we need the proper checks in place. We might need to do something like pandas where if an operation is done that might be questionable, a warning message pops up by default.

I am not sure if this is possible, but happy to be corrected. How would you emit warnings and for which functions? e.g. for every sort? See below how this might require quite a lot of bookkeeping.

The other option is to create a library ontop of pyopenms for more "pythonic behaviour"; however, that just creates another library to maintain.

I think this could unfortunately be the only option that will be consistent and achieve what you want. You would need to restrict the API surface manually and then do something like pandas or polars.

I expect that an increasing share of pyOpenMS code will be generated with the help of coding agents. This makes good documentation, consistent semantics, and expressive naming even more important. A _view suffix, as @jpfeuffer suggested, could help make the semantics explicit. But let's also explore alternatives and then prove that this will lead to a more consistent and easier API.

By the way, Polars is generally considered to have a cleaner and more Pythonic API than pandas; most of us are simply more familiar with pandas syntax. I would therefore avoid treating pandas as the benchmark for the API or user experience we want to achieve. It has too many issues...

@timosachsenberg

Copy link
Copy Markdown
Contributor

Codex sol on the highest level suggests this:

Design goal

The pyOpenMS API should be value-semantic by default, transactional for
mutation, and expose raw aliasing only through a deliberately constrained
expert API.

Users should not need to understand std::vector invalidation rules
to use ordinary pyOpenMS:

  • copies should be ordinary;
  • mutation should be explicit and convenient;
  • indexing and iteration should agree;
  • metadata should move as aligned rows;
  • aliasing should require a conspicuous opt-in;
  • unsafe zero-copy access should never look like an ordinary getter.

Public contract

Operation Recommended semantics
container[i] Owning copy
container[i] = value Explicit replacement
for value in container Owning copies, consistent with indexing
Unsuffixed getters Copies
Getters ending in _view Safe, pinned aliases with documented invalidation
Structural mutation while a view exists Raise BufferError
Mutable value classes hash = None
Shared objects References only when genuinely shared_ptr-owned and documented as handles

Scalar properties from pull request #9777 fit this model:

peak = spectrum[0]       # owning Peak1D
peak.mz = 500.0
peak.intensity = 1000.0
spectrum[0] = peak       # explicit commit

Iteration must behave consistently:

for peak in spectrum:
    peak.mz += 1.0       # modifies the copy only

This avoids the current indexing-copy/iteration-reference split.

Convenient mutation without raw references

The copy-and-replace pattern is safe but verbose. Add atomic update helpers:

spectrum.update_peak(0, mz=500.0, intensity=1000.0)
chromatogram.update_peak(0, rt=42.0)
mobilogram.update_peak(0, mobility=1.25)

For larger edits, provide transactional editors:

with spectrum.edit_peak(0) as peak:
    peak.mz = 500.0
    peak.intensity *= 2

The editor should:

  • edit a detached value;
  • commit only after successful context exit;
  • verify that the parent's structural mutation generation has not changed;
  • raise RuntimeError rather than replacing the wrong slot;
  • mark ranges and sortedness dirty on commit;
  • discard changes if the context exits with an exception.

Use the same pattern for nested containers:

with experiment.edit_spectrum(3) as spectrum:
    spectrum.setRT(120.0)
    spectrum.set_peaks(mz, intensity)

This is safer than returning an MSSpectrum& into the experiment's
vector.

Bulk peak access

Keep the current safe copy API:

mz, intensity = spectrum.get_peaks()  # detached arrays
spectrum.set_peaks(mz, intensity)

Make structured access follow the same rule:

peaks = spectrum.get_peaks_struct()   # detached structured array
spectrum.set_peaks_struct(peaks)

The current writable native buffer should not be exposed as an ordinary
get_peaks_struct_view(). An explicit name alone does not prevent
use-after-reallocation or metadata corruption.

Safe zero-copy views

If true zero-copy access is retained, it needs buffer-export pinning:

view = spectrum.get_peaks_struct_view()  # read-only, keeps parent alive
spectrum.resize(100)                     # raises BufferError

This requires:

  • a live-export counter associated with the C++ container;
  • every structural mutator, including C++ algorithms, to respect it;
  • sorting, assignment, clear, reserve,
    resize, and replacement to be blocked;
  • the ndarray to release its export when its owner token is destroyed;
  • the parent to remain alive for the lifetime of the ndarray.

Without that infrastructure, raw views should live in an explicit expert
namespace:

view = pyopenms.unsafe.peaks_view(spectrum)

A name such as unsafe.peaks_view() is more honest than merely
adding a _view suffix.

Generation counters alone cannot protect NumPy arrays because NumPy reads and
writes their memory without calling back into pyOpenMS.

Metadata must be edited as aligned rows

Writable views of only (mz, intensity) cannot safely coexist with
parallel float, integer, and string data arrays.

Introduce an owning aligned representation:

table = spectrum.get_peak_table()
table.sort_by("mz")
table.float_arrays["ion_mobility"] *= 2
spectrum.set_peak_table(table)

PeakTable should contain:

  • peak positions;
  • peak intensities;
  • all float data arrays;
  • all integer data arrays;
  • all string data arrays;
  • their names and descriptions.

Commit should validate all lengths and replace everything atomically.

set_peaks() must not silently leave existing metadata misaligned.
If metadata exists, it should either:

  • require an aligned PeakTable;
  • raise and require the caller to clear metadata explicitly; or
  • accept an explicit policy such as metadata="clear".

Silent preservation across unrelated peak replacement is unsafe.

The same aligned-row principle applies to:

  • MSChromatogram;
  • Mobilogram;
  • OSSpectrum;
  • OSChromatogram;
  • RescoreOutput;
  • IonImage data and mask;
  • imaging geometry pixels and their lookup index.

Geometry pixels should never expose a writable raw view because coordinate
changes must update lookup_.

Iterator ownership

Replace nb::make_iterator over native C++ iterators with an
iterator containing:

  • a strong reference to the parent;
  • the current integer index;
  • the parent's structural mutation generation;
  • copy-returning indexed access.

If the generation changes during iteration, raise:

RuntimeError: container was structurally modified during iteration

This avoids both temporary-owner failures and invalidated C++ iterators.

The default iterator should therefore behave like:

peak = next(iter(spectrum))
peak.mz = 500.0

assert spectrum[0].mz != 500.0

An explicitly named proxy iterator could be added later if there is sufficient
demand.

Optional element views

If write-through element access is needed, provide a distinct proxy:

peak = spectrum.peak_view(0)
peak.mz = 500.0

Peak1DView should hold:

  • a strong parent reference;
  • an integer index, not a Peak1D*;
  • the structural mutation generation observed at creation.

Every access should check the generation:

peak = spectrum.peak_view(0)
spectrum.push_back(Peak1D())

peak.mz
# ReferenceError: Peak1DView was invalidated by structural mutation

The proxy must have a different Python type from Peak1D and
provide an explicit conversion:

owned_peak = peak.copy()

Raw vector-element references should never be wrapped directly as apparently
owning Peak1D objects.

Vector-returning getters

Methods such as getSpectra(), getHits(), and
getTransitions() should return honest snapshots:

spectra = experiment.getSpectra()  # list of owning copies

Both operations should be detached:

spectra.append(MSSpectrum())  # does not modify experiment
spectra[0].setRT(42.0)        # does not modify experiment

Use setSpectra(), indexed replacement, or transactional editors
to modify the parent.

The limited exception is a collection intentionally holding
shared_ptr<T>. Such objects may return stable shared
handles, but shared identity must be part of the documented API contract.

A converted Python list must never be described as a "mutable reference to the
internal vector."

Range and sortedness state

The Python API should not permit undefined search results.

  • Position changes mark sortedness unknown.
  • Position and intensity changes mark ranges dirty.
  • Structural mutations increment the mutation generation.
  • Range getters lazily recompute when dirty.
  • findNearest() checks sortedness and raises when necessary.
  • Sorting increments the mutation generation and reorders all metadata arrays.

For example:

spectrum.update_peak(0, mz=700.0)

spectrum.findNearest(700.0)
# ValueError: spectrum is not sorted by m/z; call sortByPosition()

findNearest() should not silently sort because sorting mutates the
container and invalidates outstanding editors or proxies.

The same rules should apply to:

  • MSSpectrum;
  • MSChromatogram;
  • Mobilogram;
  • MSExperiment;
  • FeatureMap;
  • ConsensusMap.

Mutable hashes

Every mutable equality-bearing class should be unhashable:

peak = Peak1D()
hash(peak)
# TypeError: unhashable type: 'Peak1D'

This includes peaks, sequences, identifications, metadata objects, and other
setter-bearing types.

Retain hash only when:

  • the object is immutable;
  • equality and hashing use stable identity; or
  • mutation creates a new object.

Where users need a stable key, provide an explicit conversion:

key = peak.as_tuple()
key = sequence.toString()

Public documentation

Add a user-facing page covering:

  • copies versus views;
  • parent ownership;
  • structural invalidation;
  • fixed view shapes;
  • metadata alignment;
  • sortedness requirements;
  • range invalidation;
  • transactional editing;
  • mutable hashes;
  • the unsafe expert namespace.

Every view method must also document its own concrete invalidators. A generic
memory-management page is not enough because most users discover these methods
through help() and generated API documentation.

The developer wrapping guide must stop recommending raw
nb::make_iterator and Element& indexing as the
default container pattern.

Proposed migration for OpenMS 3.6

  1. Keep pull request [pyOpenMS] Pythonic snake_case properties for Peak1D and MSSpectrum (#9760) #9777's scalar properties.
  2. Keep MSSpectrum.getitem copy-returning.
  3. Make analogous container indexing and iteration copy-returning.
  4. Add update_peak() and transactional edit_*()
    helpers.
  5. Make get_peaks_struct() return a detached copy.
  6. Remove the raw byte _get_peaks_view() methods.
  7. Quarantine unpinned aliases under pyopenms.unsafe.
  8. Fix MSChromatogram and Mobilogram metadata sorting.
  9. Validate metadata lengths during bulk replacement.
  10. Fix the PeakIndex lifetime anchor.
  11. Remove mutable hashes.
  12. Add temporary-owner and reallocation tests under ASan/UBSan.
  13. Add safe pinned views later, only with native export locking or
    copy-on-write storage.

@timosachsenberg

Copy link
Copy Markdown
Contributor

View-first pyOpenMS API proposal

Status: alternative API design optimized for large-data, zero-copy Python use

Date: 2026-07-22

This document interprets, rather than claims to formalize, the priorities
expressed by jcharkow in the discussion on pull request #9777:

  • copying large OpenMS datasets is a recurring pyOpenMS problem;
  • returning references or views is important for making Python a first-class
    language;
  • views might be the advantageous default;
  • questionable operations need checks or warnings;
  • the solution should remain inside pyOpenMS rather than become another
    separately maintained library.

Source discussion:
jcharkow on reference-first access

Related documents:

Executive decision

The view-first API inverts the default of the value-first proposal:

Container access returns checked views by default. Calling
.copy() explicitly produces an independent value.

A pyOpenMS view must not be a raw C++ reference. It is a distinct checked type
that owns its parent, stores an index rather than an element pointer, and
detects structural invalidation.

Large numeric buffers use a separate safety mechanism: buffer-export pinning.
While NumPy directly aliases native memory, operations that can invalidate the
buffer are rejected with BufferError.

Warnings are useful when an operation remains memory-safe. They are not a
substitute for preventing use-after-free.

Comparison with the value-first proposal

Operation Value-first proposal View-first proposal
container[i] Owning copy Checked element view
Iteration Owning copies Checked element views
Vector getter List of owning copies Typed sequence view
Bulk peak access Detached NumPy arrays Zero-copy column/table view
Detachment Default Explicit .copy()
Element mutation Replace or transactional editor Direct write-through view
NumPy aliasing Expert-only until safe First-class, but pinned
Structural mutation Ordinary Invalidates checked views or is blocked by exported buffers

The value-first design provides simpler safety. The view-first design better
addresses the performance problem that motivates jcharkow's proposal.

Public contract

Python surface Required semantics
container[i] Checked view that writes through
container[i].copy() Detached owning value
for item in container Checked views, consistent with indexing
Slice Typed sequence view
Collection getter Typed sequence or table view, not a converted Python list
.copy() on any view Owning snapshot
NumPy export Pinned native buffer with a strong owner
Mutation invalidating checked object views Proceed, increment generation, and optionally warn
Mutation invalidating exported NumPy storage Reject with BufferError
Mutable value or view Unhashable

Checked element views

User-facing behavior

Indexing a spectrum returns a Peak1DView:

peak = spectrum[0]       # Peak1DView
peak.mz = 500.0          # writes through
peak.intensity *= 2

assert spectrum[0].mz == 500.0

Detachment is explicit:

owned_peak = spectrum[0].copy()  # Peak1D
owned_peak.mz = 600.0

assert spectrum[0].mz == 500.0

The view and the value have different Python types:

isinstance(spectrum[0], Peak1DView)       # True
isinstance(spectrum[0].copy(), Peak1D)    # True

This prevents an aliased C++ subobject from masquerading as an owning value.

Internal representation

An element view stores:

  • a strong reference to its parent;
  • the integer element index;
  • the structural mutation generation observed when it was created;
  • no raw pointer or C++ iterator into the element vector.

Every access checks the parent's current generation:

peak = spectrum[0]
spectrum.push_back(Peak1D())

peak.mz
# ReferenceError: Peak1DView was invalidated by structural mutation

The property setter resolves the current element by index and delegates to a
parent-aware mutation function:

parent.setPeakMZ(index, value);

That function can mark ranges and sortedness dirty without exposing the
element's address.

Structural mutations

The following operations increment a container's structural generation:

  • append and push;
  • insertion and erasure;
  • resize and reserve when storage can change;
  • clear;
  • assignment and bulk replacement;
  • set-peaks operations;
  • sorting and selection;
  • swapping;
  • any algorithm that can reorder or replace container elements.

Sorting increments the generation even if no allocation occurs because an
existing index may now denote a different logical element.

Nested object views

Apply the same design to large nested elements:

spectrum = experiment.spectra[3]  # MSSpectrumView
spectrum.rt = 120.0
spectrum.peaks.intensity[:] *= 2

owned_spectrum = spectrum.copy()  # MSSpectrum

Candidate view types include:

  • Peak1DView;
  • ChromatogramPeakView;
  • MobilityPeak1DView;
  • MSSpectrumView;
  • MSChromatogramView;
  • FeatureView;
  • ConsensusFeatureView;
  • identification and hit views.

View classes should be generated from binding metadata where practical.
Manually reproducing every bound method for every view type would be difficult
to keep consistent.

View-first iteration

Iteration must agree with indexing:

for peak in spectrum:
    peak.intensity *= 2  # writes through

The iterator stores:

  • a strong parent reference;
  • the next integer index;
  • the structural generation from iterator creation.

It does not store native begin/end iterators. If the parent generation changes:

iterator = iter(spectrum)
first = next(iterator)
spectrum.push_back(Peak1D())
next(iterator)

# RuntimeError: MSSpectrum was structurally modified during iteration

Users who need owning values request them explicitly:

owned_peaks = [peak.copy() for peak in spectrum]

Typed sequence views

Methods returning C++ vectors should not materialize detached Python lists with
aliased elements. They should return typed sequence views:

spectra = experiment.spectra       # SpectrumSequenceView
hits = identification.hits         # PeptideHitSequenceView
transitions = assay.transitions    # TransitionSequenceView

A sequence view supports:

  • len(view);
  • checked indexing;
  • checked iteration;
  • view-preserving slices;
  • explicit .copy();
  • documented structural operations where appropriate.

Example:

spectra = experiment.spectra

spectra[0].rt = 42.0        # writes through
subset = spectra[10:20]     # SpectrumSequenceView
snapshot = subset.copy()    # list of owning MSSpectrum values

A shared-pointer collection is a special case. Its elements can be stable
shared handles rather than index views, but that identity model must be
explicit in the return type and documentation.

PeakTableView

Per-peak access should be complemented by a first-class bulk interface:

peaks = spectrum.peaks  # PeakTableView

peaks.mz[:] *= 1.0001
peaks.intensity[:] = numpy.sqrt(peaks.intensity)

The table exposes:

peaks.mz
peaks.intensity
peaks.float_arrays
peaks.integer_arrays
peaks.string_arrays

PeakTableView owns the spectrum and represents all data aligned
with peak rows.

Column access

Because Peak1D is stored as an array of structures, m/z and
intensity can be exposed as strided NumPy arrays over the existing storage:

  • m/z starts at the position-field offset with the size of
    Peak1D as its stride;
  • intensity starts at the intensity-field offset with the same stride.

This is zero-copy even though the arrays are not C-contiguous.

Some downstream operations may request contiguous data and therefore copy.
Such copies should be explicit or produce an
OpenMSImplicitCopyWarning above a configurable size threshold.

Aligned row operations

Structural row operations must go through the table:

peaks.sort("mz")
peaks.select(indices)
peaks.erase(mask)

These operations update:

  • peak records;
  • every float data array;
  • every integer data array;
  • every string data array;
  • sortedness state;
  • cached ranges;
  • the structural generation.

A public writable structured ndarray is unsuitable as the primary interface:
its in-place record sorting can reorder peak records without reordering
separate metadata arrays.

If a structured ndarray is offered, it should be a read-only view or a
detached copy:

records = spectrum.peaks.to_numpy(copy=False)  # pinned, read-only view
owned_records = spectrum.peaks.to_numpy(copy=True)

Buffer-export pinning

Checked object views do not contain native element pointers and can detect
invalidation later. NumPy arrays are different: they access memory directly
without calling back into pyOpenMS.

Each native ndarray owner must therefore register an active buffer export with
the parent.

Required behavior

mz = spectrum.peaks.mz

spectrum.resize(100)
# BufferError: cannot resize MSSpectrum while exported arrays exist

After the export is released:

del mz
spectrum.resize(100)

Operations blocked while an exported array exists include:

  • reserve and resize;
  • append, insertion, and erasure;
  • clear;
  • assignment and bulk replacement;
  • storage-swapping sorts and selections;
  • destruction or replacement of nested array storage.

The ndarray owner token:

  • keeps the parent alive;
  • increments the export count when created;
  • decrements it when destroyed;
  • records whether the export is read-only or writable.

All Python-visible algorithms that can structurally mutate the parent must
respect the same export state. If native algorithms can bypass it, the locking
mechanism must be implemented in or below the C++ container layer rather than
only in Python wrappers.

Object-view invalidation warnings

An object view remains memory-safe after structural mutation because it stores
no native element pointer. The mutation may proceed, but the old view becomes
invalid:

peak = spectrum[0]
spectrum.sortByPosition()

# OpenMSViewInvalidationWarning:
# sortByPosition invalidated 1 outstanding Peak1DView

peak.mz
# ReferenceError

Warning is appropriate here because the operation itself remains safe.

Maintaining an exact count of live object views is optional. At minimum, a
container can record that views have been issued since the last generation
change and warn conservatively.

Warning and error policy

Suggested warning categories:

Category Meaning
OpenMSViewInvalidationWarning A safe operation invalidated checked object views
OpenMSImplicitCopyWarning Conversion or an operation materialized a potentially large copy
OpenMSAlignmentWarning The caller explicitly discarded or replaced aligned metadata
BufferError An operation would invalidate directly exported native memory
ReferenceError A checked view is used after its parent generation changed

Configuration could use Python warning filters or a small pyOpenMS option API:

pyopenms.set_option("view_invalidation", "warn")  # warn, error, ignore
pyopenms.set_option("implicit_copy", "warn")

Memory-unsafe buffer invalidation must not have an ignore mode in the ordinary
API.

Range and sortedness state

Write-through views make explicit dirty-state tracking necessary.

Required state transitions

  • Changing a position marks sortedness unknown.
  • Changing a position or intensity marks ranges dirty.
  • Structural mutation increments the generation.
  • Sorting establishes the appropriate sortedness state.
  • Aligned selection and replacement mark ranges dirty.

Range access should lazily refresh dirty caches:

spectrum[0].intensity = 500.0
maximum = spectrum.max_intensity  # refreshes if dirty

Search operations must reject unsorted input:

spectrum[0].mz = 700.0
spectrum.findNearest(700.0)

# ValueError: spectrum is not sorted by m/z; call sortByPosition()

The search function should not silently sort because sorting invalidates
outstanding object views and may be unexpectedly expensive.

Metadata-array alignment

All row-count-changing APIs must validate aligned metadata arrays.

set_peaks() must not silently retain metadata of an incompatible
shape. A view-first API can expose explicit policies:

spectrum.set_peaks(mz, intensity, metadata="error")  # default
spectrum.set_peaks(mz, intensity, metadata="clear")

For atomic replacement with metadata:

snapshot = spectrum.peaks.copy()  # owning PeakTable
snapshot.mz[:] *= 1.0001
spectrum.set_peak_table(snapshot)

The current native sorting defects in MSChromatogram and
Mobilogram must be fixed before their table views are writable.

Imaging, OpenSwath, and result arrays

The same rules apply outside peak containers.

IonImage

Intensity and mask form aligned state. A writable intensity-only ndarray cannot
be the complete mutation API.

image.pixels.set(x, y, intensity)

A bulk image editor must update both arrays or make the mask policy explicit.

MSImagingGeometry

Pixel coordinates and lookup_ must remain synchronized. Pixel
records can be exposed as a read-only pinned view, but coordinate mutation must
go through geometry-aware methods.

OpenSwath arrays

Coordinate, intensity, and drift arrays need a common sequence-length contract.
Shared-pointer ownership can keep replaced arrays alive, while resizing the
array's internal vector still requires export pinning.

RescoreOutput

Scores, q-values, and posterior error probabilities are aligned. Prefer a
read-only result-table view or validate all lengths before algorithmic use.

Hashing

View types are mutable aliases and must be unhashable. Owning value types with
content equality must also be unhashable while mutable:

hash(spectrum[0])
# TypeError: unhashable type: 'Peak1DView'

hash(spectrum[0].copy())
# TypeError: unhashable type: 'Peak1D'

Stable keys should be explicit immutable representations rather than mutable
OpenMS objects.

Keeping the design inside pyOpenMS

The design does not require a separately distributed wrapper library.

Possible implementation locations are:

  1. direct C++ nanobind view classes;
  2. generated binding helpers for element and sequence views;
  3. Python facade classes shipped inside the existing pyOpenMS package;
  4. a combination in which lifetime-critical operations live in C++ and
    ergonomic collection properties live in pyOpenMS addons.

A facade within the same package can restrict the public API without creating
another release, dependency, or repository. The low-level bindings can remain
private implementation details where compatibility permits.

Implementation requirements

This design is substantially more invasive than returning
reference_internal.

It requires:

  1. A structural mutation generation for every mutable container.
  2. Strong parent ownership in every view.
  3. Index-based element proxies with no stored element pointer.
  4. Index-and-generation iterators instead of native iterators.
  5. Typed sequence views instead of vector-to-list conversion.
  6. Buffer-export counters for NumPy aliases.
  7. Structural mutators and algorithms that respect active exports.
  8. Dirty range and sortedness tracking.
  9. Correct aligned sorting and selection for all metadata-array kinds.
  10. Explicit view and value Python types.
  11. ASan/UBSan tests for temporary owners and every reallocation path.
  12. Public documentation centered on views, .copy(), warnings,
    and buffer locking.

Warnings alone do not make raw references safe. The generation and export
mechanisms are prerequisites.

Proposed user-facing examples

Direct element editing

peak = spectrum[0]
peak.mz = 500.0
peak.intensity *= 2

Explicit detachment

owned_peak = spectrum[0].copy()
owned_spectrum = experiment.spectra[0].copy()
owned_hits = identification.hits.copy()

Bulk editing

peaks = spectrum.peaks
peaks.mz[:] += calibration_offset
peaks.intensity[:] = numpy.maximum(peaks.intensity, 0)

Safe structural mutation

peak = spectrum[0]
spectrum.push_back(Peak1D())  # invalidates peak, may warn

peak.mz                     # raises ReferenceError

Pinned NumPy storage

mz = spectrum.peaks.mz
spectrum.push_back(Peak1D())  # raises BufferError

del mz
spectrum.push_back(Peak1D())  # succeeds

Aligned sorting

spectrum.peaks.sort("mz")

Suggested migration path

Phase 1: correctness infrastructure

  1. Fix metadata-array sorting and validation.
  2. Introduce structural mutation generations.
  3. Replace raw iterators with index-and-generation iterators.
  4. Add dirty range and sortedness state.
  5. Remove mutable hashes.

Phase 2: checked object views

  1. Introduce Peak1DView and analogous peak views.
  2. Make spectrum, chromatogram, and mobilogram indexing return views.
  3. Add .copy() to every view.
  4. Introduce typed sequence views for maps and identification collections.
  5. Add invalidation warnings and ReferenceError tests.

Phase 3: safe zero-copy arrays

  1. Add buffer-export pinning.
  2. Introduce PeakTableView.
  3. Expose strided m/z and intensity arrays.
  4. Make structured exports read-only or detached.
  5. Add copy warnings for hidden contiguous conversions.

Phase 4: consistent public surface

  1. Add collection properties such as spectrum.peaks,
    experiment.spectra, and
    identification.hits.
  2. Deprecate ambiguous copy/reference getters.
  3. Publish a complete view and ownership guide.
  4. Keep old getter/setter methods during a documented compatibility period.

Recommendation

If avoiding large-data copies is the primary design goal, adopt the view-first
model rather than raw references:

  • checked views by default;
  • .copy() as universal explicit detachment;
  • typed sequence views instead of Python-list materialization;
  • PeakTableView for large numeric data;
  • generation-based invalidation for object views;
  • hard buffer pinning for NumPy arrays;
  • warnings only when the operation remains memory-safe;
  • no raw T& wrappers.

This provides the behavior jcharkow appears to want while addressing the
ownership and invalidation concerns raised by jpfeuffer:
reference and reordering concern.

@timosachsenberg

Copy link
Copy Markdown
Contributor

I added two alternatives. But I don’t feel competent enough to really judge all implications including potential issues when going free threaded, also backwards compatibility is probably a major issue for both… etc. Someone really needs to dive into this topic …

@aliviahossain

Copy link
Copy Markdown
Contributor Author

I went through this discussion thread. To answer @jcharkow 's question directly: as a newer user, the thing I'd probably want most is consistency. The thing of copy vs reference by itself is that they disagree. iter hands out references while getitem returns a copy, and get_peaks_struct() writes through while get_peaks() doesn't. That mismatch is harder to learn than either rule would be on its own. So my honest expectation is one clear default, plus a loud, explicit way to opt into the other.

On the design, I think it helps to split two problems that look like one only:

  • Object access (spectrum[0]) can be made safe with a parent reference, an index, and a generation counter. It never holds a raw pointer, so it can detect invalidation and raise cleanly. A warning is fine here because the operation stays memory safe.
  • NumPy buffers are different. NumPy reads and writes the memory directly without calling back into pyOpenMS, so a generation counter can't protect them. Those need real buffer-export pinning that blocks resize/sort while an export is alive, and that has to be a hard error, not a warning.

On the pandas angle: @jcharkow 's warning-on-questionable-op idea is basically the SettingWithCopyWarning model, and I'd lean away from it since pandas itself is moving off that toward copy-on-write. @jpfeuffer 's view-by-default-plus-.copy() suggestion is actually closer to where I'd land.

Where I've landed: the copy cost that actually hurts on large data is bulk, whole spectra and big arrays, not per-element Peak1D copies (16 bytes). So we can get most of the performance win from a bulk PeakTableView with strided zero-copy mz/intensity columns plus pinning, while keeping a [ ] copy and aligning iteration to also copy. Note that iteration hands out references today, so that alignment is itself a small behaviour change and would need a deprecation note, same as flipping the default indexing semantics. I don't think either should happen without a deprecation cycle. A couple of correctness items are worth doing regardless of which default we pick: set_peaks currently resizes the peak container without realigning existing data arrays, and mutable value types are still hashable. (sortByPosition already reorders the data arrays for MSSpectrum and MSChromatogram, so that side is fine.)

@timosachsenberg I guess on free threading every safety mechanism in the view proposals (generation counters, buffer-export counts, keep-alive refs) is shared mutable state that would need to be atomic under a no-GIL interpreter, whereas copies have nothing to race on. That's another reason to keep the safe copy as the default and treat checked views and pinned buffers as an explicit opt-in we harden carefully. On backwards compatibility, I'd say it's a real constraint for both proposals, not just the view-first one, since even the value-first path changes iteration semantics, removes mutable hashes, and detaches get_peaks_struct.

Please note, that I was doubtful about a few behaviours/changes, so I ran a check through Claude before writing all of this. Also this PR is purely additive now (snake_case properties only, getitem back to copy), so none of this blocks it. It can be merged safely, and the ownership/view work can proceed as its own.

@timosachsenberg

Copy link
Copy Markdown
Contributor

I like the current PR. And thanks for the nice analysis. @jpfeuffer @jcharkow what about you?
One favor: if everyone agrees can you also do this for mschromatogram? and maybe mobilogram?
And maybe make a quick sweep with an agent which core classes are most widely used and could profit from the scalar approach as well?

@jpfeuffer

Copy link
Copy Markdown
Contributor

Yes, PR can be merged. Comments should be turned into an issue.

@aliviahossain

Copy link
Copy Markdown
Contributor Author

@timosachsenberg , @jpfeuffer Alright, then please merge this PR. I'll later open issues for MSChromatogram and Mobilogram, and also thoroughly go through the codebase to confirm which classes are most benefitted by the scalar properties. Thanks !

@timosachsenberg
timosachsenberg merged commit 27e1a36 into OpenMS:develop Jul 23, 2026
39 checks passed
@timosachsenberg

Copy link
Copy Markdown
Contributor

As requested by @jpfeuffer, the ownership / copy-vs-view discussion from this thread is now preserved in #9792 so it doesn't get lost in a merged PR.

It captures the inconsistency itself (__getitem__ copies while __iter__ still hands out references, get_peaks() copies while get_peaks_struct() writes through), the positions from @jcharkow, @jpfeuffer and @timosachsenberg, both candidate designs (value-first vs. view-first), the open questions on backwards compatibility and free-threading, and the correctness items that are worth fixing regardless of which default wins.

The MSChromatogram / Mobilogram scalar-property follow-ups @timosachsenberg asked for are noted there as separate, non-blocking items — @aliviahossain, feel free to open those as their own issues.

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.

Make core pyOpenMS classes more Pythonic: systematize snake_case property access

4 participants