Skip to content

Fix ChromatogramPeak IntensityType consistency and unify zero-copy API conventions - #8857

Merged
timosachsenberg merged 34 commits into
developfrom
feature/zero-copy-api-unification
Mar 10, 2026
Merged

timosachsenberg merged 34 commits into
developfrom
feature/zero-copy-api-unification

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Fix Type consistency for IntensityType #3379: Change ChromatogramPeak::IntensityType from double to float, matching all other peak types (Peak1D, Peak2D, MobilityPeak1D, MobilityPeak2D)
  • Modernize typedef to using declarations across all peak types
  • Unify zero-copy API conventions in pyOpenMS bindings (relates to Inconsistent naming/implementation conventions for zero-copy array access (_view vs _mv) #8855):
    • _mv = typed zero-copy column view, returns None if empty (e.g. get_data_mv(), get_matrix_mv())
    • _struct = structured zero-copy record view, returns empty structured array if empty (e.g. get_peaks_struct())
    • Eliminate orphan conventions (_view → internal _get_peaks_view, _as_view → _mv)

Changes

C++ core (issue #3379):

  • ChromatogramPeak::IntensityType: double → float (16-byte AoS layout preserved: double pos | float intensity | 4B padding)
  • Fix narrowing conversions in FeatureFinderMultiplexAlgorithm, ChromeleonFile, LayerData1DChrom with static_cast<ChromatogramPeak::IntensityType>
  • Add static_assert compile-time checks for type consistency across all peak types
  • Modernize typedef → using in Peak2D, MobilityPeak2D

pyOpenMS bindings:

  • Update ChromatogramPeak binding to use float intensity
  • Update MSChromatogram get_peaks/set_peaks for float intensity arrays
  • Implement get_peaks_struct() in C++ for all three peak containers (MSSpectrum, MSChromatogram, Mobilogram) with proper structured dtype {coordinate: float64, intensity: float32}
  • Add _get_peaks_view() (internal raw byte view) for all three
  • Add static_assert(sizeof(...) == 16) for all three peak types
  • Add empty guards to all 6 OpenSwath _mv methods (return None on empty)
  • Rename get_matrix_as_view() → get_matrix_mv() with empty guard
  • Move MSSpectrum get_peaks_struct from Python addon to C++ binding
  • Remove redundant Python addons for get_peaks_struct (MSSpectrum, Mobilogram)

Tests (34 passing):

  • test_zerocopy_conventions.py: 7 cross-cutting convention tests (empty handling, writeback, no public _view methods)
  • test_spectrum_zerocopy.py: zero-copy modification, memory safety, empty struct
  • test_mschromatogram_struct_view.py: zero-copy, memory safety, empty, dtype, type consistency
  • test_mobilogram_struct_view.py: values, zero-copy, empty, single peak, 100k dataset, memory lifetime, mutation
  • test_OpenSwathDataStructures.py: empty guards for all OpenSwath _mv methods
  • test_matrix_zerocopy.py: bidirectional zero-copy, empty guard

Test plan

  • All 34 pyOpenMS zero-copy tests pass
  • C++ build succeeds with no warnings from narrowing conversions
  • Zero-copy verified: numpy writes propagate to C++ objects
  • Memory safety verified: views survive GC of local scope
  • Arrow/Parquet code unaffected (uses get_peaks()/get_data_dict(), not view methods)
  • CI full test suite

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Zero-copy structured and raw-byte views for spectra, chromatograms, and mobilograms; get_peaks_struct added for some types.
  • Behavior

    • New *_view accessors return empty/null-equivalent views for empty containers; writable views reflect underlying data. Some helper addon structured helpers were removed.
  • Refactor

    • Peak/chromatogram/spectrum intensities standardized to 32-bit float in bindings.
  • Chores

    • Deprecated "mv" aliases added that warn and forward to new view-based accessors.
  • Tests

    • Added/updated tests for empty-case behavior, structured dtypes, zero-copy semantics, and naming conventions.
  • Documentation

    • Examples and docs updated to use the new view-based API.

timosachsenberg and others added 19 commits March 9, 2026 10:28
- Use &self[0] instead of self.data() (MSChromatogram/Mobilogram
  inherit privately from std::vector, data() not public)
- Use nb::dict with operator[] instead of constructor kwargs
  (nanobind dict doesn't support kwargs in constructor)
- Handle empty containers by returning np.empty(0, dtype)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
All 6 OpenSwath _mv methods (OSBinaryDataArray.get_data_mv,
OSSpectrum.get_mz_array_mv/get_intensity_array_mv/get_drift_time_array_mv,
OSChromatogram.get_time_array_mv/get_intensity_array_mv) now return None
when called on empty data, matching the convention used by kernel types
(FloatDataArray, IntegerDataArray).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…+ binding

Unifies zero-copy API: MSSpectrum now implements get_peaks_struct in C++
like MSChromatogram and Mobilogram. Also fixes missing empty guard in
get_peaks_view. Removes the Python addon that wrapped get_peaks_view.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Adds comprehensive tests validating the zero-copy API naming conventions:
- _mv methods return None on empty, typed ndarray when populated
- _struct methods return empty structured array on empty, named fields when populated
- No public _view/_as_view methods remain (convention drift guard)
- Both _mv and _struct views support writeback to C++ objects

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…inding)

The upstream develop branch added a Python addon for Mobilogram.get_peaks_struct
that calls get_peaks_struct_mv. Our C++ binding provides get_peaks_struct directly,
making the addon redundant and conflicting.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…Peak1D

- Fix Mobilogram docstring referencing old get_peaks_struct_mv name
- Add static_assert(sizeof(Peak1D) == 16) matching ChromatogramPeak and MobilityPeak1D

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Chromatogram/peak intensity typedefs modernized; ChromatogramPeak::IntensityType changed to float and call sites cast accordingly. pyOpenMS bindings and addons migrated mv → view naming, switched intensity buffers to float32, added zero-copy structured/byte views and ABI/static_assert guards; tests and deprecated aliases updated.

Changes

Cohort / File(s) Summary
Peak headers
src/openms/include/OpenMS/KERNEL/ChromatogramPeak.h, src/openms/include/OpenMS/KERNEL/Peak2D.h, src/openms/include/OpenMS/KERNEL/MobilityPeak2D.h
Modernized typedef → using; changed ChromatogramPeak::IntensityType to float; Position/Coordinate aliases updated.
C++ call sites
src/openms/source/FEATUREFINDER/FeatureFinderMultiplexAlgorithm.cpp, src/openms/source/FORMAT/ChromeleonFile.cpp, src/openms_gui/source/VISUAL/LayerData1DChrom.cpp
Added explicit static_cast<ChromatogramPeak::IntensityType> when constructing peaks to match new float intensity type.
pyOpenMS bindings (core)
src/pyOpenMS/bindings/.../bind_chromatogram.cpp, .../bind_kernel.cpp, .../bind_spectrum.cpp, .../bind_analysis.cpp, .../bind_datastructures.cpp
Switched intensity buffers to float32; get_peaks now returns (rt: float64, intensity: float32); added _get_peaks_view (raw AoS bytes) and get_peaks_struct (zero-copy structured dtype); added ABI/static_assert guards; enforced C-contiguous arrays; renamed *_mv → *_view and handle empty-case views.
pyOpenMS Python addons & deprecations
src/pyOpenMS/pyopenms/addons/mobilogram.py, src/pyOpenMS/pyopenms/addons/msspectrum.py, src/pyOpenMS/pyopenms/addons/deprecated_mv_aliases.py
Removed some old structured addon helpers for mobilogram/MSSpectrum; added deprecated_mv_aliases creating _mv wrappers that emit DeprecationWarning and delegate to new *_view methods.
pyOpenMS tests & benchmarks
src/pyOpenMS/tests/*, src/pyOpenMS/tests/unittests/*, src/pyOpenMS/tests/benchmark_pyopenms.py
Updated tests/benchmarks to new *_view names; added tests for empty-view behavior, structured-array dtypes (mz/rt float64, intensity float32), zero-copy writeback, and naming conventions.
C++ tests / ABI guards
src/tests/class_tests/openms/source/ChromatogramPeak_test.cpp
Added includes and static_asserts to ensure ChromatogramPeak::IntensityType matches Peak1D/Peak2D intensity types for ABI/zero-copy expectations.
Test resource outputs
src/tests/topp/*.featureXML
Data-only updates: numeric formatting/rounding and ID normalizations in featureXML test resources (no API changes).

Sequence Diagram(s)

sequenceDiagram
    participant Py as Python caller
    participant Bind as pybind binding
    participant Cpp as C++ container
    participant NumPy as NumPy

    Py->>Bind: call get_peaks_struct() or _get_peaks_view()
    alt get_peaks_struct
        Bind->>Cpp: request raw pointer, length, field offsets (mz/rt: float64, intensity: float32)
        Cpp-->>Bind: return pointer + byte length
        Bind->>NumPy: construct structured dtype and call frombuffer(pointer, dtype)
        NumPy-->>Py: return zero-copy structured ndarray (lifetime tied to owner)
    else _get_peaks_view
        Bind->>Cpp: request raw pointer and length (or nullptr if empty)
        Cpp-->>Bind: return pointer (or nullptr)
        Bind->>NumPy: create uint8 ndarray view/frombuffer with owner capsule or return empty view
        NumPy-->>Py: return raw byte ndarray or empty view
    end
Loading

Possibly related PRs

Suggested reviewers

  • poshul
  • jpfeuffer

Poem

🐇
I hop through headers, light and fleet,
Floats beneath my tiny feet.
Views of bytes and structs align,
From C++ fields to NumPy fine.
I nibble warnings, leave code neat. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 49.18% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main changes: fixing ChromatogramPeak's IntensityType consistency (from double to float) and unifying zero-copy API conventions across peak types.
Linked Issues check ✅ Passed The PR comprehensively addresses the primary objective in #3379: changing ChromatogramPeak::IntensityType from double to float to match other peak types, fixing narrowing-conversion warnings, propagating changes through consumers and bindings, and enforcing consistency with static_assert checks.
Out of Scope Changes check ✅ Passed All changes appear directly related to the stated objectives: type alias modernization (typedef to using), narrowing-conversion fixes, zero-copy API naming consistency (mv/struct suffixes), empty-guard implementations, and supporting test/documentation updates. No unrelated refactoring detected.

✏️ 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
  • Commit unit tests in branch feature/zero-copy-api-unification

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: 3

Caution

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

⚠️ Outside diff range comments (1)
src/pyOpenMS/bindings/bind_spectrum.cpp (1)

168-184: ⚠️ Potential issue | 🟠 Major

Inconsistent ndarray owner in _get_peaks_view(); use explicit Python object reference.

This method returns an nb::ndarray pointing into self.data() with nb::handle() as owner. However, get_peaks_struct() in the same file uses nb::find(self) for the same pattern, and get_drift_time_array_mv() uses the self_obj approach you propose. Passing nb::handle() bypasses explicit lifetime binding to the parent; use the nb::object self_obj capture pattern to ensure the ndarray holds a reference to self across the garbage collection boundary.

Proposed fix
-        .def("_get_peaks_view", [](OpenMS::MSSpectrum& self) {
+        .def("_get_peaks_view", [](nb::object self_obj) {
+            auto& self = nb::cast<OpenMS::MSSpectrum&>(self_obj);
             // Cast to a raw byte pointer
             uint8_t* data_ptr = self.empty() ? nullptr : reinterpret_cast<uint8_t*>(self.data());
@@
             return nb::ndarray<nb::numpy, uint8_t, nb::c_contig>(
                 data_ptr,
                 1,
                 shape,
-                nb::handle()
+                self_obj
             );
         },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_spectrum.cpp` around lines 168 - 184, The lambda
for _get_peaks_view returns an nb::ndarray whose owner is nb::handle(), which
does not tie the array lifetime to the MSSpectrum instance; change the lambda to
capture an explicit Python object owner (e.g. create nb::object self_obj =
nb::find(self) or nb::cast(self) and capture it by value) and pass that object
as the ndarray owner instead of nb::handle(); mirror the pattern used in
get_peaks_struct()/get_drift_time_array_mv so the returned ndarray holds a
reference to self and prevents premature GC of self.data().
🧹 Nitpick comments (5)
src/openms/include/OpenMS/KERNEL/ChromatogramPeak.h (1)

38-42: Route the public floating-point aliases through Types.h.

This change still hard-codes float and double in a public header. Please use the corresponding OpenMS primitive aliases from OpenMS/CONCEPT/Types.h so the precision choice stays centralized and platform-independent.

As per coding guidelines, "Use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead of raw C++ types for platform-independent code."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/include/OpenMS/KERNEL/ChromatogramPeak.h` around lines 38 - 42,
The public typedefs IntensityType and CoordinateType currently hard-code raw C++
types; include OpenMS/CONCEPT/Types.h and replace the aliases to use the OpenMS
primitive aliases instead (e.g., change "using IntensityType = float;" to use
the OpenMS float alias and "using CoordinateType = double;" to use the OpenMS
double alias), leaving PositionType (DPosition<1>) unchanged; update the
includes at the top to `#include` "OpenMS/CONCEPT/Types.h" and ensure
IntensityType and CoordinateType reference the corresponding symbols from that
header.
src/openms/include/OpenMS/KERNEL/Peak2D.h (1)

37-39: Prefer OpenMS scalar aliases in these public typedefs.

While touching this API surface, please switch IntensityType / CoordinateType to the matching aliases from OpenMS/CONCEPT/Types.h instead of raw float / double so this header stays aligned with the portability convention.

As per coding guidelines: Use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead of raw C++ types for platform-independent code.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/include/OpenMS/KERNEL/Peak2D.h` around lines 37 - 39, Replace the
raw built-in types with the OpenMS scalar aliases: add an `#include` for
"OpenMS/CONCEPT/Types.h" and change the two typedefs so IntensityType and
CoordinateType use the corresponding aliases from that header (keep the public
alias names IntensityType and CoordinateType in Peak2D.h but assign them to the
Types.h aliases), ensuring the header compiles with the new include.
src/pyOpenMS/bindings/bind_spectrum.cpp (1)

50-52: The new ABI guard only checks size, not layout.

get_peaks_struct() hardcodes mz at offset 0, intensity at offset 8, and itemsize = 16, but the new static_assert only validates total size. A future member reorder or padding change could still pass the build and silently corrupt the structured view. Please add explicit layout checks next to this assert, or derive the dtype metadata from a shared layout definition.

Also applies to: 186-208

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_spectrum.cpp` around lines 50 - 52, The current
ABI guard only checks sizeof(OpenMS::Peak1D) but get_peaks_struct() hardcodes
field offsets (mz at 0, intensity at 8) and itemsize=16, so add explicit layout
assertions to prevent silent breakage: in the same spot as the static_assert for
sizeof(Peak1D) add static_asserts (or constexpr checks) that
offsetof(OpenMS::Peak1D, mz) == 0, offsetof(OpenMS::Peak1D, intensity) == 8 and
that alignof/OpenMS layout yields itemsize==16; alternatively refactor
get_peaks_struct() to derive dtype metadata programmatically from
offsetof/sizeof/alignof of Peak1D so the structured-array dtype is always
generated from the actual C++ layout rather than hardcoded offsets.
src/openms/include/OpenMS/KERNEL/MobilityPeak2D.h (1)

36-38: Prefer OpenMS scalar aliases in these public typedefs.

Same note here: since this header already depends on OpenMS/CONCEPT/Types.h, it would be better to keep IntensityType / CoordinateType on the project-defined primitive aliases instead of raw float / double.

As per coding guidelines: Use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead of raw C++ types for platform-independent code.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/include/OpenMS/KERNEL/MobilityPeak2D.h` around lines 36 - 38, The
public typedefs in MobilityPeak2D.h should use the project-defined scalar
aliases from OpenMS/CONCEPT/Types.h instead of raw float/double; replace the
current IntensityType = float and CoordinateType = double with the corresponding
OpenMS primitive aliases (i.e., swap the raw types for the OpenMS floating-point
alias for intensities and the OpenMS coordinate/precision alias for coordinates)
so the class uses platform-independent types; keep the typedef names
IntensityType and CoordinateType but source their underlying types from Types.h.
src/pyOpenMS/bindings/bind_chromatogram.cpp (1)

45-46: Bind against the peak aliases instead of repeating the ABI as literals.

The new paths now spell the ChromatogramPeak contract in several places (double, float, offsets 0/8, itemsize 16, and size_t). The single sizeof(OpenMS::ChromatogramPeak) == 16 check will not catch alias drift or a layout change that still keeps the total size at 16 bytes, so the Python dtype/view can silently diverge from the C++ type. Please centralize this through OpenMS::ChromatogramPeak::{CoordinateType, IntensityType, PositionType} plus OpenMS::Size, and strengthen the static assertions around the struct-view ABI.

Possible direction
+using RtType = OpenMS::ChromatogramPeak::CoordinateType;
+using IntensityType = OpenMS::ChromatogramPeak::IntensityType;
+using PeakSizeType = OpenMS::Size;
+
-const size_t rt_bytes = n * sizeof(double);
-const size_t int_bytes = n * sizeof(float);
+const PeakSizeType rt_bytes = n * sizeof(RtType);
+const PeakSizeType int_bytes = n * sizeof(IntensityType);
 ...
-auto rt_arr = as_numpy_array<double>(rt_obj);
-auto int_arr = as_numpy_array<float>(int_obj);
+auto rt_arr = as_numpy_array<RtType>(rt_obj);
+auto int_arr = as_numpy_array<IntensityType>(int_obj);

Based on learnings, "Use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead of raw C++ types for platform-independent code."

Also applies to: 131-142, 166-172, 194-205

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_chromatogram.cpp` around lines 45 - 46, Replace
the brittle literal ABI checks with assertions that reference the OpenMS
aliases: use OpenMS::ChromatogramPeak::CoordinateType, ::IntensityType and
::PositionType and OpenMS::Size in your static_asserts (e.g.
std::is_same_v<CoordinateType,double> and std::is_same_v<IntensityType,float>
where appropriate), assert sizeof(OpenMS::ChromatogramPeak) equals
sizeof(CoordinateType)+sizeof(IntensityType) (and/or uses alignof checks) and
replace hardcoded offset/itemsize literals with offsetof(...) checks that use
the actual member names and the alias types; update every assertion occurrences
(the existing sizeof(...) == 16 checks and the other literal checks mentioned)
to reference these aliases so the Python dtype/view follows the canonical OpenMS
types rather than raw literals.
🤖 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_chromatogram.cpp`:
- Around line 193-205: The lambda bound to set_peaks reads raw pointers from
NumPy arrays but doesn’t guarantee C-contiguity; change the conversion to
require contiguous arrays and force contiguity before taking pointers by using
nb::c_contig in the ndarray signature and calling NumPy’s ascontiguousarray on
the incoming objects (i.e., ensure you convert rt_obj/int_obj via
np.ascontiguousarray and then use as_numpy_array<double, nb::c_contig> and
as_numpy_array<float, nb::c_contig>) so that OpenMS::MSChromatogram element
access and pointer arithmetic are safe.

In `@src/pyOpenMS/bindings/bind_datastructures.cpp`:
- Around line 650-658: The change replaced the public method name; restore a
deprecated alias by adding a forwarding definition for get_matrix_as_view that
calls the new get_matrix_mv implementation and emits a deprecation warning;
specifically, add a .def("get_matrix_as_view", [](nb::object self_obj) { issue a
Python deprecation warning (e.g., PyErr_WarnEx or
nb::module::import("warnings").attr("warn")) then return the same nb::ndarray
result from get_matrix_mv's lambda logic ), so existing callers of
get_matrix_as_view continue to work while guiding them to use get_matrix_mv.

In `@src/pyOpenMS/bindings/bind_kernel.cpp`:
- Around line 1644-1655: The _get_peaks_view lambda in bind_kernel.cpp currently
constructs the ndarray with nb::handle() as the owner which is inconsistent with
get_peaks_struct() and can allow the view to outlive the Mobilogram; update the
ndarray constructor to use nb::find(self) as the owner (i.e. replace
nb::handle() with nb::find(self)) so the returned ndarray correctly registers
the OpenMS::Mobilogram lifetime, and apply the same change to the analogous
_get_peaks_view implementations in bind_spectrum.cpp and bind_chromatogram.cpp;
keep nb::rv_policy::reference_internal unchanged.

---

Outside diff comments:
In `@src/pyOpenMS/bindings/bind_spectrum.cpp`:
- Around line 168-184: The lambda for _get_peaks_view returns an nb::ndarray
whose owner is nb::handle(), which does not tie the array lifetime to the
MSSpectrum instance; change the lambda to capture an explicit Python object
owner (e.g. create nb::object self_obj = nb::find(self) or nb::cast(self) and
capture it by value) and pass that object as the ndarray owner instead of
nb::handle(); mirror the pattern used in
get_peaks_struct()/get_drift_time_array_mv so the returned ndarray holds a
reference to self and prevents premature GC of self.data().

---

Nitpick comments:
In `@src/openms/include/OpenMS/KERNEL/ChromatogramPeak.h`:
- Around line 38-42: The public typedefs IntensityType and CoordinateType
currently hard-code raw C++ types; include OpenMS/CONCEPT/Types.h and replace
the aliases to use the OpenMS primitive aliases instead (e.g., change "using
IntensityType = float;" to use the OpenMS float alias and "using CoordinateType
= double;" to use the OpenMS double alias), leaving PositionType (DPosition<1>)
unchanged; update the includes at the top to `#include` "OpenMS/CONCEPT/Types.h"
and ensure IntensityType and CoordinateType reference the corresponding symbols
from that header.

In `@src/openms/include/OpenMS/KERNEL/MobilityPeak2D.h`:
- Around line 36-38: The public typedefs in MobilityPeak2D.h should use the
project-defined scalar aliases from OpenMS/CONCEPT/Types.h instead of raw
float/double; replace the current IntensityType = float and CoordinateType =
double with the corresponding OpenMS primitive aliases (i.e., swap the raw types
for the OpenMS floating-point alias for intensities and the OpenMS
coordinate/precision alias for coordinates) so the class uses
platform-independent types; keep the typedef names IntensityType and
CoordinateType but source their underlying types from Types.h.

In `@src/openms/include/OpenMS/KERNEL/Peak2D.h`:
- Around line 37-39: Replace the raw built-in types with the OpenMS scalar
aliases: add an `#include` for "OpenMS/CONCEPT/Types.h" and change the two
typedefs so IntensityType and CoordinateType use the corresponding aliases from
that header (keep the public alias names IntensityType and CoordinateType in
Peak2D.h but assign them to the Types.h aliases), ensuring the header compiles
with the new include.

In `@src/pyOpenMS/bindings/bind_chromatogram.cpp`:
- Around line 45-46: Replace the brittle literal ABI checks with assertions that
reference the OpenMS aliases: use OpenMS::ChromatogramPeak::CoordinateType,
::IntensityType and ::PositionType and OpenMS::Size in your static_asserts (e.g.
std::is_same_v<CoordinateType,double> and std::is_same_v<IntensityType,float>
where appropriate), assert sizeof(OpenMS::ChromatogramPeak) equals
sizeof(CoordinateType)+sizeof(IntensityType) (and/or uses alignof checks) and
replace hardcoded offset/itemsize literals with offsetof(...) checks that use
the actual member names and the alias types; update every assertion occurrences
(the existing sizeof(...) == 16 checks and the other literal checks mentioned)
to reference these aliases so the Python dtype/view follows the canonical OpenMS
types rather than raw literals.

In `@src/pyOpenMS/bindings/bind_spectrum.cpp`:
- Around line 50-52: The current ABI guard only checks sizeof(OpenMS::Peak1D)
but get_peaks_struct() hardcodes field offsets (mz at 0, intensity at 8) and
itemsize=16, so add explicit layout assertions to prevent silent breakage: in
the same spot as the static_assert for sizeof(Peak1D) add static_asserts (or
constexpr checks) that offsetof(OpenMS::Peak1D, mz) == 0,
offsetof(OpenMS::Peak1D, intensity) == 8 and that alignof/OpenMS layout yields
itemsize==16; alternatively refactor get_peaks_struct() to derive dtype metadata
programmatically from offsetof/sizeof/alignof of Peak1D so the structured-array
dtype is always generated from the actual C++ layout rather than hardcoded
offsets.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b080daae-0535-46f4-bf41-b5f3128fa418

📥 Commits

Reviewing files that changed from the base of the PR and between 8317056 and b6b94e0.

📒 Files selected for processing (21)
  • src/openms/include/OpenMS/KERNEL/ChromatogramPeak.h
  • src/openms/include/OpenMS/KERNEL/MobilityPeak2D.h
  • src/openms/include/OpenMS/KERNEL/Peak2D.h
  • src/openms/source/FEATUREFINDER/FeatureFinderMultiplexAlgorithm.cpp
  • src/openms/source/FORMAT/ChromeleonFile.cpp
  • src/openms_gui/source/VISUAL/LayerData1DChrom.cpp
  • src/pyOpenMS/bindings/bind_analysis.cpp
  • src/pyOpenMS/bindings/bind_chromatogram.cpp
  • src/pyOpenMS/bindings/bind_datastructures.cpp
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/bindings/bind_spectrum.cpp
  • src/pyOpenMS/pyopenms/addons/mobilogram.py
  • src/pyOpenMS/pyopenms/addons/msspectrum.py
  • src/pyOpenMS/tests/test_matrix_zerocopy.py
  • src/pyOpenMS/tests/unittests/test000.py
  • src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py
  • src/pyOpenMS/tests/unittests/test_mobilogram_struct_view.py
  • src/pyOpenMS/tests/unittests/test_mschromatogram_struct_view.py
  • src/pyOpenMS/tests/unittests/test_spectrum_zerocopy.py
  • src/pyOpenMS/tests/unittests/test_zerocopy_conventions.py
  • src/tests/class_tests/openms/source/ChromatogramPeak_test.cpp
💤 Files with no reviewable changes (2)
  • src/pyOpenMS/pyopenms/addons/mobilogram.py
  • src/pyOpenMS/pyopenms/addons/msspectrum.py

Comment thread src/pyOpenMS/bindings/bind_kernel.cpp Resolved
timosachsenberg and others added 5 commits March 9, 2026 12:10
Update expected output for OpenSwathWorkflow tests 17, 17_b, 21, and 23
to reflect minor numerical differences from ChromatogramPeak intensity
type change (double → float).

Co-Authored-By: Claude Opus 4.6 <[email protected]>

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

♻️ Duplicate comments (1)
src/pyOpenMS/bindings/bind_kernel.cpp (1)

1644-1655: ⚠️ Potential issue | 🟠 Major

Bind _get_peaks_view() to the parent Mobilogram.

Line 1651 still uses an empty owner handle, so the returned ndarray can outlive self and end up pointing at freed storage. The structured variant right below already avoids this by registering the parent object.

Suggested fix
         return nb::ndarray<nb::numpy, uint8_t, nb::c_contig>(
             data_ptr,
             1,
             shape,
-            nb::handle()
+            nb::find(self)
         );
In nanobind, when constructing `nb::ndarray` from a raw pointer, does `nb::rv_policy::reference_internal` alone keep the parent object alive, or should the ndarray owner handle be set explicitly (for example with `nb::find(self)`) to tie the array lifetime to the parent Python object?
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_kernel.cpp` around lines 1644 - 1655, The
_get_peaks_view binding creates an nb::ndarray from a raw pointer but uses an
empty owner handle so the array can outlive the Mobilogram; change the ndarray
construction to pass the Mobilogram parent as the owner (use nb::find(self) or
equivalent) instead of nb::handle(), keeping the
nb::rv_policy::reference_internal policy, so the returned ndarray lifetime is
tied to the Mobilogram instance (update the lambda in _get_peaks_view that
constructs nb::ndarray<...> to use nb::find(self) as the owner handle).
🧹 Nitpick comments (1)
src/pyOpenMS/bindings/bind_kernel.cpp (1)

1657-1678: Derive the structured dtype layout from MobilityPeak1D instead of hard-coding 8 and 16.

Lines 1664-1665 duplicate ABI constants. The size assert only protects one of them, so a future layout tweak can silently desync the dtype description from the actual buffer.

Suggested refactor
+                constexpr auto position_bytes = sizeof(OpenMS::MobilityPeak1D::PositionType);
                 dtype_dict["names"] = nb::make_tuple("mobility", "intensity");
                 dtype_dict["formats"] = nb::make_tuple(np.attr("float64"), np.attr("float32"));
-                dtype_dict["offsets"] = nb::make_tuple(0, 8);
-                dtype_dict["itemsize"] = 16;
+                dtype_dict["offsets"] = nb::make_tuple(0, position_bytes);
+                dtype_dict["itemsize"] = sizeof(OpenMS::MobilityPeak1D);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_kernel.cpp` around lines 1657 - 1678, The dtype
offsets and itemsize in the get_peaks_struct lambda are hard-coded (8 and 16)
and can drift from the actual OpenMS::MobilityPeak1D layout; change the code to
compute those values from the struct instead: use sizeof(OpenMS::MobilityPeak1D)
for "itemsize", use offsetof(OpenMS::MobilityPeak1D, intensity) (and
offsetof(..., mobility) or 0) for the "offsets" tuple, and compute the
byte_shape as n * sizeof(OpenMS::MobilityPeak1D); also keep or add a
static_assert that sizeof(members) and type sizes match the expected
float64/float32 mapping to prevent ABI drift. Update the dtype_dict construction
in the get_peaks_struct lambda (the lambda bound to
OpenMS::Mobilogram::get_peaks_struct) to derive these values rather than using
literals.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/pyOpenMS/bindings/bind_kernel.cpp`:
- Around line 1644-1655: The _get_peaks_view binding creates an nb::ndarray from
a raw pointer but uses an empty owner handle so the array can outlive the
Mobilogram; change the ndarray construction to pass the Mobilogram parent as the
owner (use nb::find(self) or equivalent) instead of nb::handle(), keeping the
nb::rv_policy::reference_internal policy, so the returned ndarray lifetime is
tied to the Mobilogram instance (update the lambda in _get_peaks_view that
constructs nb::ndarray<...> to use nb::find(self) as the owner handle).

---

Nitpick comments:
In `@src/pyOpenMS/bindings/bind_kernel.cpp`:
- Around line 1657-1678: The dtype offsets and itemsize in the get_peaks_struct
lambda are hard-coded (8 and 16) and can drift from the actual
OpenMS::MobilityPeak1D layout; change the code to compute those values from the
struct instead: use sizeof(OpenMS::MobilityPeak1D) for "itemsize", use
offsetof(OpenMS::MobilityPeak1D, intensity) (and offsetof(..., mobility) or 0)
for the "offsets" tuple, and compute the byte_shape as n *
sizeof(OpenMS::MobilityPeak1D); also keep or add a static_assert that
sizeof(members) and type sizes match the expected float64/float32 mapping to
prevent ABI drift. Update the dtype_dict construction in the get_peaks_struct
lambda (the lambda bound to OpenMS::Mobilogram::get_peaks_struct) to derive
these values rather than using literals.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 009d23b3-8a7b-40ff-8c83-cd56499c9cd9

📥 Commits

Reviewing files that changed from the base of the PR and between 4b39fb2 and 45fd881.

📒 Files selected for processing (11)
  • src/pyOpenMS/bindings/bind_analysis.cpp
  • src/pyOpenMS/bindings/bind_datastructures.cpp
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/bindings/bind_spectrum.cpp
  • src/pyOpenMS/pyopenms/addons/deprecated_mv_aliases.py
  • src/pyOpenMS/tests/benchmark_pyopenms.py
  • src/pyOpenMS/tests/test_matrix_zerocopy.py
  • src/pyOpenMS/tests/unittests/test000.py
  • src/pyOpenMS/tests/unittests/test_MSSpectrum.py
  • src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py
  • src/pyOpenMS/tests/unittests/test_zerocopy_conventions.py
✅ Files skipped from review due to trivial changes (1)
  • src/pyOpenMS/tests/unittests/test_zerocopy_conventions.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/pyOpenMS/tests/test_matrix_zerocopy.py
  • src/pyOpenMS/bindings/bind_datastructures.cpp
  • src/pyOpenMS/tests/unittests/test000.py

- Enforce C-contiguity in as_numpy_array helper (nb::c_contig +
  ascontiguousarray) to prevent silent data corruption from strided arrays
- Add get_matrix_as_view deprecated alias for backward compatibility
- Use self_obj as ndarray owner in _get_peaks_view (all 3 binding files)
- Add type-checking static_asserts (is_standard_layout, CoordinateType,
  IntensityType) alongside sizeof checks
- Derive structured dtype offsets from sizeof(PositionType) instead of
  hardcoded literals
- Harmonize docstrings ("zero-copy writable view" instead of "fast but unsafe")
- Update docs (README.md, performance.rst) to use _view naming
- Extend convention test to cover OpenSwath types

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@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

Caution

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

⚠️ Outside diff range comments (1)
src/pyOpenMS/bindings/bind_spectrum.cpp (1)

338-352: 🛠️ Refactor suggestion | 🟠 Major

Resolve the drift-time view via getIMData().

This path still rediscovers the ion-mobility array by matching "Ion Mobility" labels inside FloatDataArrays. Please use the stored index from self.getIMData().first instead, so the view follows OpenMS' canonical IM mapping rather than metadata naming. The copy-returning get_drift_time_array() path should stay aligned too.

Suggested fix
-            auto& fda = self.getFloatDataArrays();
-            for (auto& arr : fda) {
-                if (arr.getName() == "Ion Mobility" || arr.getMetaValue("name") == "Ion Mobility") {
-                    if (arr.empty()) return std::nullopt;
-                    return nb::ndarray<nb::numpy, float, nb::ndim<1>>(
-                        arr.data(), {arr.size()}, self_obj
-                    );
-                }
-            }
-            return std::nullopt;
+            const auto im_index = self.getIMData().first;
+            auto& fda = self.getFloatDataArrays();
+            if (im_index >= fda.size() || fda[im_index].empty()) {
+                return std::nullopt;
+            }
+            auto& arr = fda[im_index];
+            return nb::ndarray<nb::numpy, float, nb::ndim<1>>(
+                arr.data(), {arr.size()}, self_obj
+            );
Based on learnings: in OpenMS, the proper way to access ion mobility data in `MSSpectrum` is to use the `getIMData()` method, which returns the position of the ion mobility data in `FloatDataArrays`.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_spectrum.cpp` around lines 338 - 352, The current
get_drift_time_array_view implementation rediscovers the IM array by name;
instead call self.getIMData() to obtain the canonical index (auto im_pair =
self.getIMData(); use im_pair.first), verify containsIMData()/that index is
valid, then fetch the FloatDataArrays entry by that index (auto& arr =
self.getFloatDataArrays()[index]), check arr.empty(), and return the zero-copy
nb::ndarray backed by arr.data() and arr.size() with self_obj as parent; keep
the behavior consistent with the copy-returning get_drift_time_array() path.
🧹 Nitpick comments (3)
src/pyOpenMS/bindings/bind_kernel.cpp (2)

1468-1475: Guard the zero-copy integer view against OpenMS::Int width drift.

This view aliases self.data() as int32_t*, but the container stores OpenMS::Int. That is only safe if OpenMS::Int is guaranteed 32-bit on every supported platform. Please either bind OpenMS::Int directly or add a compile-time width check next to the other ABI guards.

As per coding guidelines, "Use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead of raw C++ types for platform-independent code."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_kernel.cpp` around lines 1468 - 1475, The
zero-copy view in get_data_view currently casts IntegerDataArray::data() to
int32_t*, which is unsafe if OpenMS::Int isn't 32-bit; update the binding to
either use OpenMS::Int as the ndarray element type (so the view matches
IntegerDataArray) or add a compile-time ABI guard next to the other checks that
static_asserts sizeof(OpenMS::Int) == 4 (and conditionally select int32_t view
only when that holds), referencing the get_data_view lambda and
OpenMS::DataArrays::IntegerDataArray to locate the code to change.

111-119: Add a matching ChromatogramPeak type guard here.

The binding now hardcodes float for ChromatogramPeak, but only MobilityPeak1D is asserted at module init. A future header drift would still compile via implicit conversion and silently desync the Python signature from the C++ type.

Possible guard
+    static_assert(std::is_same_v<OpenMS::ChromatogramPeak::CoordinateType, double>,
+                  "ChromatogramPeak::CoordinateType must be double");
+    static_assert(std::is_same_v<OpenMS::ChromatogramPeak::IntensityType, float>,
+                  "ChromatogramPeak::IntensityType must be float");

Also applies to: 195-197

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_kernel.cpp` around lines 111 - 119, Add the same
ABI/type guards for OpenMS::ChromatogramPeak that are present for
OpenMS::MobilityPeak1D: insert static_asserts checking
std::is_standard_layout_v<OpenMS::ChromatogramPeak>, that
ChromatogramPeak::CoordinateType matches the double dtype used by the bindings,
that ChromatogramPeak::IntensityType matches float (the hardcoded dtype), and a
size sanity-check (matching the byte-size expected by your zero-copy struct
view). Place these checks alongside the existing MobilityPeak1D asserts (where
get_peaks_struct dtype is determined) and duplicate them at the second location
referenced (the block around the other set of asserts, e.g., the area referenced
by “also applies to: 195-197”).
src/pyOpenMS/bindings/bind_chromatogram.cpp (1)

28-41: Consider hoisting as_numpy_array() into shared binding utilities.

This exact coercion helper now exists in multiple peak-binding modules, so the next contiguity or dtype fix will need to stay in sync again. Moving it into binding_utils.h would keep the zero-copy input contract consistent.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_chromatogram.cpp` around lines 28 - 41, The helper
template as_numpy_array<T>(nb::object) is duplicated across modules; move this
exact template into a common header (e.g., binding_utils.h) and replace the
local definition in bind_chromatogram.cpp with an `#include` of that header and
use the shared as_numpy_array symbol; ensure the header exposes the same
signature and behavior (type-selecting float32/float64 via std::is_same_v,
calling numpy.ascontiguousarray, using nb::try_cast and throwing the same
runtime_error message), update any includes/usings so bind_chromatogram.cpp
compiles without its local copy, and remove the duplicate implementations from
other peak-binding modules so they all include binding_utils.h instead.
🤖 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 1366-1375: Rename the exported method from get_data_view to
get_data_mv to follow the new zero-copy naming convention in bind_kernel.cpp
(the lambda that returns nb::ndarray<...> from
OpenMS::DataArrays::FloatDataArray / IntDataArray); update both occurrences
(around the FloatDataArray and IntDataArray bindings) to .def("get_data_mv",
...) and, if backward compatibility is required, add a thin deprecated alias
.def("get_data_view", [](nb::object self_obj){ /* forward to get_data_mv or call
same lambda but emit deprecation warning */ }) so callers still work while
signaling deprecation.

---

Outside diff comments:
In `@src/pyOpenMS/bindings/bind_spectrum.cpp`:
- Around line 338-352: The current get_drift_time_array_view implementation
rediscovers the IM array by name; instead call self.getIMData() to obtain the
canonical index (auto im_pair = self.getIMData(); use im_pair.first), verify
containsIMData()/that index is valid, then fetch the FloatDataArrays entry by
that index (auto& arr = self.getFloatDataArrays()[index]), check arr.empty(),
and return the zero-copy nb::ndarray backed by arr.data() and arr.size() with
self_obj as parent; keep the behavior consistent with the copy-returning
get_drift_time_array() path.

---

Nitpick comments:
In `@src/pyOpenMS/bindings/bind_chromatogram.cpp`:
- Around line 28-41: The helper template as_numpy_array<T>(nb::object) is
duplicated across modules; move this exact template into a common header (e.g.,
binding_utils.h) and replace the local definition in bind_chromatogram.cpp with
an `#include` of that header and use the shared as_numpy_array symbol; ensure the
header exposes the same signature and behavior (type-selecting float32/float64
via std::is_same_v, calling numpy.ascontiguousarray, using nb::try_cast and
throwing the same runtime_error message), update any includes/usings so
bind_chromatogram.cpp compiles without its local copy, and remove the duplicate
implementations from other peak-binding modules so they all include
binding_utils.h instead.

In `@src/pyOpenMS/bindings/bind_kernel.cpp`:
- Around line 1468-1475: The zero-copy view in get_data_view currently casts
IntegerDataArray::data() to int32_t*, which is unsafe if OpenMS::Int isn't
32-bit; update the binding to either use OpenMS::Int as the ndarray element type
(so the view matches IntegerDataArray) or add a compile-time ABI guard next to
the other checks that static_asserts sizeof(OpenMS::Int) == 4 (and conditionally
select int32_t view only when that holds), referencing the get_data_view lambda
and OpenMS::DataArrays::IntegerDataArray to locate the code to change.
- Around line 111-119: Add the same ABI/type guards for OpenMS::ChromatogramPeak
that are present for OpenMS::MobilityPeak1D: insert static_asserts checking
std::is_standard_layout_v<OpenMS::ChromatogramPeak>, that
ChromatogramPeak::CoordinateType matches the double dtype used by the bindings,
that ChromatogramPeak::IntensityType matches float (the hardcoded dtype), and a
size sanity-check (matching the byte-size expected by your zero-copy struct
view). Place these checks alongside the existing MobilityPeak1D asserts (where
get_peaks_struct dtype is determined) and duplicate them at the second location
referenced (the block around the other set of asserts, e.g., the area referenced
by “also applies to: 195-197”).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5901c588-77b7-4bbf-a9f2-e38b336137a9

📥 Commits

Reviewing files that changed from the base of the PR and between 45fd881 and 3960eef.

📒 Files selected for processing (7)
  • src/pyOpenMS/README.md
  • src/pyOpenMS/bindings/bind_chromatogram.cpp
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/bindings/bind_spectrum.cpp
  • src/pyOpenMS/performance.rst
  • src/pyOpenMS/pyopenms/addons/deprecated_mv_aliases.py
  • src/pyOpenMS/tests/unittests/test_zerocopy_conventions.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/pyOpenMS/tests/unittests/test_zerocopy_conventions.py

Comment thread src/pyOpenMS/bindings/bind_kernel.cpp Resolved
… on empty containers

Unify empty-container behavior: all _view methods now return empty numpy
arrays (matching _struct and copy methods) instead of None. This removes
the need for callers to check for None before array operations.

Affected methods: FloatDataArray/IntegerDataArray.get_data_view(),
MatrixDouble.get_matrix_view(), OSBinaryDataArray.get_data_view(),
OSSpectrum.get_mz/intensity/drift_time_array_view(),
OSChromatogram.get_time/intensity_array_view().

Note: MSSpectrum.get_drift_time_array_view() still returns None when no
ion mobility data exists (distinct from "empty container").

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@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

🧹 Nitpick comments (4)
src/pyOpenMS/bindings/bind_kernel.cpp (3)

111-119: Guard the actual intensity field offset, not just size and scalar types.

get_peaks_struct() derives the intensity offset from sizeof(PositionType), but the current ABI asserts never prove that the member actually starts there. If padding is ever introduced between position_ and intensity_, the structured dtype will silently reinterpret the wrong bytes. Please source this offset from a compile-time constant or offsetof defined where MobilityPeak1D’s members are visible.

Also applies to: 1667-1673

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_kernel.cpp` around lines 111 - 119, The ABI guards
currently check sizes and scalar types for OpenMS::MobilityPeak1D but not the
actual offset of the intensity member; update the assertions so get_peaks_struct
uses a compile-time offset (e.g. offsetof(OpenMS::MobilityPeak1D, intensity_) or
a constexpr offset provided where MobilityPeak1D is defined) instead of assuming
sizeof(PositionType) == intensity offset, and add a static_assert that
offsetof(OpenMS::MobilityPeak1D, intensity_) == expected_offset (and similarly
verify offsetof(..., position_) if needed) so the structured dtype and
get_peaks_struct compute the intensity field location safely.

1467-1474: Make the IntegerDataArray NumPy ABI assumption explicit.

int32_t* data_ptr = self.data() only works as a zero-copy view while the container’s value_type is exactly 32-bit. Add a static_assert near the module ABI guards so a future type change breaks clearly instead of turning this into a portability trap.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_kernel.cpp` around lines 1467 - 1474, Add an
explicit compile-time check that OpenMS::DataArrays::IntegerDataArray actually
uses a 32-bit integer so the zero-copy cast to int32_t in the get_data_view
lambda is safe: introduce a static_assert (placed near the module ABI guards /
top of the bindings file) that verifies
sizeof(OpenMS::DataArrays::IntegerDataArray::value_type) == sizeof(int32_t) or
std::is_same_v<... , int32_t>, so any future change to IntegerDataArray’s
value_type fails at compile time rather than silently breaking the NumPy ABI
assumption used by the get_data_view lambda.

94-107: Constrain as_numpy_array() to the dtypes it really supports.

Right now every non-float instantiation falls into the float64 branch and only fails later at try_cast. A compile-time guard will make future misuse fail loudly.

♻️ Suggested change
 template <typename T>
 nb::ndarray<nb::numpy, T, nb::ndim<1>, nb::c_contig> as_numpy_array(nb::object obj) {
+    static_assert(std::is_same_v<T, float> || std::is_same_v<T, double>,
+                  "as_numpy_array only supports float and double");
     nb::ndarray<nb::numpy, T, nb::ndim<1>, nb::c_contig> arr;
     if (nb::try_cast(obj, arr)) return arr;  // already the right type and contiguous — zero-copy
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/bindings/bind_kernel.cpp` around lines 94 - 107, The template
as_numpy_array currently treats every non-float T as float64 and defers failure
to runtime; add a compile-time constraint so only float and double are allowed:
in the as_numpy_array<T> function (or its declaration) add a static_assert (or
enable_if/SFINAE) that T is either float or double, and adjust the dtype
selection to only handle those two types (float -> numpy.float32, double ->
numpy.float64); this will cause invalid instantiations to fail at compile time
instead of producing confusing runtime errors.
src/pyOpenMS/tests/unittests/test_zerocopy_conventions.py (1)

135-159: Add OpenSwath alias coverage to this deprecation test.

This only exercises FloatDataArray.get_data_mv() and MatrixDouble.get_matrix_mv(), but the same PR also renamed the OpenSwath accessors in src/pyOpenMS/bindings/bind_analysis.cpp. If OSBinaryDataArray.get_data_mv(), OSSpectrum.get_*_array_mv(), or OSChromatogram.get_*_array_mv() is missing from src/pyOpenMS/pyopenms/addons/deprecated_mv_aliases.py, this suite will not catch the breakage.

Based on learnings: pyOpenMS zero-copy typed view naming uses *_view, and backward-compatible *_mv methods exist only as deprecated aliases implemented in src/pyOpenMS/pyopenms/addons/deprecated_mv_aliases.py.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/tests/unittests/test_zerocopy_conventions.py` around lines 135 -
159, The test only checks FloatDataArray.get_data_mv() and
MatrixDouble.get_matrix_mv(); extend it to also exercise the OpenSwath aliases
so missing deprecated aliases in deprecated_mv_aliases.py are detected: call
OSBinaryDataArray.get_data_mv(), OSSpectrum.get_<...>_array_mv() (all array
accessors exposed on OSSpectrum), and OSChromatogram.get_<...>_array_mv() inside
warnings.catch_warnings blocks, assert a single DeprecationWarning whose message
mentions the corresponding new *_view name and verify the returned view is not
None and has the expected dtype/shape; use the class names OSBinaryDataArray,
OSSpectrum, and OSChromatogram to locate where to add these checks.
🤖 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_spectrum.cpp`:
- Around line 338-352: The current get_drift_time_array_view uses name-based
search on getFloatDataArrays which can miss IM data; change it to call
containsIMData()/getIMData() to obtain the IM index (call getIMData() on the
MSSpectrum), verify the index is valid (not -1) and use that index into
getFloatDataArrays() to get the FloatDataArray, then create and return the
ndarray view from that array (handling empty() -> nullptr as before); update
get_drift_time_array_view to reference getIMData(), containsIMData(),
getFloatDataArrays(), and the function name get_drift_time_array_view when
making the fix.

---

Nitpick comments:
In `@src/pyOpenMS/bindings/bind_kernel.cpp`:
- Around line 111-119: The ABI guards currently check sizes and scalar types for
OpenMS::MobilityPeak1D but not the actual offset of the intensity member; update
the assertions so get_peaks_struct uses a compile-time offset (e.g.
offsetof(OpenMS::MobilityPeak1D, intensity_) or a constexpr offset provided
where MobilityPeak1D is defined) instead of assuming sizeof(PositionType) ==
intensity offset, and add a static_assert that offsetof(OpenMS::MobilityPeak1D,
intensity_) == expected_offset (and similarly verify offsetof(..., position_) if
needed) so the structured dtype and get_peaks_struct compute the intensity field
location safely.
- Around line 1467-1474: Add an explicit compile-time check that
OpenMS::DataArrays::IntegerDataArray actually uses a 32-bit integer so the
zero-copy cast to int32_t in the get_data_view lambda is safe: introduce a
static_assert (placed near the module ABI guards / top of the bindings file)
that verifies sizeof(OpenMS::DataArrays::IntegerDataArray::value_type) ==
sizeof(int32_t) or std::is_same_v<... , int32_t>, so any future change to
IntegerDataArray’s value_type fails at compile time rather than silently
breaking the NumPy ABI assumption used by the get_data_view lambda.
- Around line 94-107: The template as_numpy_array currently treats every
non-float T as float64 and defers failure to runtime; add a compile-time
constraint so only float and double are allowed: in the as_numpy_array<T>
function (or its declaration) add a static_assert (or enable_if/SFINAE) that T
is either float or double, and adjust the dtype selection to only handle those
two types (float -> numpy.float32, double -> numpy.float64); this will cause
invalid instantiations to fail at compile time instead of producing confusing
runtime errors.

In `@src/pyOpenMS/tests/unittests/test_zerocopy_conventions.py`:
- Around line 135-159: The test only checks FloatDataArray.get_data_mv() and
MatrixDouble.get_matrix_mv(); extend it to also exercise the OpenSwath aliases
so missing deprecated aliases in deprecated_mv_aliases.py are detected: call
OSBinaryDataArray.get_data_mv(), OSSpectrum.get_<...>_array_mv() (all array
accessors exposed on OSSpectrum), and OSChromatogram.get_<...>_array_mv() inside
warnings.catch_warnings blocks, assert a single DeprecationWarning whose message
mentions the corresponding new *_view name and verify the returned view is not
None and has the expected dtype/shape; use the class names OSBinaryDataArray,
OSSpectrum, and OSChromatogram to locate where to add these checks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d53ec7c0-8930-4a72-acf7-65a206721b88

📥 Commits

Reviewing files that changed from the base of the PR and between 3960eef and c973066.

📒 Files selected for processing (7)
  • src/pyOpenMS/bindings/bind_analysis.cpp
  • src/pyOpenMS/bindings/bind_datastructures.cpp
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/bindings/bind_spectrum.cpp
  • src/pyOpenMS/tests/test_matrix_zerocopy.py
  • src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py
  • src/pyOpenMS/tests/unittests/test_zerocopy_conventions.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/pyOpenMS/tests/test_matrix_zerocopy.py

… IM arrays

Replace fragile name-based loop ("Ion Mobility" string matching) in
get_drift_time_array and get_drift_time_array_view with the proper
containsIMData()/getIMData() API which uses CV term hierarchy via
IMDataConverter::getIMUnit() to locate the correct float data array.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@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_spectrum.cpp`:
- Around line 333-343: get_drift_time_array_view currently returns a zero-length
ndarray when the IM float array exists but is empty; change it to return None in
that case by checking arr.empty() after obtaining arr from getFloatDataArrays()
and return std::nullopt instead of constructing an ndarray; keep existing
behavior for non-empty arrays (use arr.data(), arr.size(), and self_obj to build
the ndarray) and preserve the containsIMData/getIMData checks.
- Around line 194-219: The get_peaks_struct lambda for MSSpectrum (and analogues
in Mobilogram and MSChromatogram) should follow the self_obj owner pattern:
change the lambda signature to take nb::object self_obj, cast self_obj to
OpenMS::MSSpectrum& (or the appropriate class) instead of using the implicit
self, and when constructing the ndarray pass self_obj as the owner instead of
nb::find(self); also update the nb::rv_policy and docstring usage as needed to
match other *_view()/get_peaks_view() methods. Ensure you replace nb::find(self)
with self_obj in the ndarray constructor call inside get_peaks_struct for
MSSpectrum, Mobilogram and MSChromatogram.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d742060e-416d-4784-9b19-4b272b8154cc

📥 Commits

Reviewing files that changed from the base of the PR and between c973066 and 5cec917.

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

Comment thread src/pyOpenMS/bindings/bind_spectrum.cpp Resolved
Comment thread src/pyOpenMS/bindings/bind_spectrum.cpp Resolved
…string

- Remove duplicate `using OSBDA` declaration in bind_analysis.cpp
  (already defined earlier in the same scope)
- Fix copy-paste error in MSChromatogram.sortByPosition docstring
  ("intensity" -> "position (RT)")

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@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_analysis.cpp`:
- Around line 2886-2896: The ndarray views (e.g., in get_mz_array_view) use
self_obj as the owner but the raw data pointer comes from a replaceable
BinaryDataArrayPtr (mz_arr/int_arr/time_arr) which can be reset by
setMZArray/setIntensityArray/setTimeArray and free the buffer; change the owner
passed to nb::ndarray from self_obj to the concrete array shared_ptr (i.e.,
nb::cast(mz_arr) or equivalent) so the BinaryDataArray stays alive while the
ndarray exists; apply the same fix to the corresponding functions that return
intensity/time views referenced in the review (use int_arr/time_arr as ndarray
owners instead of OSSpec/self_obj).

In `@src/pyOpenMS/bindings/bind_chromatogram.cpp`:
- Around line 169-197: The get_peaks_struct wrapper should mirror the ownership
pattern used in _get_peaks_view: change the signature to accept nb::object
self_obj, cast it to OpenMS::MSChromatogram& (e.g. auto& self =
self_obj.cast<OpenMS::MSChromatogram&>()), and when constructing the ndarray
pass self_obj as the owner instead of using nb::find(self); this preserves the
Python object's lifetime for the returned numpy view while keeping the rest of
the logic (dtype creation, empty check, data_ptr/byte_shape, and frombuffer
call) unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 524abfb0-4e0e-45d0-83f6-3cdedc157711

📥 Commits

Reviewing files that changed from the base of the PR and between 5cec917 and 31f1b5d.

📒 Files selected for processing (2)
  • src/pyOpenMS/bindings/bind_analysis.cpp
  • src/pyOpenMS/bindings/bind_chromatogram.cpp

Comment thread src/pyOpenMS/bindings/bind_analysis.cpp Resolved
…ad of None

Missed test assertion after changing _view methods to return empty
arrays on empty containers.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@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 (1)
src/pyOpenMS/tests/unittests/test_MSSpectrum.py (1)

171-171: Use the existing np alias instead of __import__.

numpy is already imported as np at the top of the file. Using __import__('numpy') is inconsistent and less readable.

Suggested fix
-        self.assertIsInstance(data_view, __import__('numpy').ndarray)
+        self.assertIsInstance(data_view, np.ndarray)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/tests/unittests/test_MSSpectrum.py` at line 171, Replace the use
of __import__('numpy') in the assertion with the existing np alias: update the
assertion that checks data_view's type (self.assertIsInstance(data_view,
__import__('numpy').ndarray)) to use np.ndarray instead so it reads
self.assertIsInstance(data_view, np.ndarray), referencing the data_view variable
in the test_MSSpectrum test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/pyOpenMS/tests/unittests/test_MSSpectrum.py`:
- Line 171: Replace the use of __import__('numpy') in the assertion with the
existing np alias: update the assertion that checks data_view's type
(self.assertIsInstance(data_view, __import__('numpy').ndarray)) to use
np.ndarray instead so it reads self.assertIsInstance(data_view, np.ndarray),
referencing the data_view variable in the test_MSSpectrum test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d379f613-c55e-4681-be0b-01b6de2ffed5

📥 Commits

Reviewing files that changed from the base of the PR and between 31f1b5d and 6343ea7.

📒 Files selected for processing (1)
  • src/pyOpenMS/tests/unittests/test_MSSpectrum.py

timosachsenberg and others added 4 commits March 9, 2026 21:16
Update contrib submodule to include CMAKE_POSITION_INDEPENDENT_CODE=ON
for the static libcurl build, fixing Linux wheel build linker failures.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Points to contrib master which includes the merged curl -fPIC fix,
openssl-devel addition to Dockerfiles, and improved error output.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- OpenSwath _view methods: use shared_ptr as ndarray owner instead of
  self_obj, preventing dangling pointers when arrays are replaced via
  setMZArray/setIntensityArray/setTimeArray/setDriftTimeArray
- get_peaks_struct methods: replace fragile nb::find(self) with
  nb::object self_obj pattern matching _get_peaks_view

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@timosachsenberg
timosachsenberg merged commit 9a99712 into develop Mar 10, 2026
41 checks passed
@timosachsenberg
timosachsenberg deleted the feature/zero-copy-api-unification branch March 10, 2026 06:02
github-actions Bot pushed a commit that referenced this pull request Mar 11, 2026
The _view zero-copy methods return an empty ndarray when the container
is empty, not None. This was incorrectly documented as 'None if empty'
after the zero-copy API naming unification in #8857.

The actual implementation in bind_kernel.cpp returns an empty ndarray
with shape (0,), consistent with its docstring 'empty array if empty'.
This is confirmed by test_zerocopy_conventions.py which asserts
isinstance(arr, np.ndarray) and len(arr) == 0.

Co-authored-by: Copilot <[email protected]>
timosachsenberg pushed a commit that referenced this pull request Mar 11, 2026
…DME (#8879)

The _view zero-copy methods return an empty ndarray when the container
is empty, not None. This was incorrectly documented as 'None if empty'
after the zero-copy API naming unification in #8857.

The actual implementation in bind_kernel.cpp returns an empty ndarray
with shape (0,), consistent with its docstring 'empty array if empty'.
This is confirmed by test_zerocopy_conventions.py which asserts
isinstance(arr, np.ndarray) and len(arr) == 0.

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
github-actions Bot pushed a commit that referenced this pull request Mar 12, 2026
…ruct, deprecated _mv)

The zero-copy API naming convention was standardized in #8857
(Fix ChromatogramPeak IntensityType consistency and unify zero-copy API
conventions). Enforcement tests were added in
test_zerocopy_conventions.py, but the naming convention itself was not
documented in the developer README.

Add a 'Zero-copy API Naming Conventions' subsection to README.md
explaining:
- _view suffix: typed 1-D ndarray column views
- _struct suffix: structured ndarray record views
- _mv suffix: deprecated (aliases live in deprecated_mv_aliases.py)
- Empty-container return behavior for each suffix

Co-authored-by: Copilot <[email protected]>
timosachsenberg pushed a commit that referenced this pull request Mar 12, 2026
…ruct, deprecated _mv) (#8890)

The zero-copy API naming convention was standardized in #8857
(Fix ChromatogramPeak IntensityType consistency and unify zero-copy API
conventions). Enforcement tests were added in
test_zerocopy_conventions.py, but the naming convention itself was not
documented in the developer README.

Add a 'Zero-copy API Naming Conventions' subsection to README.md
explaining:
- _view suffix: typed 1-D ndarray column views
- _struct suffix: structured ndarray record views
- _mv suffix: deprecated (aliases live in deprecated_mv_aliases.py)
- Empty-container return behavior for each suffix

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
github-actions Bot pushed a commit that referenced this pull request Mar 17, 2026
Add missing changelog entries for changes merged in the past 7 days:

- PyOpenMS: PeptideAndProteinQuant.getPeptideResults/getProteinResults exposed (#8543)
- PyOpenMS BREAKING: zero-copy _mv methods renamed to _view (#8857)
- TOPP BREAKING: FeatureFinderMultiplex/MultiplexResolver parameter missed_cleavages renamed to max_nr_labelled_aas (#8911)
- TOPP: MaRaClusterAdapter annotates consensus spectra with native IDs and cluster metadata (#8864)
- TOPP: MetaboliteAdductDecharger adds multimer detection (#8888)
- OpenMS Library BREAKING: ChromatogramPeak::IntensityType changed double -> float (#8857)
- Build: CMake 4.x compat fix for Windows packaging (#8880)
- Build: Fix pyOpenMS dev build RPATH (#8892)
- Build: Correctly locate locally installed nanobind (#8874)

Co-authored-by: Copilot <[email protected]>
timosachsenberg pushed a commit that referenced this pull request Mar 17, 2026
Add missing changelog entries for changes merged in the past 7 days:

- PyOpenMS: PeptideAndProteinQuant.getPeptideResults/getProteinResults exposed (#8543)
- PyOpenMS BREAKING: zero-copy _mv methods renamed to _view (#8857)
- TOPP BREAKING: FeatureFinderMultiplex/MultiplexResolver parameter missed_cleavages renamed to max_nr_labelled_aas (#8911)
- TOPP: MaRaClusterAdapter annotates consensus spectra with native IDs and cluster metadata (#8864)
- TOPP: MetaboliteAdductDecharger adds multimer detection (#8888)
- OpenMS Library BREAKING: ChromatogramPeak::IntensityType changed double -> float (#8857)
- Build: CMake 4.x compat fix for Windows packaging (#8880)
- Build: Fix pyOpenMS dev build RPATH (#8892)
- Build: Correctly locate locally installed nanobind (#8874)

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
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.

Type consistency for IntensityType

2 participants