Skip to content

Feature/drift time os spec - #6352

Closed
hroest wants to merge 24 commits into
OpenMS:developfrom
hroest:feature/drift_time_os_spec
Closed

hroest wants to merge 24 commits into
OpenMS:developfrom
hroest:feature/drift_time_os_spec

Conversation

@hroest

@hroest hroest commented Sep 27, 2022 •

Copy link
Copy Markdown
Contributor

Description

Allows access to the drift time part of OSSpectrum / OSChromatogram from pyOpenMS

Summary by CodeRabbit

  • New Features

    • Enhanced data handling for chromatograms and spectra to allow efficient modification and retrieval of multiple data arrays.
    • Added options to access data in both optimized array formats and via raw memory views, including support for drift time data.
    • Introduced new methods to set and get bulk data arrays, improving usability and performance.
    • Updated performance benchmarks to reflect improved data processing efficiency.
  • Tests

    • Expanded test coverage to ensure data integrity and verify the updated data retrieval and manipulation features.

@jpfeuffer jpfeuffer added the NoJenkins Skips Jenkins tests for PRs label Sep 27, 2022
@hroest
hroest force-pushed the feature/drift_time_os_spec branch from b83c066 to d51d82a Compare September 30, 2022 21:41
@hroest

hroest commented Sep 30, 2022

Copy link
Copy Markdown
Contributor Author

I have added a few more functions and tests, especially around the memory view:

Memoryview is about 3x faster than copying into numpy arrays and about 200x faster than using a Python list (pyopenms 2.7):

(pyopenms_27) hr@hr-Precision-5520:~$ python -m timeit -r 3 -s 'import pyopenms, numpy; d = numpy.random.rand( 100000).astype(numpy.float64); df = d.astype(numpy.float32); da = pyopenms.OSBinaryDataArray(); da.data = list(d.tolist()); s=pyopenms.OSSpectrum();s.setMZArray(d.tolist()); s.setIntensityArray(d.tolist()); rr= numpy.sum(d)'  \
> 'q = s.getMZArray(); assert numpy.sum(q) '
50 loops, best of 3: 6.07 msec per loop
(py38_bleeding) hr@hr-Precision-5520:~/openmsall/builds/openms_merge4/pyOpenMS$ python -m timeit -r 3 -s 'import pyopenms, numpy; d = numpy.random.rand( 100000).astype(numpy.float64); df = d.astype(numpy.float32); da = pyopenms.OSBinaryDataArray(); da.data = list(d.tolist()); s=pyopenms.OSSpectrum();s.setMZArray(d.tolist()); s.setIntensityArray(d.tolist()); rr= numpy.sum(d)'  \
'q = s.getMZArray(); assert numpy.sum(q) '
2000 loops, best of 3: 113 usec per loop
(py38_bleeding) hr@hr-Precision-5520:~/openmsall/builds/openms_merge4/pyOpenMS$ python -m timeit -r 3 -s 'import pyopenms, numpy; d = numpy.random.rand( 100000).astype(numpy.float64); df = d.astype(numpy.float32); da = pyopenms.OSBinaryDataArray(); da.data = list(d.tolist()); s=pyopenms.OSSpectrum();s.setMZArray(d.tolist()); s.setIntensityArray(d.tolist()); rr= numpy.sum(d)'  \
'q = s.getMZArray_mv(); assert numpy.sum(q) '
10000 loops, best of 3: 30.6 usec per loop

This is especially pronounced if only a few values are required from the data (eg first and last) which is about 50x faster with the memory view than copying into a numpy array and about 1500x faster than using a Python list (pyopenms 2.7):

(pyopenms_27) hr@hr-Precision-5520:~/openmsall/builds/openms_merge4/pyOpenMS$ python -m timeit -r 3 -s 'import pyopenms, numpy; d = numpy.random.rand( 100000).astype(numpy.float64); df = d.astype(numpy.float32); da = pyopenms.OSBinaryDataArray(); da.data = list(d.tolist()); s=pyopenms.OSSpectrum();s.setMZArray(d.tolist()); s.setIntensityArray(d.tolist()); rr= numpy.sum(d); lf = d[0]+d[-1]'  \
'q = s.getIntensityArray(); assert lf == q[0] + q[-1]'
200 loops, best of 3: 1.75 msec per loop
(py38_bleeding) hr@hr-Precision-5520:~/openmsall/builds/openms_merge4/pyOpenMS$ python -m timeit -r 3 -s 'import pyopenms, numpy; d = numpy.random.rand( 100000).astype(numpy.float64); df = d.astype(numpy.float32); da = pyopenms.OSBinaryDataArray(); da.data = list(d.tolist()); s=pyopenms.OSSpectrum();s.setMZArray(d.tolist()); s.setIntensityArray(d.tolist()); rr= numpy.sum(d); lf = d[0]+d[-1]'  \
'q = s.getIntensityArray_mv(); assert lf == q[0] + q[-1]'
200000 loops, best of 3: 1.04 usec per loop
(py38_bleeding) hr@hr-Precision-5520:~/openmsall/builds/openms_merge4/pyOpenMS$ python -m timeit -r 3 -s 'import pyopenms, numpy; d = numpy.random.rand( 100000).astype(numpy.float64); df = d.astype(numpy.float32); da = pyopenms.OSBinaryDataArray(); da.data = list(d.tolist()); s=pyopenms.OSSpectrum();s.setMZArray(d.tolist()); s.setIntensityArray(d.tolist()); rr= numpy.sum(d); lf = d[0]+d[-1]'  \
'q = s.getIntensityArray(); assert lf == q[0] + q[-1]'
5000 loops, best of 3: 54.1 usec per loop

However, its of course also easier to create a problem with the memory view:

Type "help", "copyright", "credits" or "license" for more information.
>>> import pyopenms, numpy; d = numpy.random.rand( 100000).astype(numpy.float64); df = d.astype(numpy.float32); da = pyopenms.OSBinaryDataArray(); da.data = list(d.tolist()); s=pyopenms.OSSpectrum();s.setMZArray(d.tolist()); s.setIntensityArray(d.tolist()); 
>>> 
>>> data_mv = s.getIntensityArray_mv()
>>> data = s.getIntensityArray()
>>> del s # delete underlying data
>>> 
>>> data[0]
0.8177584860990009
>>> data_mv[0] # Oh no, where did my data go?
6.9373143522718e-310
>>> 

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

Coo! Minor comments about docs.




def getData(self):

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.

I think it would be very important to add a function documentation to those methods.
And for the mv method, one could add the example that you showed on what NOT to do.

libcpp_string description

libcpp_vector[double] getData(self) #wrap-ignore wrap-doc:Access to a copy of the underlying data using a numpy array
libcpp_vector[double] getData_mv(self) #wrap-ignore wrap-doc:Access to the underlying data using a memory view

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.

Hmm now I am actually not 100% sure if this will generate the docs. I would think they need to be in the pyx as docstrings. What do you think? I guess having them in both locations would be safe but also redundant. Docs could also be extended for such a "dangerous" function.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

turns it out is not showing up in the docs (makes sense since we add wrap-ignore)

@jpfeuffer

Copy link
Copy Markdown
Contributor

We just need to move the docstrings from the pxd to pyx and extend a little bit with the nice comments from this PR.

@coderabbitai

coderabbitai Bot commented Apr 9, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This pull request adds new data manipulation methods to the OpenSwath classes. In C++ headers and Cython modules, new setter and getter functions have been introduced for OSChromatogram and OSSpectrum to handle binary data arrays. Methods now support both NumPy array conversion and raw memory views. A new file for OSBinaryDataArray provides additional data access routines. Benchmark scripts and unit tests have been updated to measure and ensure the correct functionality of these enhancements.

Changes

Files Change Summary
src/openswathalgo/.../DataStructures.h Added setDataArrays(std::vector<BinaryDataArrayPtr>& val) to both OSChromatogram and OSSpectrum structures.
src/pyOpenMS/addons/OSBinaryDataArray.pyx Introduced new file with getData (returns a NumPy array) and getData_mv (returns a raw double array) methods.
src/pyOpenMS/addons/OSChromatogram.pyx, src/pyOpenMS/addons/OSSpectrum.pyx Updated existing getter methods to return NumPy arrays; added new raw getters (*_mv), getDataArrays, and setDataArrays methods for enhanced binary data management. Added detailed docstrings.
src/pyOpenMS/pxds/OpenSwathDataStructures.pxd Reformatted constructors and added declarations for new methods (getData, getData_mv, drift time accessors, raw getters, and setDataArrays) for OSBinaryDataArray, OSSpectrum, and OSChromatogram.
src/pyOpenMS/performance.rst Updated performance benchmarks: replaced retrieval commands with processing-focused ones, adjusted loop counts, and added new measurements for OSSpectrum and MSSpectrum methods.
src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py Added new test methods for OSSpectrum and OSChromatogram to verify data retrieval, memory view integrity, and overall data array manipulation.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant OSSpectrum
    participant DataAccessor
    Client->>OSSpectrum: Call getMZArray() / getTimeArray()
    OSSpectrum->>DataAccessor: Retrieve underlying libcpp_vector data
    DataAccessor-->>OSSpectrum: Return data copy
    OSSpectrum->>Client: Convert to NumPy array and return
Loading
sequenceDiagram
    participant Client
    participant OSHandler
    participant UnderlyingCPP
    Client->>OSHandler: Call setDataArrays(newArrays)
    OSHandler->>UnderlyingCPP: Validate input and clear existing data
    OSHandler->>UnderlyingCPP: Populate with new OSBinaryDataArray instances
    UnderlyingCPP-->>OSHandler: Acknowledge update
    OSHandler->>Client: Confirm data arrays updated
Loading

Possibly related PRs

Suggested labels

Review effort 2/5

Suggested reviewers

  • jpfeuffer

Poem

I'm a rabbit, quick on my feet,
Hopping through code with a rhythmic beat.
New methods dance in the data stream,
Arrays and views now gleam and beam.
With every change, I leap with delight—
CodeRabbit hops into a future bright! 🐇


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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@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: 6

♻️ Duplicate comments (3)
src/pyOpenMS/addons/OSBinaryDataArray.pyx (2)

5-9: 🛠️ Refactor suggestion

Add documentation for the getData method.

The method performs data conversion from native C++ container to NumPy array, but lacks documentation explaining its purpose, return type, and potential performance characteristics. Consider adding a docstring to clarify that this method returns a copy of the data as a NumPy array.

    def getData(self):
+        """
+        Retrieve the data as a NumPy array.
+        
+        This method creates a copy of the underlying data, so it's safe to use
+        even after the original object is deleted or modified.
+        
+        Returns
+        -------
+        numpy.ndarray
+            A NumPy array containing a copy of the data
+        """
        cdef shared_ptr[_OSBinaryDataArray] _r = self.inst
        cdef double[::1] arr = <double [:_r.get().data.size()]>_r.get().data.data()
        retval = np.asarray(arr.copy())
        return retval

11-14: 🛠️ Refactor suggestion

Document the memory view method with safety warnings.

The getData_mv method returns a direct memory view which offers significant performance benefits but can lead to memory corruption if used incorrectly. Add documentation that clearly warns about memory safety concerns and provides example usage.

    def getData_mv(self):
+        """
+        Retrieve the data as a memory view for fast direct access.
+        
+        WARNING: The returned memory view refers directly to the underlying data.
+        If the original object is deleted or the underlying data is changed, the
+        memory view will point to invalid memory causing undefined behavior.
+        
+        Example of incorrect usage that can lead to memory corruption:
+           data_array = spectrum.getDataArrays()[0]
+           view = data_array.getData_mv()
+           del data_array  # The view is now invalid!
+           sum(view)  # This can crash or return incorrect values
+        
+        Returns
+        -------
+        memory view
+            A direct view of the underlying data array
+        """
        cdef shared_ptr[_OSBinaryDataArray] _r = self.inst
        cdef double[::1] arr = <double [:_r.get().data.size()]>_r.get().data.data()
        return arr
src/pyOpenMS/pxds/OpenSwathDataStructures.pxd (1)

13-14: Docstring placement may require moving to .pyx
This mirrors previous feedback about docstrings in .pxd not always showing up in documentation. Consider relocating them into the .pyx for clarity.

🧹 Nitpick comments (7)
src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h (2)

144-147: Add documentation for the setDataArrays method.

The method lacks documentation explaining its purpose and proper usage. Consider adding a comment similar to other setter methods in this class.

+    /// set all data arrays
+    /// @param val Vector of binary data arrays to be set
     void setDataArrays(std::vector<BinaryDataArrayPtr>& val)
     {
       binaryDataArrayPtrs = val;
     }

279-282: Add documentation for the setDataArrays method in OSSpectrum.

Similar to the OSChromatogram class, this method also lacks documentation explaining its purpose and proper usage.

+    /// set all data arrays
+    /// @param val Vector of binary data arrays to be set
     void setDataArrays(std::vector<BinaryDataArrayPtr>& val)
     {
       binaryDataArrayPtrs = val;
     }
src/pyOpenMS/addons/OSChromatogram.pyx (1)

53-67: Update setTimeArray and setIntensityArray to use NumPy arrays.

Both setTimeArray and setIntensityArray methods still use Python lists instead of NumPy arrays, which is inconsistent with the getter methods. Consider updating them to accept NumPy arrays for consistency and better performance.

    def setTimeArray(self, list data):
-        assert isinstance(data, list), 'arg transitions wrong type'
+        """
+        Set the time array.
+        
+        Parameters
+        ----------
+        data : list or numpy.ndarray
+            A list or NumPy array of time values
+        """
+        assert isinstance(data, (list, np.ndarray)), 'arg transitions wrong type'

        cdef shared_ptr[_OSBinaryDataArray] v0 = shared_ptr[_OSBinaryDataArray](new _OSBinaryDataArray() ) 
        cdef libcpp_vector[double] _vec = data
        v0.get().data = data
        self.inst.get().setTimeArray(v0)

    def setIntensityArray(self, list data):
-        assert isinstance(data, list), 'arg transitions wrong type'
+        """
+        Set the intensity array.
+        
+        Parameters
+        ----------
+        data : list or numpy.ndarray
+            A list or NumPy array of intensity values
+        """
+        assert isinstance(data, (list, np.ndarray)), 'arg transitions wrong type'

        cdef shared_ptr[_OSBinaryDataArray] v0 = shared_ptr[_OSBinaryDataArray](new _OSBinaryDataArray() ) 
        cdef libcpp_vector[double] _vec = data
        v0.get().data = data
        self.inst.get().setIntensityArray(v0)
src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py (3)

50-50: Remove unnecessary semicolon
Python doesn’t require semicolons at the end of statements.

- da.description = b"Ion Mobility";
+ da.description = b"Ion Mobility"
🧰 Tools
🪛 Ruff (0.8.2)

50-50: Statement ends with an unnecessary semicolon

Remove unnecessary semicolon

(E703)

🪛 GitHub Check: CodeFactor

[notice] 50-50: src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py#L50
statement ends with a semicolon (E703)


63-63: Remove unnecessary semicolon
Similar to line 50, remove the unused semicolon for cleanliness.

- da.description = b"test";
+ da.description = b"test"
🧰 Tools
🪛 Ruff (0.8.2)

63-63: Statement ends with an unnecessary semicolon

Remove unnecessary semicolon

(E703)

🪛 GitHub Check: CodeFactor

[notice] 63-63: src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py#L63
statement ends with a semicolon (E703)


134-134: Remove unnecessary semicolon
Again, semicolons are not needed in Python.

- da.description = b"test";
+ da.description = b"test"
🧰 Tools
🪛 Ruff (0.8.2)

134-134: Statement ends with an unnecessary semicolon

Remove unnecessary semicolon

(E703)

🪛 GitHub Check: CodeFactor

[notice] 134-134: src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py#L134
statement ends with a semicolon (E703)

src/pyOpenMS/addons/OSSpectrum.pyx (1)

5-9: Consider the performance impact of copying data
Using arr.copy() before np.asarray() ensures safe isolation from changes to the underlying buffer, but it incurs extra overhead. If performance is critical, consider clarifying that getMZArray and similar methods produce a copy, whereas *_mv() methods return a memory view.

Also applies to: 17-20, 27-33

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b36cdec and c1e2be2.

📒 Files selected for processing (7)
  • src/openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h (2 hunks)
  • src/pyOpenMS/addons/OSBinaryDataArray.pyx (1 hunks)
  • src/pyOpenMS/addons/OSChromatogram.pyx (1 hunks)
  • src/pyOpenMS/addons/OSSpectrum.pyx (2 hunks)
  • src/pyOpenMS/performance.rst (4 hunks)
  • src/pyOpenMS/pxds/OpenSwathDataStructures.pxd (2 hunks)
  • src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py

50-50: Statement ends with an unnecessary semicolon

Remove unnecessary semicolon

(E703)


63-63: Statement ends with an unnecessary semicolon

Remove unnecessary semicolon

(E703)


134-134: Statement ends with an unnecessary semicolon

Remove unnecessary semicolon

(E703)

🪛 GitHub Check: CodeFactor
src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py

[notice] 63-63: src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py#L63
statement ends with a semicolon (E703)


[notice] 50-50: src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py#L50
statement ends with a semicolon (E703)


[notice] 134-134: src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py#L134
statement ends with a semicolon (E703)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (windows-2022, cl.exe, default)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
🔇 Additional comments (10)
src/pyOpenMS/performance.rst (1)

51-67: Great performance benchmarks demonstrating improved efficiency!

The benchmarks clearly demonstrate the significant performance improvements of the memory view methods compared to traditional methods: getTimeArray_mv is ~3-4× faster than getTimeArray and direct memory access is orders of magnitude faster.

The benchmark results align with the PR's claim about memory views being approximately 3× faster than copying to NumPy arrays, which is excellent documentation of the performance benefits.

src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py (3)

27-74: Thorough coverage for test_spectrum_osw
This test covers m/z, intensity, and drift time arrays comprehensively, ensuring data integrity after array manipulations.

🧰 Tools
🪛 Ruff (0.8.2)

50-50: Statement ends with an unnecessary semicolon

Remove unnecessary semicolon

(E703)


63-63: Statement ends with an unnecessary semicolon

Remove unnecessary semicolon

(E703)

🪛 GitHub Check: CodeFactor

[notice] 63-63: src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py#L63
statement ends with a semicolon (E703)


[notice] 50-50: src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py#L50
statement ends with a semicolon (E703)


75-112: Clear demonstration of memory view behavior
These tests accurately illustrate how modifying a memory view reflects on the underlying data while preserving the original copy’s integrity.


113-145: Well-structured test for OSChromatogram
This method verifies time, intensity, and appended data arrays thoroughly.

🧰 Tools
🪛 Ruff (0.8.2)

134-134: Statement ends with an unnecessary semicolon

Remove unnecessary semicolon

(E703)

🪛 GitHub Check: CodeFactor

[notice] 134-134: src/pyOpenMS/tests/unittests/test_OpenSwathDataStructures.py#L134
statement ends with a semicolon (E703)

src/pyOpenMS/addons/OSSpectrum.pyx (4)

10-13: Memory view implementations
These methods cleanly expose raw data as memory views, facilitating efficient manipulation.

Also applies to: 22-25, 35-39


41-53: getDataArrays implementation
Converting the C++ vector of shared pointers into a Python list is straightforward and correct.


55-67: setDataArrays logic
Clearing the existing array vector, appending new data, and setting them on the C++ object aligns well with the intended design.


68-75: setMZArray function
Accepts a Python list, transfers values to the underlying C++ structure, and maintains type consistency. Looks good.

src/pyOpenMS/pxds/OpenSwathDataStructures.pxd (2)

20-34: OSSpectrum additions
The added constructors, getters, and setters (including drift time) are consistent with the .pyx definitions and enhance data manipulation capabilities.


44-56: OSChromatogram enhancements
New memory view methods and setDataArrays are well-aligned with the OSSpectrum counterpart, ensuring a uniform API.

Comment thread src/pyOpenMS/addons/OSChromatogram.pyx Resolved
Comment thread src/pyOpenMS/addons/OSChromatogram.pyx Resolved
Comment thread src/pyOpenMS/addons/OSChromatogram.pyx Resolved
Comment thread src/pyOpenMS/addons/OSChromatogram.pyx Resolved
Comment thread src/pyOpenMS/addons/OSChromatogram.pyx Resolved
Comment thread src/pyOpenMS/addons/OSChromatogram.pyx Resolved
@timosachsenberg

Copy link
Copy Markdown
Contributor

@jpfeuffer can we add the documentation as suggested by CodeRabbit?

@jpfeuffer

Copy link
Copy Markdown
Contributor

Yes, of course. pyx are just appended to the functions generated by autowrap.
But as suggested by me, I would add some code snippets on how things can go wrong with a memory view directly in the documentation.

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c1e2be2 and 787f4d5.

📒 Files selected for processing (2)
  • src/pyOpenMS/addons/OSChromatogram.pyx (1 hunks)
  • src/pyOpenMS/addons/OSSpectrum.pyx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/pyOpenMS/addons/OSChromatogram.pyx
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
🔇 Additional comments (7)
src/pyOpenMS/addons/OSSpectrum.pyx (7)

3-23: Well-implemented conversion to numpy array with proper safety measures.

The method correctly returns a copy of the data as a numpy array, ensuring memory safety. The comprehensive documentation and examples clearly explain the usage pattern.


24-54: Excellent documentation of memory view lifetime risks.

The implementation provides the expected zero-copy performance benefit, and the comprehensive warnings with concrete examples effectively communicate the dangers of improper usage. This is a valuable addition for performance-critical use cases.


55-75: Consistent implementation with getMZArray.

The method correctly follows the same safe pattern of returning a copied numpy array.


76-106: Properly implemented memory view access with clear warnings.


107-133: Well-implemented drift time access with proper NULL handling.

The method correctly handles the case where drift time data may not be present, returning None appropriately. The documentation clearly explains the ion mobility use case.


134-167: Consistent implementation with proper NULL handling.


168-200: Correctly implemented data array retrieval.

The method properly converts C++ shared pointers to Python OSBinaryDataArray objects.

Comment on lines 256 to 258
cdef libcpp_vector[double] _vec = data
v0.get().data = data
self.inst.get().setMZArray(v0)

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.

🛠️ Refactor suggestion

Remove unused variable declaration.

The variable _vec is declared but never used.

         cdef shared_ptr[_OSBinaryDataArray] v0 = shared_ptr[_OSBinaryDataArray](new _OSBinaryDataArray() )
-        cdef libcpp_vector[double] _vec = data
         v0.get().data = data
         self.inst.get().setMZArray(v0)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cdef libcpp_vector[double] _vec = data
v0.get().data = data
self.inst.get().setMZArray(v0)
cdef shared_ptr[_OSBinaryDataArray] v0 = shared_ptr[_OSBinaryDataArray](new _OSBinaryDataArray() )
v0.get().data = data
self.inst.get().setMZArray(v0)
🤖 Prompt for AI Agents
In src/pyOpenMS/addons/OSSpectrum.pyx around lines 256 to 258, the variable _vec
is declared but never used. Remove the declaration of _vec to clean up the code
and avoid unused variable warnings.

Comment on lines 283 to 285
cdef libcpp_vector[double] _vec = data
v0.get().data = data
self.inst.get().setIntensityArray(v0)

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.

🛠️ Refactor suggestion

Remove unused variable declaration.

The variable _vec is declared but never used, same as in setMZArray.

         cdef shared_ptr[_OSBinaryDataArray] v0 = shared_ptr[_OSBinaryDataArray](new _OSBinaryDataArray() )
-        cdef libcpp_vector[double] _vec = data
         v0.get().data = data
         self.inst.get().setIntensityArray(v0)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cdef libcpp_vector[double] _vec = data
v0.get().data = data
self.inst.get().setIntensityArray(v0)
cdef shared_ptr[_OSBinaryDataArray] v0 = shared_ptr[_OSBinaryDataArray](new _OSBinaryDataArray() )
v0.get().data = data
self.inst.get().setIntensityArray(v0)
🤖 Prompt for AI Agents
In src/pyOpenMS/addons/OSSpectrum.pyx around lines 283 to 285, the variable _vec
is declared but never used. Remove the declaration of _vec to clean up the code
and avoid unused variable warnings, similar to the fix needed in setMZArray.

Comment on lines +227 to +234
cdef libcpp_vector[ shared_ptr[_OSBinaryDataArray] ] _r = self.inst.get().getDataArrays()
_r.clear()

cdef OSBinaryDataArray rv
for rv in inp:
_r.push_back(rv.inst)

self.inst.get().setDataArrays(_r)

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.

🛠️ Refactor suggestion

Remove unnecessary get() and clear() operations.

The current implementation retrieves the existing data arrays into a local variable _r and then clears it, which has no effect on the actual spectrum. These operations are unnecessary since setDataArrays() will replace all arrays anyway.

-        cdef libcpp_vector[ shared_ptr[_OSBinaryDataArray] ]  _r = self.inst.get().getDataArrays()
-        _r.clear()
+        cdef libcpp_vector[ shared_ptr[_OSBinaryDataArray] ]  _r

         cdef OSBinaryDataArray rv
         for rv in inp:
             _r.push_back(rv.inst)

         self.inst.get().setDataArrays(_r)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cdef libcpp_vector[ shared_ptr[_OSBinaryDataArray] ] _r = self.inst.get().getDataArrays()
_r.clear()
cdef OSBinaryDataArray rv
for rv in inp:
_r.push_back(rv.inst)
self.inst.get().setDataArrays(_r)
cdef libcpp_vector[ shared_ptr[_OSBinaryDataArray] ] _r
cdef OSBinaryDataArray rv
for rv in inp:
_r.push_back(rv.inst)
self.inst.get().setDataArrays(_r)
🤖 Prompt for AI Agents
In src/pyOpenMS/addons/OSSpectrum.pyx around lines 227 to 234, remove the calls
to get() and clear() on the existing data arrays since clearing the local copy
does not affect the spectrum. Instead, directly create a new libcpp_vector,
populate it with the input arrays, and pass it to setDataArrays() to replace the
data arrays efficiently.

timosachsenberg and others added 6 commits August 4, 2025 17:07
- Remove unnecessary semicolons from test file (lines 50, 63, 134)
- Add documentation for setDataArrays() methods in DataStructures.h
- Add docstrings for getData() and getData_mv() in OSBinaryDataArray.pyx

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Handle the case where arrays are empty when creating memory views.
When data.size() is 0, data.data() returns NULL, and trying to
create a Cython memory view from NULL causes ValueError.

This fix:
- Returns np.empty(0) for copy methods (getMZArray, getIntensityArray, etc.)
- Returns None for memory view methods (*_mv) when array is empty
- Adds size check before creating memory view

Fixes test failure in test_ChromatogramExtractorAlgorithm.py

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
- Add get_mz_array(), get_intensity_array(), get_drift_time_array() to MSSpectrum
- Add get_drift_time_array_mv() and get_drift_time_unit() for ion mobility data
- Optimize get_peaks() with direct indexing instead of iterator
- Standardize FloatDataArray: get_data() returns copy, get_data_mv() returns view
- Add docstrings to OSSpectrum, OSChromatogram, OSBinaryDataArray addon methods
- Use snake_case naming convention consistent with existing pyOpenMS style
- Fix empty array handling (copy methods return empty array, view methods return None)
- Update unit tests for new method signatures and semantics

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
RichSpectrum class no longer exists in OpenMS - update test file name
to reflect that it only tests MSSpectrum.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@timosachsenberg

Copy link
Copy Markdown
Contributor

superseeded by #8423

timosachsenberg added a commit that referenced this pull request Dec 6, 2025
…8423)

* [FEATURE] also allow access to drift time

* [FEATURE] allow memory-view access to arrays

* [FEATURE] allow access to all data arrays

* [FEATURE] allow access to all data arrays

* [FEATURE] faster access to all data arrays

* [FEATURE] fast access to data in DataArrays

* [FIX] bugfix, actually copy the numpy data

* [FIX] get data arrays without copy

* [FEATURE] add setDataArrays() function

* [FEATURE] update pxd file

* [TEST] add tests

* [DOC] add performance tests

* add doc

* Address code review feedback for PR #6352

- Remove unnecessary semicolons from test file (lines 50, 63, 134)
- Add documentation for setDataArrays() methods in DataStructures.h
- Add docstrings for getData() and getData_mv() in OSBinaryDataArray.pyx

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* Fix empty array handling in OSSpectrum/OSChromatogram

Handle the case where arrays are empty when creating memory views.
When data.size() is 0, data.data() returns NULL, and trying to
create a Cython memory view from NULL causes ValueError.

This fix:
- Returns np.empty(0) for copy methods (getMZArray, getIntensityArray, etc.)
- Returns None for memory view methods (*_mv) when array is empty
- Adds size check before creating memory view

Fixes test failure in test_ChromatogramExtractorAlgorithm.py

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* Add MSSpectrum array accessors and improve pyOpenMS data array methods

- Add get_mz_array(), get_intensity_array(), get_drift_time_array() to MSSpectrum
- Add get_drift_time_array_mv() and get_drift_time_unit() for ion mobility data
- Optimize get_peaks() with direct indexing instead of iterator
- Standardize FloatDataArray: get_data() returns copy, get_data_mv() returns view
- Add docstrings to OSSpectrum, OSChromatogram, OSBinaryDataArray addon methods
- Use snake_case naming convention consistent with existing pyOpenMS style
- Fix empty array handling (copy methods return empty array, view methods return None)
- Update unit tests for new method signatures and semantics

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* Rename test_MSSpectrumAndRichSpectrum to test_MSSpectrum

RichSpectrum class no longer exists in OpenMS - update test file name
to reflect that it only tests MSSpectrum.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* [WIP] Update benchmark snippets to use snake_case Python method names (#8424)

* Initial plan

* Update benchmark snippets to use snake_case Python method names

Co-authored-by: timosachsenberg <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: timosachsenberg <[email protected]>

* Fix docstring example to demonstrate get_drift_time_array_mv() method (#8425)

* Initial plan

* Update docstring example to use get_drift_time_array_mv() method

Co-authored-by: timosachsenberg <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: timosachsenberg <[email protected]>

* Remove unused setUp method from test_MSSpectrum.py (#8426)

* Initial plan

* Remove unused setUp method and os import from test_MSSpectrum.py

Co-authored-by: timosachsenberg <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: timosachsenberg <[email protected]>

* Fix Cython nogil syntax and update tests to use snake_case API

- Fix Cython `nogil` position in OpenSwathDataStructures.pxd (use `except + nogil` not `nogil except +`)
- Update pyOpenMS tests to use new snake_case method names:
  - getMZArray() → get_mz_array()
  - getIntensityArray() → get_intensity_array()
  - setMZArray() → set_mz_array()
  - setIntensityArray() → set_intensity_array()
  - getTimeArray() → get_time_array()

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

---------

Co-authored-by: Hannes Roest <[email protected]>
Co-authored-by: Samuel Wein <[email protected]>
Co-authored-by: Claude <[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

NoJenkins Skips Jenkins tests for PRs Performance pyOpenMS

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants