Repository navigation
Fix ChromatogramPeak IntensityType consistency and unify zero-copy API conventions - #8857
Conversation
…cy (issue #3379) Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
…layout Co-Authored-By: Claude Opus 4.6 <[email protected]>
#3379) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…Peak2D Co-Authored-By: Claude Opus 4.6 <[email protected]>
…pe change Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
…tensity Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ed dtype Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- 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]>
…ility 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]>
…nsistency 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]>
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>
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughChromatogram/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
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
Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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: 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 | 🟠 MajorInconsistent ndarray owner in
_get_peaks_view(); use explicit Python object reference.This method returns an
nb::ndarraypointing intoself.data()withnb::handle()as owner. However,get_peaks_struct()in the same file usesnb::find(self)for the same pattern, andget_drift_time_array_mv()uses theself_objapproach you propose. Passingnb::handle()bypasses explicit lifetime binding to the parent; use thenb::object self_objcapture pattern to ensure the ndarray holds a reference toselfacross 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 throughTypes.h.This change still hard-codes
floatanddoublein a public header. Please use the corresponding OpenMS primitive aliases fromOpenMS/CONCEPT/Types.hso the precision choice stays centralized and platform-independent.As per coding guidelines, "Use OpenMS primitive types from
OpenMS/CONCEPT/Types.hinstead 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/CoordinateTypeto the matching aliases fromOpenMS/CONCEPT/Types.hinstead of rawfloat/doubleso this header stays aligned with the portability convention.As per coding guidelines: Use OpenMS primitive types from
OpenMS/CONCEPT/Types.hinstead 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()hardcodesmzat offset0,intensityat offset8, anditemsize = 16, but the newstatic_assertonly 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 keepIntensityType/CoordinateTypeon the project-defined primitive aliases instead of rawfloat/double.As per coding guidelines: Use OpenMS primitive types from
OpenMS/CONCEPT/Types.hinstead 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
ChromatogramPeakcontract in several places (double,float, offsets0/8, itemsize16, andsize_t). The singlesizeof(OpenMS::ChromatogramPeak) == 16check 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 throughOpenMS::ChromatogramPeak::{CoordinateType, IntensityType, PositionType}plusOpenMS::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.hinstead 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
📒 Files selected for processing (21)
src/openms/include/OpenMS/KERNEL/ChromatogramPeak.hsrc/openms/include/OpenMS/KERNEL/MobilityPeak2D.hsrc/openms/include/OpenMS/KERNEL/Peak2D.hsrc/openms/source/FEATUREFINDER/FeatureFinderMultiplexAlgorithm.cppsrc/openms/source/FORMAT/ChromeleonFile.cppsrc/openms_gui/source/VISUAL/LayerData1DChrom.cppsrc/pyOpenMS/bindings/bind_analysis.cppsrc/pyOpenMS/bindings/bind_chromatogram.cppsrc/pyOpenMS/bindings/bind_datastructures.cppsrc/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/bindings/bind_spectrum.cppsrc/pyOpenMS/pyopenms/addons/mobilogram.pysrc/pyOpenMS/pyopenms/addons/msspectrum.pysrc/pyOpenMS/tests/test_matrix_zerocopy.pysrc/pyOpenMS/tests/unittests/test000.pysrc/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.pysrc/pyOpenMS/tests/unittests/test_mobilogram_struct_view.pysrc/pyOpenMS/tests/unittests/test_mschromatogram_struct_view.pysrc/pyOpenMS/tests/unittests/test_spectrum_zerocopy.pysrc/pyOpenMS/tests/unittests/test_zerocopy_conventions.pysrc/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
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]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/pyOpenMS/bindings/bind_kernel.cpp (1)
1644-1655:⚠️ Potential issue | 🟠 MajorBind
_get_peaks_view()to the parentMobilogram.Line 1651 still uses an empty owner handle, so the returned ndarray can outlive
selfand 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 fromMobilityPeak1Dinstead of hard-coding8and16.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
📒 Files selected for processing (11)
src/pyOpenMS/bindings/bind_analysis.cppsrc/pyOpenMS/bindings/bind_datastructures.cppsrc/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/bindings/bind_spectrum.cppsrc/pyOpenMS/pyopenms/addons/deprecated_mv_aliases.pysrc/pyOpenMS/tests/benchmark_pyopenms.pysrc/pyOpenMS/tests/test_matrix_zerocopy.pysrc/pyOpenMS/tests/unittests/test000.pysrc/pyOpenMS/tests/unittests/test_MSSpectrum.pysrc/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.pysrc/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]>
There was a problem hiding this comment.
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 | 🟠 MajorResolve the drift-time view via
getIMData().This path still rediscovers the ion-mobility array by matching
"Ion Mobility"labels insideFloatDataArrays. Please use the stored index fromself.getIMData().firstinstead, so the view follows OpenMS' canonical IM mapping rather than metadata naming. The copy-returningget_drift_time_array()path should stay aligned too.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`.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 + );🤖 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 againstOpenMS::Intwidth drift.This view aliases
self.data()asint32_t*, but the container storesOpenMS::Int. That is only safe ifOpenMS::Intis guaranteed 32-bit on every supported platform. Please either bindOpenMS::Intdirectly 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.hinstead 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 matchingChromatogramPeaktype guard here.The binding now hardcodes
floatforChromatogramPeak, but onlyMobilityPeak1Dis 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 hoistingas_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.hwould 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
📒 Files selected for processing (7)
src/pyOpenMS/README.mdsrc/pyOpenMS/bindings/bind_chromatogram.cppsrc/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/bindings/bind_spectrum.cppsrc/pyOpenMS/performance.rstsrc/pyOpenMS/pyopenms/addons/deprecated_mv_aliases.pysrc/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
… 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]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
src/pyOpenMS/bindings/bind_kernel.cpp (3)
111-119: Guard the actualintensityfield offset, not just size and scalar types.
get_peaks_struct()derives theintensityoffset fromsizeof(PositionType), but the current ABI asserts never prove that the member actually starts there. If padding is ever introduced betweenposition_andintensity_, the structured dtype will silently reinterpret the wrong bytes. Please source this offset from a compile-time constant oroffsetofdefined whereMobilityPeak1D’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 theIntegerDataArrayNumPy ABI assumption explicit.
int32_t* data_ptr = self.data()only works as a zero-copy view while the container’svalue_typeis exactly 32-bit. Add astatic_assertnear 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: Constrainas_numpy_array()to the dtypes it really supports.Right now every non-
floatinstantiation falls into thefloat64branch and only fails later attry_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()andMatrixDouble.get_matrix_mv(), but the same PR also renamed the OpenSwath accessors insrc/pyOpenMS/bindings/bind_analysis.cpp. IfOSBinaryDataArray.get_data_mv(),OSSpectrum.get_*_array_mv(), orOSChromatogram.get_*_array_mv()is missing fromsrc/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*_mvmethods exist only as deprecated aliases implemented insrc/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
📒 Files selected for processing (7)
src/pyOpenMS/bindings/bind_analysis.cppsrc/pyOpenMS/bindings/bind_datastructures.cppsrc/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/bindings/bind_spectrum.cppsrc/pyOpenMS/tests/test_matrix_zerocopy.pysrc/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.pysrc/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]>
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_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
📒 Files selected for processing (1)
src/pyOpenMS/bindings/bind_spectrum.cpp
…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]>
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_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
📒 Files selected for processing (2)
src/pyOpenMS/bindings/bind_analysis.cppsrc/pyOpenMS/bindings/bind_chromatogram.cpp
…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]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/pyOpenMS/tests/unittests/test_MSSpectrum.py (1)
171-171: Use the existingnpalias instead of__import__.
numpyis already imported asnpat 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
📒 Files selected for processing (1)
src/pyOpenMS/tests/unittests/test_MSSpectrum.py
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]>
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]>
…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]>
…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]>
…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]>
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]>
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]>
Summary
IntensityType#3379: ChangeChromatogramPeak::IntensityTypefromdoubletofloat, matching all other peak types (Peak1D,Peak2D,MobilityPeak1D,MobilityPeak2D)typedeftousingdeclarations across all peak types_mv= typed zero-copy column view, returnsNoneif 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())_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)FeatureFinderMultiplexAlgorithm,ChromeleonFile,LayerData1DChromwithstatic_cast<ChromatogramPeak::IntensityType>static_assertcompile-time checks for type consistency across all peak typestypedef→usinginPeak2D,MobilityPeak2DpyOpenMS bindings:
ChromatogramPeakbinding to usefloatintensityMSChromatogramget_peaks/set_peaksforfloatintensity arraysget_peaks_struct()in C++ for all three peak containers (MSSpectrum, MSChromatogram, Mobilogram) with proper structured dtype{coordinate: float64, intensity: float32}_get_peaks_view()(internal raw byte view) for all threestatic_assert(sizeof(...) == 16)for all three peak types_mvmethods (returnNoneon empty)get_matrix_as_view()→get_matrix_mv()with empty guardget_peaks_structfrom Python addon to C++ bindingget_peaks_struct(MSSpectrum, Mobilogram)Tests (34 passing):
test_zerocopy_conventions.py: 7 cross-cutting convention tests (empty handling, writeback, no public_viewmethods)test_spectrum_zerocopy.py: zero-copy modification, memory safety, empty structtest_mschromatogram_struct_view.py: zero-copy, memory safety, empty, dtype, type consistencytest_mobilogram_struct_view.py: values, zero-copy, empty, single peak, 100k dataset, memory lifetime, mutationtest_OpenSwathDataStructures.py: empty guards for all OpenSwath_mvmethodstest_matrix_zerocopy.py: bidirectional zero-copy, empty guardTest plan
get_peaks()/get_data_dict(), not view methods)🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Behavior
Refactor
Chores
Tests
Documentation