Repository navigation
[pyOpenMS] Pythonic snake_case properties for Peak1D and MSSpectrum (#9760) - #9777
timosachsenberg merged 3 commits into
Conversation
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.
|
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 (3)
📝 WalkthroughWalkthroughChangespyOpenMS API enhancement
Suggested reviewers: 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.
🧹 Nitpick comments (2)
src/pyOpenMS/tests/unittests/test_snake_case_properties.py (2)
60-64: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider asserting the remaining legacy getters for completeness.
The tests verify most legacy getters to ensure the roundtrip stays in sync, but
getDriftTime()andgetComment()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 valueConsider verifying the presence of
drift_timelegacy methods.For thoroughness, you could also assert the presence of
getDriftTime,setDriftTime,getDriftTimeUnit, andsetDriftTimeUnitalongside 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
📒 Files selected for processing (6)
CHANGELOGdoc/pyopenms/docs/source/user_guide/first_steps.rstdoc/pyopenms/docs/source/user_guide/ms_data.rstsrc/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/bindings/bind_spectrum.cppsrc/pyOpenMS/tests/unittests/test_snake_case_properties.py
|
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. |
|
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. |
|
@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? |
There was a problem hiding this comment.
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 winAdd reordering to the invalidation note.
MSSpectrumcan reorder peaks in place viasortByPosition(),sortByIntensity(),sortByIonMobility(), andsort(...), so a retainedspectrum[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.
|
I personally would prefer this. Maybe there were even some experiments on Views when @timosachsenberg moved it to nanobind? |
|
@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. |
|
We have a few views in the context of exposing internal data in numpy |
|
@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.
|
|
@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. |
|
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. 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. I wonder what @timosachsenberg and @jcharkow and Claude have to say. |
|
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. |
|
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. |
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.
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... |
|
Codex sol on the highest level suggests this: Design goalThe pyOpenMS API should be value-semantic by default, transactional for Users should not need to understand
Public contract
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 commitIteration must behave consistently: for peak in spectrum:
peak.mz += 1.0 # modifies the copy onlyThis avoids the current indexing-copy/iteration-reference split. Convenient mutation without raw referencesThe 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 *= 2The editor should:
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 Bulk peak accessKeep 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 Safe zero-copy viewsIf 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 BufferErrorThis requires:
Without that infrastructure, raw views should live in an explicit expert view = pyopenms.unsafe.peaks_view(spectrum)A name such as Generation counters alone cannot protect NumPy arrays because NumPy reads and Metadata must be edited as aligned rowsWritable views of only 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)
Commit should validate all lengths and replace everything atomically.
Silent preservation across unrelated peak replacement is unsafe. The same aligned-row principle applies to:
Geometry pixels should never expose a writable raw view because coordinate Iterator ownershipReplace
If the generation changes during iteration, raise: 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.0An explicitly named proxy iterator could be added later if there is sufficient Optional element viewsIf write-through element access is needed, provide a distinct proxy: peak = spectrum.peak_view(0)
peak.mz = 500.0
Every access should check the generation: peak = spectrum.peak_view(0)
spectrum.push_back(Peak1D())
peak.mz
# ReferenceError: Peak1DView was invalidated by structural mutationThe proxy must have a different Python type from owned_peak = peak.copy()Raw vector-element references should never be wrapped directly as apparently Vector-returning gettersMethods such as spectra = experiment.getSpectra() # list of owning copiesBoth operations should be detached: spectra.append(MSSpectrum()) # does not modify experiment
spectra[0].setRT(42.0) # does not modify experimentUse The limited exception is a collection intentionally holding A converted Python list must never be described as a "mutable reference to the Range and sortedness stateThe Python API should not permit undefined search results.
For example: spectrum.update_peak(0, mz=700.0)
spectrum.findNearest(700.0)
# ValueError: spectrum is not sorted by m/z; call sortByPosition()
The same rules should apply to:
Mutable hashesEvery mutable equality-bearing class should be unhashable: peak = Peak1D()
hash(peak)
# TypeError: unhashable type: 'Peak1D'This includes peaks, sequences, identifications, metadata objects, and other Retain
Where users need a stable key, provide an explicit conversion: key = peak.as_tuple()
key = sequence.toString()Public documentationAdd a user-facing page covering:
Every view method must also document its own concrete invalidators. A generic The developer wrapping guide must stop recommending raw Proposed migration for OpenMS 3.6
|
View-first pyOpenMS API proposalStatus: 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
Source discussion: Related documents:
Executive decisionThe view-first API inverts the default of the value-first proposal:
A pyOpenMS view must not be a raw C++ reference. It is a distinct checked type Large numeric buffers use a separate safety mechanism: buffer-export pinning. Warnings are useful when an operation remains memory-safe. They are not a Comparison with the value-first proposal
The value-first design provides simpler safety. The view-first design better Public contract
Checked element viewsUser-facing behaviorIndexing a spectrum returns a peak = spectrum[0] # Peak1DView
peak.mz = 500.0 # writes through
peak.intensity *= 2
assert spectrum[0].mz == 500.0Detachment is explicit: owned_peak = spectrum[0].copy() # Peak1D
owned_peak.mz = 600.0
assert spectrum[0].mz == 500.0The view and the value have different Python types: isinstance(spectrum[0], Peak1DView) # True
isinstance(spectrum[0].copy(), Peak1D) # TrueThis prevents an aliased C++ subobject from masquerading as an owning value. Internal representationAn element view stores:
Every access checks the parent's current generation: peak = spectrum[0]
spectrum.push_back(Peak1D())
peak.mz
# ReferenceError: Peak1DView was invalidated by structural mutationThe property setter resolves the current element by index and delegates to a parent.setPeakMZ(index, value);That function can mark ranges and sortedness dirty without exposing the Structural mutationsThe following operations increment a container's structural generation:
Sorting increments the generation even if no allocation occurs because an Nested object viewsApply the same design to large nested elements: spectrum = experiment.spectra[3] # MSSpectrumView
spectrum.rt = 120.0
spectrum.peaks.intensity[:] *= 2
owned_spectrum = spectrum.copy() # MSSpectrumCandidate view types include:
View classes should be generated from binding metadata where practical. View-first iterationIteration must agree with indexing: for peak in spectrum:
peak.intensity *= 2 # writes throughThe iterator stores:
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 iterationUsers who need owning values request them explicitly: owned_peaks = [peak.copy() for peak in spectrum]Typed sequence viewsMethods returning C++ vectors should not materialize detached Python lists with spectra = experiment.spectra # SpectrumSequenceView
hits = identification.hits # PeptideHitSequenceView
transitions = assay.transitions # TransitionSequenceViewA sequence view supports:
Example: spectra = experiment.spectra
spectra[0].rt = 42.0 # writes through
subset = spectra[10:20] # SpectrumSequenceView
snapshot = subset.copy() # list of owning MSSpectrum valuesA shared-pointer collection is a special case. Its elements can be stable PeakTableViewPer-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
Column accessBecause
This is zero-copy even though the arrays are not C-contiguous. Some downstream operations may request contiguous data and therefore copy. Aligned row operationsStructural row operations must go through the table: peaks.sort("mz")
peaks.select(indices)
peaks.erase(mask)These operations update:
A public writable structured ndarray is unsuitable as the primary interface: If a structured ndarray is offered, it should be a read-only view or a records = spectrum.peaks.to_numpy(copy=False) # pinned, read-only view
owned_records = spectrum.peaks.to_numpy(copy=True)Buffer-export pinningChecked object views do not contain native element pointers and can detect Each native ndarray owner must therefore register an active buffer export with Required behaviormz = spectrum.peaks.mz
spectrum.resize(100)
# BufferError: cannot resize MSSpectrum while exported arrays existAfter the export is released: del mz
spectrum.resize(100)Operations blocked while an exported array exists include:
The ndarray owner token:
All Python-visible algorithms that can structurally mutate the parent must Object-view invalidation warningsAn object view remains memory-safe after structural mutation because it stores peak = spectrum[0]
spectrum.sortByPosition()
# OpenMSViewInvalidationWarning:
# sortByPosition invalidated 1 outstanding Peak1DView
peak.mz
# ReferenceErrorWarning is appropriate here because the operation itself remains safe. Maintaining an exact count of live object views is optional. At minimum, a Warning and error policySuggested warning categories:
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 Range and sortedness stateWrite-through views make explicit dirty-state tracking necessary. Required state transitions
Range access should lazily refresh dirty caches: spectrum[0].intensity = 500.0
maximum = spectrum.max_intensity # refreshes if dirtySearch 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 Metadata-array alignmentAll row-count-changing APIs must validate aligned metadata arrays.
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 Imaging, OpenSwath, and result arraysThe same rules apply outside peak containers. IonImageIntensity and mask form aligned state. A writable intensity-only ndarray cannot image.pixels.set(x, y, intensity)A bulk image editor must update both arrays or make the mask policy explicit. MSImagingGeometryPixel coordinates and OpenSwath arraysCoordinate, intensity, and drift arrays need a common sequence-length contract. RescoreOutputScores, q-values, and posterior error probabilities are aligned. Prefer a HashingView types are mutable aliases and must be unhashable. Owning value types with 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 Keeping the design inside pyOpenMSThe design does not require a separately distributed wrapper library. Possible implementation locations are:
A facade within the same package can restrict the public API without creating Implementation requirementsThis design is substantially more invasive than returning It requires:
Warnings alone do not make raw references safe. The generation and export Proposed user-facing examplesDirect element editingpeak = spectrum[0]
peak.mz = 500.0
peak.intensity *= 2Explicit detachmentowned_peak = spectrum[0].copy()
owned_spectrum = experiment.spectra[0].copy()
owned_hits = identification.hits.copy()Bulk editingpeaks = spectrum.peaks
peaks.mz[:] += calibration_offset
peaks.intensity[:] = numpy.maximum(peaks.intensity, 0)Safe structural mutationpeak = spectrum[0]
spectrum.push_back(Peak1D()) # invalidates peak, may warn
peak.mz # raises ReferenceErrorPinned NumPy storagemz = spectrum.peaks.mz
spectrum.push_back(Peak1D()) # raises BufferError
del mz
spectrum.push_back(Peak1D()) # succeedsAligned sortingspectrum.peaks.sort("mz")Suggested migration pathPhase 1: correctness infrastructure
Phase 2: checked object views
Phase 3: safe zero-copy arrays
Phase 4: consistent public surface
RecommendationIf avoiding large-data copies is the primary design goal, adopt the view-first
This provides the behavior jcharkow appears to want while addressing the |
|
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 … |
|
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:
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. |
|
I like the current PR. And thanks for the nice analysis. @jpfeuffer @jcharkow what about you? |
|
Yes, PR can be merged. Comments should be turned into an issue. |
|
@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 ! |
|
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 ( The |

Description:
Applies the existing
def_prop_rwbinding pattern consistently to the core kernel classes, so pyOpenMS objects can be accessed the Pythonic way.Properties added (additive):
Peak1D:mz,intensity(posis skipped since it is just an alias ofmz)MSSpectrum:rt,ms_level,drift_time,drift_time_unit,name,comment,native_idThe
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, sospectrum[i].mz = xmutates the peak in place. This matches howMobilogram,FeatureMapandConsensusMapalready 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.pycovers 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
Baseline (before): properties absent, indexing returns a copy.
After: properties read/write and
spectrum[0].mz = xsticks (reference).Tests: 7/7 passing.
Checklist
Closes #9760
@jcharkow , @timosachsenberg Please review the PR. Thanks !
Summary by CodeRabbit
snake_caseread/write properties forMSSpectrummetadata andPeak1Dvalues (e.g.,rt,ms_level,drift_time,mz,intensity).get*/set*methods available alongside the new properties (including enum-backed drift time units).