Repository navigation
pyopenms: add zero-copy get_peaks_struct() for Mobilogram with tests - #8842
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds an ABI size check and a new C++ binding Changes
Sequence Diagram(s)sequenceDiagram
participant Py as Python code
participant Addon as pyOpenMS addon
participant Bind as C++ binding
participant Obj as Mobilogram C++ object
Py->>Addon: call get_peaks_struct()
Addon->>Bind: call get_peaks_struct_mv() -> returns uint8 ndarray (view)
Bind-->>Obj: reference internal pointer to Obj.peaks
Bind-->>Addon: return ndarray referencing Obj.peaks
Addon->>Py: cast/view ndarray as structured dtype (mobility,intensity) zero-copy
Py->>Py: read/modify structured array
Py->>Obj: modifications are reflected in Obj.peaks (shared memory)
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/pyOpenMS/bindings/bind_kernel.cpp`:
- Around line 1636-1660: Update the get_peaks_struct_raw binding's docstring to
warn that the returned raw zero-copy byte view points directly into Mobilogram's
underlying std::vector (via &self[0]) and can become invalid if the Mobilogram
undergoes capacity-changing operations (push_back, resize, reserve, clear,
etc.); reference the types MobilityPeak1D and Mobilogram and mention that while
nb::find(self) keeps the Python object alive, it does not prevent the underlying
buffer from being reallocated and invalidated.
In `@src/pyOpenMS/pyopenms/addons/mobilogram.py`:
- Around line 93-101: Add compile-time ABI guards in the C++ bindings and an
optional runtime guard in the Python accessor: in bind_kernel.cpp near the
get_peaks_struct_raw binding add static_asserts to lock the layout of
OpenMS::MobilityPeak1D (e.g., static_assert(sizeof(OpenMS::MobilityPeak1D)==16,
"...") and static_assert(offsetof(OpenMS::MobilityPeak1D, intensity_)==8,
"...")) so the ABI mismatch fails at compile time; additionally, in
src/pyOpenMS/pyopenms/addons/mobilogram.py (around the peak_dtype /
raw_view.view usage) add a small runtime check that verifies peak_dtype.itemsize
and the intensity field offset match the expected values before casting and
raise an ImportError or ValueError with a clear message if they do not.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 0b982f6f-7dd1-4b45-9889-a45ee53c48f6
📒 Files selected for processing (3)
src/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/pyopenms/addons/mobilogram.pysrc/pyOpenMS/tests/unittests/test_mobilogram_struct_view.py
|
can you check how wie name memory views in other bindings? here you used raw I think. But maybe we have a different naming schema |
|
I checked the bindings for FloatDataArray and IntegerDataArray and noticed they use the _mv suffix for memory views (e.g., get_data_mv). I’ll rename this to get_peaks_struct_mv to follow the same naming pattern. |
…w *_mv memory-view naming convention
… when container reallocates
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/pyOpenMS/bindings/bind_kernel.cpp`:
- Line 1563: Update the Mobilogram class docstring to replace the stale method
name `get_peaks_struct_raw` with the actual bound method `get_peaks_struct_mv`;
locate the Mobilogram binding definition and its docstring in bind_kernel.cpp
(search for "Mobilogram" and the string containing "get_peaks_struct_raw") and
update the text so users see `get_peaks_struct_mv` alongside `get_peaks` and
`set_peaks`.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ead06d9d-0625-4987-bcd9-f581f80ce9d5
📒 Files selected for processing (2)
src/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/pyopenms/addons/mobilogram.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
|
Thanks for the review! |
Summary
This PR introduces a new zero-copy accessor for mobilogram peak data:
Mobilogram.get_peaks_struct()Unlike
Mobilogram.get_peaks(), which copies mobility and intensity values into separate NumPy arrays, the new method provides a NumPy view directly over the underlying C++ peak container.This allows Python users to access large mobilograms efficiently without the overhead of repeated memory allocation or copying. The approach follows the same pattern used for other peak containers in pyOpenMS, keeping the API style consistent across the codebase.
Motivation
Currently,
Mobilogram.get_peaks()returns two NumPy arrays (mobility and intensity) created by copying values from the underlying C++ container.For large mobilograms, this introduces an O(n) cost every time peak data is accessed from Python.
The new
get_peaks_struct()method instead returns a NumPy view over the internal memory, avoiding the copy step entirely. This reduces both memory usage and execution time, which is particularly beneficial for workflows that repeatedly access peak data from Python.Implementation
A nanobind binding was added in
bind_kernel.cppto expose the underlyingstd::vector<MobilityPeak1D>memory as a NumPy array.On the Python side, a small addon converts this raw view into a structured NumPy array with two named fields:
mobilityintensityThis keeps the view zero-copy while making it convenient to use directly from Python.
To ensure object lifetime safety, the binding uses
nb::rv_policy::reference_internal, which guarantees that the NumPy array remains valid as long as the correspondingMobilograminstance exists.Why this layout works
The implementation relies on the memory layout of
MobilityPeak1D, which stores mobility and intensity as contiguous numeric values in the peak container. This makes it possible to expose the underlying peak vector as a NumPy view without copying the data.The Python addon then builds a structured array with named fields (
mobility,intensity) on top of this view. This keeps the zero-copy semantics while providing a more convenient interface for Python users.Tests
A dedicated test suite (
test_mobilogram_struct_view.py) accompanies this change.The tests verify:
get_peaks()All tests pass successfully.
Benchmark
Benchmarks were run on macOS (Apple Silicon) with Python 3.14.
For small mobilograms (~100 peaks),
get_peaks()is slightly faster (~1.3 µs) thanget_peaks_struct()(~2.0 µs). As the number of peaks increases, the cost of copying inget_peaks()grows linearly, whileget_peaks_struct()stays essentially constant because it only creates a view.As expected,
get_peaks()scales linearly with the number of peaks due to the required data copy, whileget_peaks_struct()remains effectively constant because it returns a zero-copy view over the underlying C++ container. For small mobilograms both methods perform similarly, but as dataset size increases the zero-copy accessor becomes dramatically faster.Backward Compatibility
This change is fully backward compatible.
The existing
get_peaks()method remains unchanged, andget_peaks_struct()simply provides a more efficient option for performance-sensitive workflows.Thanks for taking a look!
Summary by CodeRabbit
New Features
Documentation
Tests