Skip to content

pyopenms: add zero-copy get_peaks_struct() for Mobilogram with tests - #8842

Merged
timosachsenberg merged 8 commits into
OpenMS:developfrom
Srikanthkn0:mobilogram-zero-copy
Mar 5, 2026
Merged

timosachsenberg merged 8 commits into
OpenMS:developfrom
Srikanthkn0:mobilogram-zero-copy

Conversation

@Srikanthkn0

@Srikanthkn0 Srikanthkn0 commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

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.cpp to expose the underlying std::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:

  • mobility
  • intensity

This 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 corresponding Mobilogram instance 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:

  • Value consistency with get_peaks()
  • Zero-copy mutation propagation
  • Correct behavior for empty mobilograms
  • Single-peak mobilograms
  • Correctness on large datasets
  • Memory lifetime safety when the Python object goes out of scope
  • Mutation propagation back to the underlying C++ container

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) than get_peaks_struct() (~2.0 µs). As the number of peaks increases, the cost of copying in get_peaks() grows linearly, while get_peaks_struct() stays essentially constant because it only creates a view.

Peaks get_peaks() get_peaks_struct() Speedup
100 1.3 µs 2.0 µs 0.7x
1,000 3.5 µs 2.0 µs 1.7x
10,000 23.1 µs 1.9 µs 12.3x
100,000 219.8 µs 1.8 µs 119.9x
1,000,000 2834.2 µs 1.9 µs 1478.5x

As expected, get_peaks() scales linearly with the number of peaks due to the required data copy, while get_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, and get_peaks_struct() simply provides a more efficient option for performance-sensitive workflows.


Thanks for taking a look!

Summary by CodeRabbit

  • New Features

    • Added get_peaks_struct() to Mobilogram for zero-copy structured-array access to mobility and intensity, complementing existing access and allowing in-place edits to reflect in the Mobilogram.
  • Documentation

    • Updated Mobilogram docs to describe the new structured-array access path and lifetime/caveat notes.
  • Tests

    • Added unit tests covering consistency, zero-copy behavior, empty/single/large datasets, mutation propagation, and lifetime guarantees.

@coderabbitai

coderabbitai Bot commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

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: 6fd5acf8-c8da-4e4d-9a61-a429a008e9a1

📥 Commits

Reviewing files that changed from the base of the PR and between cfdcf1b and 5d86dea.

📒 Files selected for processing (1)
  • src/pyOpenMS/bindings/bind_kernel.cpp

📝 Walkthrough

Walkthrough

Adds an ABI size check and a new C++ binding get_peaks_struct_mv that returns a NumPy uint8 view over raw MobilityPeak1D memory (rv_policy reference_internal). A Python addon get_peaks_struct overlays a structured dtype (mobility: float64, intensity: float32) for zero-copy access. Tests added.

Changes

Cohort / File(s) Summary
C++ binding & ABI guard
src/pyOpenMS/bindings/bind_kernel.cpp
Adds static_assert ABI guard for MobilityPeak1D size and a new Mobilogram binding method get_peaks_struct_mv that returns a zero-copy uint8 NumPy view over the peak structs (contiguous n * sizeof(MobilityPeak1D)), uses nb::rv_policy::reference_internal, documents empty-container behavior and lifetime caveats.
Python addon
src/pyOpenMS/pyopenms/addons/mobilogram.py
Adds @addon("Mobilogram") def get_peaks_struct(self) which interprets the uint8 view from get_peaks_struct_mv() as a NumPy structured array with fields mobility (float64) and intensity (float32), offsets [0,8], itemsize 16, producing an AoS zero-copy view.
Unit tests
src/pyOpenMS/tests/unittests/test_mobilogram_struct_view.py
Adds tests validating alignment between get_peaks and the struct view, zero-copy mutation propagation, empty and single-peak cases, large dataset behavior, and memory-lifetime across GC.

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

Possibly related PRs

Poem

🐇 I nibble bytes in quiet code at dawn,
A struct of peaks on memory lawn,
No copy made, just gentle view,
Mobility and intensity, true—
Hop, change, persist, then carry on.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding a zero-copy struct accessor for Mobilogram with accompanying tests. It is specific, describes the primary functionality, and matches the actual changes in the PR.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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 and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between be7efde and 8200c8f.

📒 Files selected for processing (3)
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/pyopenms/addons/mobilogram.py
  • src/pyOpenMS/tests/unittests/test_mobilogram_struct_view.py

Comment thread src/pyOpenMS/bindings/bind_kernel.cpp Resolved
@timosachsenberg

Copy link
Copy Markdown
Contributor

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

@Srikanthkn0

Copy link
Copy Markdown
Contributor Author

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 8200c8f and cfdcf1b.

📒 Files selected for processing (2)
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/pyopenms/addons/mobilogram.py

Comment thread src/pyOpenMS/bindings/bind_kernel.cpp Resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

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

Thanks 🙏

@Srikanthkn0

Copy link
Copy Markdown
Contributor Author

Thanks for the review!

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.

2 participants