Skip to content

feat: df wrapper for ms spectrum - #8435

Merged
poshul merged 20 commits into
developfrom
dfgetwrappedforMSSpecturm
Dec 6, 2025
Merged

poshul merged 20 commits into
developfrom
dfgetwrappedforMSSpecturm

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Dec 5, 2025 •

Copy link
Copy Markdown
Contributor

This pull request adds robust support for exporting OpenMS spectrum data to pandas DataFrames, making downstream data analysis in Python much easier. The main changes include a new get_data_dict method for MSSpectrum to extract all relevant spectrum and meta information as NumPy arrays, new utility functions for conversion to pandas DataFrames, and improvements to meta value handling for correct data types. Additionally, __len__ methods were added to several data array classes for convenience.

DataFrame Export and Conversion Utilities

  • Added get_data_dict to MSSpectrum, providing a comprehensive dictionary of spectrum data (m/z, intensity, retention time, MS level, ion mobility, precursor info, ion annotation, and meta values) as NumPy arrays, suitable for DataFrame conversion.
  • Introduced to_dataframe in pandas_utils.py and exposed it in the package API for easy conversion of OpenMS data dictionaries to pandas DataFrames, with import error handling. [1] [2]
  • Refactored and improved the _add_meta_values function to ensure meta values are exported with correct types (string, int, float, etc.) using the DataValue API, enhancing DataFrame compatibility.

Class Enhancements for DataFrame Support

  • Created _MSSpectrumDF class, extending MSSpectrum with a get_df() method for direct DataFrame export; set this as the new MSSpectrum and PeakSpectrum class to unify usage and documentation.

Convenience Improvements

  • Implemented __len__ methods for FloatDataArray, IntegerDataArray, and StringDataArray to support Pythonic length queries. [1] [2] [3]

These changes significantly improve the usability of OpenMS in Python data analysis workflows.

Summary by CodeRabbit

  • New Features

    • DataFrame export added for spectra, chromatograms, and transition groups via get_df()/get_chromatogram_df()/get_feature_df().
    • Metadata export enhanced with richer type conversions.
    • Python len() support for numeric and string data arrays.
    • Expanded chromatogram type options.
  • Tests

    • Unit tests updated to reflect the extended spectrum DataFrame schema.

✏️ Tip: You can customize this high-level summary in your review settings.

ChandraDevs1 and others added 15 commits April 6, 2025 00:55
…pendency-free metadata export && change np into _np
This commit fixes the implementation of get_df() and get_data_dict() methods
for MSSpectrum, addressing issue #7966.

Key changes:

1. MSSpectrum.pxd: Removed incorrect C++ method declarations (DataFrame get_df()
   and void get_data_dict()) - these methods are implemented in Python/Cython,
   not in C++.

2. MSSpectrum.pyx addon:
   - Removed incorrect 'cdef class MSSpectrum:' declaration
   - Fixed get_data_dict() to use Python type introspection instead of
     Cython cdef DataValue (which doesn't work in def methods)
   - Changed precursor_charge dtype to int16 (can be negative)
   - Improved documentation and code formatting

3. _dataframes.py:
   - Added _MSSpectrumDF wrapper class that provides get_df() method
   - get_df() calls get_data_dict() and converts to pandas DataFrame
   - Added MSSpectrum and PeakSpectrum aliases for the DF wrapper class
   - Follows same pattern as _MSChromatogramDF

4. Tests:
   - Comprehensive tests for get_data_dict() covering basic spectra,
     ion mobility, precursors, meta values, empty spectra
   - Tests for get_df() DataFrame export functionality
   - Fixed NaN comparison issues (use np.isnan instead of ==)

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

Co-Authored-By: Claude <[email protected]>
Resolved conflict in _dataframes.py by keeping the improved _MSSpectrumDF
implementation at the top of the file (which uses get_data_dict()) and
removing the duplicate class from develop.

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

Co-Authored-By: Claude <[email protected]>
Adds support for extracting ion annotations from StringDataArray named
'IonNames'. This feature was originally added by Axel Walter in PR #7489
for spectral library work.

The ion_annotation column contains per-peak annotation strings like
"y1", "b2", "y3-H2O", etc. that are populated by tools like
TheoreticalSpectrumGenerator.

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

Co-Authored-By: Claude <[email protected]>
- Change numpy import alias from _np to np (matching autowrap generated code)
- Use len() instead of .size() for Python lists returned by autowrap
- Use sda.size() for StringDataArray (has .size() method, no __len__)
- Fix KDTreeFeatureNode.pxd wrap-doc annotation (add blank comment terminator)
- Fix test expectation for DriftTimeUnit string (VSSC -> 1/K0)

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

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

coderabbitai Bot commented Dec 5, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Added MSSpectrum.get_data_dict and DataFrame-export wrapper classes for spectra, chromatograms, and MRM transition groups; added len to DataArray wrappers; refactored DataFrame export to use DataValue-aware meta-value conversions and adjusted minor pxd formatting.

Changes

Cohort / File(s) Summary
Spectrum data export
src/pyOpenMS/addons/MSSpectrum.pyx
Added def get_data_dict(self, export_meta_values=True) returning per-peak dictionaries (mz, intensity, rt, ms_level, native_id) and optional fields (ion_mobility, ion_mobility_unit, precursor_mz, precursor_charge, ion_annotation) plus meta-values when requested. Handles missing data with NaN/empty values.
DataFrame export framework
src/pyOpenMS/pyopenms/_dataframes.py
Introduced _MSSpectrumDF, _MSChromatogramDF, _MRMTransitionGroupCPDF with get_df() / export methods; rewired public aliases (MSSpectrum, PeakSpectrum, MSChromatogram, MRMTransitionGroupCP) to use new wrappers; replaced inline MSSpectrum->DataFrame logic to call get_data_dict; added DataValue-based _add_meta_values conversions and expanded ChromatogramType handling.
Array wrapper length support
src/pyOpenMS/addons/FloatDataArray.pyx, src/pyOpenMS/addons/IntegerDataArray.pyx, src/pyOpenMS/addons/StringDataArray.pyx
Added def __len__(self) to each wrapper delegating to self.inst.get().size() so Python len(...) reflects element count.
Tests updated
src/pyOpenMS/tests/unittests/test000.py
Adjusted MSSpectrum DataFrame test expectations for added column(s) (now asserts shape (2, 11) and checks new columns such as ion_mobility_unit, ms_level, precursor_mz, precursor_charge, native_id, ion_annotation).
Binding comment/formatting
src/pyOpenMS/pxds/KDTreeFeatureNode.pxd, src/pyOpenMS/pxds/MSSpectrum.pxd
Cosmetic reformatting and indentation changes in pxd files; no public API/signature changes.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Focus review areas:
    • src/pyOpenMS/pyopenms/_dataframes.py: new wrapper classes, DataFrame assembly logic, and DataValue type conversions in _add_meta_values.
    • src/pyOpenMS/addons/MSSpectrum.pyx: correctness around IM data detection (containsIMData/getIMData), precursor extraction, StringDataArray handling for IonNames, and NaN/empty fallbacks.
    • Tests: src/pyOpenMS/tests/unittests/test000.py adjusted expectations — ensure alignment with produced DataFrame schema.
    • Ensure ChromatogramType enum mapping matches C++ definitions and does not break external users.

Possibly related PRs

Suggested reviewers

  • poshul

Poem

🐰 In fields of peaks I hop and write,
I gather mz and intensity bright,
I count array lengths with a twitch of my paw,
Pack meta and drift in a tidy dict draw,
Hoppity hops — DataFrames take flight! ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: df wrapper for ms spectrum' accurately describes the main change: adding a DataFrame wrapper for MSSpectrum with get_df() functionality and related utilities.
Docstring Coverage ✅ Passed Docstring coverage is 84.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dfgetwrappedforMSSpecturm

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (4)
src/pyOpenMS/pxds/KDTreeFeatureNode.pxd (1)

5-12: Verify whether these formatting changes are intentional.

This file contains only formatting adjustments (whitespace, comment indentation) to KDTreeFeatureNode bindings, which appears unrelated to the PR's MSSpectrum DataFrame export functionality. These changes may be accidental (e.g., IDE auto-formatting).

Consider whether these changes should be:

  • Reverted if accidental
  • Moved to a separate cleanup PR if intentional

Additionally, line 11 contains a commented-out constructor that could be removed if it's no longer needed.

src/pyOpenMS/pyopenms/_dataframes.py (1)

730-733: Catch specific exception types and preserve context.

The bare except Exception is too broad and may hide unexpected errors. Additionally, the exception context is lost.

Apply this diff to catch more specific exceptions and preserve context:

-        except Exception: 
-            df[col_name] = _np.full(df.shape[0], str(dv), dtype='object')
+        except (TypeError, ValueError, AttributeError) as e:
+            # Fallback to string representation for unsupported types
+            df[col_name] = _np.full(df.shape[0], str(dv), dtype='object')
src/pyOpenMS/addons/MSSpectrum.pyx (2)

46-66: Ion mobility handling correctly uses getIMData, but could be slightly more robust

You’re correctly using containsIMData() and getIMData() to locate the ion mobility FloatDataArray, which aligns with the recommended pattern instead of assuming a fixed array index. Based on learnings, this is the right way to access IM data.

Two small robustness/performance considerations you may want to adopt:

  • Add a guard that len(im_arrays[im_index]) == cnt before indexing up to cnt to avoid potential IndexError if the IM array length ever drifts from the peak count.
  • Consider np.asarray(im_arrays[im_index], dtype=np.float64) instead of a Python list comprehension for large spectra, assuming the binding exposes the data array as a sequence compatible with NumPy.

If you expect the sizes to always match by design, these can stay as optional cleanups rather than required changes.


88-115: Meta value export is robust, but consider reserved-key collisions

The meta value handling is careful and type‑aware (bool vs int, float, str, and an object fallback with a broad except), which should cover the various MetaInfoInterface types well.

One behavioral nuance: meta keys are written directly into data_dict and can collide with core keys like "mz", "rt", "ms_level", etc., silently overwriting them if a user sets such a meta key. If you want to avoid this, you could either:

  • Skip meta keys that collide with a reserved set of column names, or
  • Namespace meta keys (e.g. prefix them with "meta_").

Not strictly required, but it would make the API more predictable in edge cases.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5bbe625 and a4eb624.

📒 Files selected for processing (7)
  • src/pyOpenMS/addons/MSSpectrum.pyx (4 hunks)
  • src/pyOpenMS/converters/__init__.py (1 hunks)
  • src/pyOpenMS/converters/pandas_utils.py (1 hunks)
  • src/pyOpenMS/pxds/KDTreeFeatureNode.pxd (1 hunks)
  • src/pyOpenMS/pxds/MSSpectrum.pxd (1 hunks)
  • src/pyOpenMS/pyopenms/_dataframes.py (2 hunks)
  • src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/pyOpenMS/tests/**/*.py

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write pyOpenMS tests for new Python bindings

Files:

  • src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py
🧠 Learnings (6)
📚 Learning: 2025-04-07T21:16:06.557Z
Learnt from: jpfeuffer
Repo: OpenMS/OpenMS PR: 7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.

Applied to files:

  • src/pyOpenMS/addons/MSSpectrum.pyx
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/**/*.h : Add Doxygen comments for new public methods and classes in pyOpenMS bindings

Applied to files:

  • src/pyOpenMS/addons/MSSpectrum.pyx
  • src/pyOpenMS/pxds/KDTreeFeatureNode.pxd
  • src/pyOpenMS/pxds/MSSpectrum.pxd
📚 Learning: 2025-06-16T15:48:09.667Z
Learnt from: FreezB11
Repo: OpenMS/OpenMS PR: 7969
File: src/pyOpenMS/pxds/TMTThirtyTwoPlexQuantitationMethod.pxd:4-4
Timestamp: 2025-06-16T15:48:09.667Z
Learning: In OpenMS .pxd files, the established pattern for extern from statements is to include angle brackets inside the string literal, like `cdef extern from "<OpenMS/PATH/TO/FILE.h>" namespace "OpenMS":`. This is consistent across all existing quantitation method .pxd files and other .pxd files in the OpenMS codebase.

Applied to files:

  • src/pyOpenMS/pxds/MSSpectrum.pxd
📚 Learning: 2025-06-16T15:49:26.504Z
Learnt from: FreezB11
Repo: OpenMS/OpenMS PR: 7969
File: src/pyOpenMS/pxds/TMTThirtyTwoPlexQuantitationMethod.pxd:1-3
Timestamp: 2025-06-16T15:49:26.504Z
Learning: In OpenMS Python bindings (.pxd files), derived quantitation method classes like TMTThirtyTwoPlexQuantitationMethod only need to declare their constructors. All other public methods (getName, getChannelInformation, getNumberOfChannels, getIsotopeCorrectionMatrix, getReferenceChannel) are inherited from the base IsobaricQuantitationMethod class and don't need to be redeclared explicitly.

Applied to files:

  • src/pyOpenMS/pxds/MSSpectrum.pxd
📚 Learning: 2025-11-18T20:08:08.900Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8374
File: src/pyOpenMS/pxds/SimpleSVM.pxd:0-0
Timestamp: 2025-11-18T20:08:08.900Z
Learning: In pyOpenMS .pxd files, copy constructors should be declared for wrapped C++ classes (e.g., `ClassName(ClassName&) except + nogil`) even when the C++ class has a deleted copy constructor. This is a standard pyOpenMS/Cython convention required for proper wrapper generation and Python object semantics.

Applied to files:

  • src/pyOpenMS/pxds/MSSpectrum.pxd
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/tests/**/*.py : Write pyOpenMS tests for new Python bindings

Applied to files:

  • src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py
🧬 Code graph analysis (1)
src/pyOpenMS/converters/__init__.py (1)
src/pyOpenMS/converters/pandas_utils.py (1)
  • to_dataframe (1-21)
🪛 Ruff (0.14.7)
src/pyOpenMS/converters/pandas_utils.py

16-19: Avoid specifying long messages outside the exception class

(TRY003)

src/pyOpenMS/pyopenms/_dataframes.py

732-732: Do not catch blind exception: Exception

(BLE001)


742-742: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


742-742: Avoid specifying long messages outside the exception class

(TRY003)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: build-lnx
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-macos
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-win
  • GitHub Check: build-and-test (macos-15-intel, xcode, 16.0.0)
  • GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-26, xcode, 26.0)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: cppcheck-test
🔇 Additional comments (8)
src/pyOpenMS/pyopenms/_dataframes.py (2)

27-72: LGTM! Clean implementation of DataFrame export for MSSpectrum.

The _MSSpectrumDF class properly extends MSSpectrum with the get_df() method that delegates to get_data_dict(). The docstring is comprehensive and the alias setup for both MSSpectrum and PeakSpectrum follows the established pattern in this file.


745-754: LGTM! Enum expansion looks correct.

The new chromatogram type enum values are properly named and follow the existing pattern.

src/pyOpenMS/pxds/MSSpectrum.pxd (1)

77-78: LGTM! Formatting-only changes.

These are minor formatting adjustments to the constructor declarations with no functional impact.

src/pyOpenMS/converters/__init__.py (1)

3-5: LGTM! Clean public API exposure.

The to_dataframe function is properly imported and exposed via __all__. The internal converters remain unexposed which is the correct design.

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

8-146: Excellent test coverage for get_data_dict().

The test class comprehensively covers:

  • Basic spectrum with peaks and metadata
  • Ion mobility data handling
  • Precursor information
  • Various meta value types (int, float, string)
  • Empty spectrum edge case
  • export_meta_values flag behavior
  • Ion annotations via StringDataArray

This aligns well with the PR objectives for robust MSSpectrum data export. Based on learnings, these tests properly exercise the new Python bindings.


149-234: Good DataFrame export tests with proper pandas handling.

The tests appropriately skip when pandas is not installed, and cover the key scenarios for DataFrame export including precursor data, meta values, and empty spectra.


237-275: LGTM! Basic MSSpectrum functionality tests.

The tests verify core operations including peak manipulation, range updates, and the set_peaks/get_peaks roundtrip.

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

1-2: NumPy cimport/import placement is consistent with typed array usage

cimport numpy as np and import numpy as np are needed for the typed np.ndarray[...] declarations and np.* calls later in this file; placement at the top is appropriate and matches existing patterns in this module.

Comment thread src/pyOpenMS/addons/MSSpectrum.pyx Resolved
Comment thread src/pyOpenMS/converters/pandas_utils.py Resolved
Comment thread src/pyOpenMS/pyopenms/_dataframes.py Resolved
- Add __len__ method to StringDataArray, FloatDataArray, IntegerDataArray
- Update MSSpectrum.pyx to use len() instead of .size() for consistency
- Enables Python's built-in len() function on these container classes

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

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/pyOpenMS/addons/MSSpectrum.pyx (1)

37-44: Use dynamic string dtype for native_id to prevent silent truncation.

The fixed dtype='U100' can silently truncate native_id values longer than 100 characters. Apply the same dynamic dtype pattern used for ion_annotation (lines 82-84):

Apply this diff:

-        cnt = len(mzs)
-        data_dict = {
-            'mz': mzs,
-            'intensity': intensities,
-            'rt': np.full(cnt, self.getRT(), dtype=np.float64),
-            'ms_level': np.full(cnt, self.getMSLevel(), dtype=np.uint16),
-            'native_id': np.full(cnt, self.getNativeID(), dtype='U100')
-        }
+        cnt = len(mzs)
+        native_id = self.getNativeID()
+        native_id_dtype = f"U{max(len(native_id), 1)}"
+        data_dict = {
+            'mz': mzs,
+            'intensity': intensities,
+            'rt': np.full(cnt, self.getRT(), dtype=np.float64),
+            'ms_level': np.full(cnt, self.getMSLevel(), dtype=np.uint16),
+            'native_id': np.full(cnt, native_id, dtype=native_id_dtype),
+        }
🧹 Nitpick comments (1)
src/pyOpenMS/addons/MSSpectrum.pyx (1)

46-65: Optimize ion mobility data extraction using get_data() method.

The element-by-element iteration at lines 52-55 is inefficient. FloatDataArray has a get_data() method that returns the entire numpy array directly.

Apply this diff:

         # Ion mobility handling
         if self.containsIMData():
             im_index, drift_time_unit = self.getIMData()
             im_arrays = self.getFloatDataArrays()
 
             if im_index >= 0 and im_index < len(im_arrays):
-                data_dict['ion_mobility'] = np.array(
-                    [im_arrays[im_index][i] for i in range(cnt)],
-                    dtype=np.float64
-                )
+                data_dict['ion_mobility'] = im_arrays[im_index].get_data().astype(np.float64)
             else:
                 data_dict['ion_mobility'] = np.full(cnt, np.nan, dtype=np.float64)

Based on learnings, the use of getIMData() to retrieve the ion mobility index is correct.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a4eb624 and 3de001b.

📒 Files selected for processing (4)
  • src/pyOpenMS/addons/FloatDataArray.pyx (1 hunks)
  • src/pyOpenMS/addons/IntegerDataArray.pyx (1 hunks)
  • src/pyOpenMS/addons/MSSpectrum.pyx (4 hunks)
  • src/pyOpenMS/addons/StringDataArray.pyx (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-04-07T21:16:06.557Z
Learnt from: jpfeuffer
Repo: OpenMS/OpenMS PR: 7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.

Applied to files:

  • src/pyOpenMS/addons/MSSpectrum.pyx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-lnx
  • GitHub Check: build-win
  • GitHub Check: build-and-test (macos-26, xcode, 26.0)
  • GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: cppcheck-test
🔇 Additional comments (8)
src/pyOpenMS/addons/IntegerDataArray.pyx (1)

75-77: LGTM!

The __len__ method correctly delegates to the underlying C++ container's size, enabling Pythonic len() usage on IntegerDataArray instances.

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

29-31: LGTM!

The __len__ method correctly exposes the array size, consistent with the pattern used in IntegerDataArray and FloatDataArray.

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

108-110: LGTM!

The __len__ method provides a consistent Pythonic interface across all DataArray types.

src/pyOpenMS/addons/MSSpectrum.pyx (5)

1-3: LGTM!

NumPy imports are correctly added for the new data export functionality.


7-31: LGTM!

The docstring is comprehensive and clearly documents the method's behavior, parameters, and return structure.


67-75: LGTM!

Precursor information handling is correct, with appropriate defaults for missing data. Using the first precursor is a reasonable convention.


77-86: LGTM!

Ion annotation handling correctly uses dynamic dtype to accommodate variable-length strings, and properly validates that the annotation array length matches the peak count. The use of len(sda) relies on the __len__ method added to StringDataArray in this PR.


88-114: LGTM with note on type checking pattern.

The meta value handling is robust and correctly maps OpenMS meta value types to appropriate NumPy dtypes. The dynamic dtype for strings (line 108) follows the correct pattern. The bool check at line 101 using type(v) is type(True) is unconventional but necessary to distinguish bool from int (since bool is a subclass of int in Python). The fallback to object dtype with exception handling provides good defensive coverage.

timosachsenberg and others added 3 commits December 5, 2025 22:11
…pecturm

# Conflicts:
#	src/pyOpenMS/addons/MSSpectrum.pyx
#	src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py
Following the standard Python library pattern (PyArrow, Polars, BioPandas),
DataFrame conversion should be done via methods on objects (.get_df())
rather than standalone helper functions.

- Delete pandas_utils.py (contained to_dataframe helper)
- Remove to_pandas() from _dataframes.py (redundant with pd.DataFrame)
- Clean up converters/__init__.py imports

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

Co-Authored-By: Claude <[email protected]>
@timosachsenberg timosachsenberg changed the title df wrapper for ms spectrum feat: df wrapper for ms spectrum Dec 6, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/pyOpenMS/addons/MSSpectrum.pyx (1)

37-44: Use dynamic string dtype for native_id to prevent silent truncation.

The fixed dtype='U100' can silently truncate native_id values longer than 100 characters. This issue was previously flagged but remains unaddressed. The correct pattern is already demonstrated in this file at lines 82-84 (for ion_annotation) and line 108 (for string meta values).

Apply this diff to use a dynamic dtype:

     cnt = len(mzs)
+    native_id = self.getNativeID()
+    native_id_dtype = f"U{max(len(native_id), 1)}"
     data_dict = {
         'mz': mzs,
         'intensity': intensities,
         'rt': np.full(cnt, self.getRT(), dtype=np.float64),
         'ms_level': np.full(cnt, self.getMSLevel(), dtype=np.uint16),
-        'native_id': np.full(cnt, self.getNativeID(), dtype='U100')
+        'native_id': np.full(cnt, native_id, dtype=native_id_dtype),
     }
🧹 Nitpick comments (2)
src/pyOpenMS/addons/MSSpectrum.pyx (2)

52-55: Optimize ion mobility array construction.

The current implementation creates a Python list via list comprehension then converts to a NumPy array. This is inefficient compared to accessing the underlying FloatDataArray data directly.

Consider this more efficient approach:

         if im_index >= 0 and im_index < len(im_arrays):
-            data_dict['ion_mobility'] = np.array(
-                [im_arrays[im_index][i] for i in range(cnt)],
-                dtype=np.float64
-            )
+            # Access data directly from FloatDataArray
+            im_data = im_arrays[im_index].get_data()
+            data_dict['ion_mobility'] = np.array(im_data, dtype=np.float64)
         else:

88-114: Consider consistency with meta value type detection approach.

This implementation uses Python type introspection on autowrapped values (isinstance(v, int), etc.), while _add_meta_values() in _dataframes.py (lines 715-728) uses DataValue.valueType() for type detection. Both approaches should work, but the inconsistency may cause maintenance confusion.

The current implementation is solid:

  • Line 101 correctly uses type(v) is type(True) to distinguish bools from ints
  • Dynamic string dtype at line 108 prevents truncation
  • Exception handling provides robust fallback

Consider standardizing on one approach across the codebase. If you prefer the DataValue.valueType() approach, you could refactor this to match _add_meta_values():

# Alternative approach using DataValue (for consistency with _dataframes.py)
dv = self.getMetaValue(k)
if dv.valueType() == _DataValue.STRING_VALUE:
    v = dv.toString().decode()
    data_dict[k_str] = np.full(cnt, v, dtype=f"U{max(len(v), 1)}")
elif dv.valueType() == _DataValue.INT_VALUE:
    data_dict[k_str] = np.full(cnt, dv.toInt(), dtype=np.int64)
# ... etc
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3bf2f0b and b863c20.

📒 Files selected for processing (4)
  • src/pyOpenMS/addons/FloatDataArray.pyx (1 hunks)
  • src/pyOpenMS/addons/MSSpectrum.pyx (2 hunks)
  • src/pyOpenMS/pxds/MSSpectrum.pxd (1 hunks)
  • src/pyOpenMS/pyopenms/_dataframes.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/pyOpenMS/pxds/MSSpectrum.pxd
  • src/pyOpenMS/addons/FloatDataArray.pyx
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-04-07T21:16:06.557Z
Learnt from: jpfeuffer
Repo: OpenMS/OpenMS PR: 7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.

Applied to files:

  • src/pyOpenMS/addons/MSSpectrum.pyx
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/**/*.h : Add Doxygen comments for new public methods and classes in pyOpenMS bindings

Applied to files:

  • src/pyOpenMS/addons/MSSpectrum.pyx
🪛 Ruff (0.14.7)
src/pyOpenMS/pyopenms/_dataframes.py

732-732: Do not catch blind exception: Exception

(BLE001)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (12)
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-lnx
  • GitHub Check: build-macos
  • GitHub Check: build-win
  • GitHub Check: build-macos-arm
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-15-intel, xcode, 16.0.0)
  • GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (macos-26, xcode, 26.0)
  • GitHub Check: cppcheck-test
🔇 Additional comments (4)
src/pyOpenMS/addons/MSSpectrum.pyx (2)

67-76: LGTM!

The precursor information handling is correct. The use of np.int16 for charge values provides sufficient range (typical charges are 1-8, occasionally higher but well within int16 range).


77-86: LGTM!

The ion annotation handling correctly uses a dynamic dtype pattern to prevent truncation. The code relies on len(sda) which requires StringDataArray.__len__() to be implemented (added in this PR according to the AI summary).

src/pyOpenMS/pyopenms/_dataframes.py (2)

27-72: LGTM!

The _MSSpectrumDF wrapper class cleanly extends _MSSpectrum with DataFrame export capability. The implementation correctly delegates to get_data_dict() and the module/name aliasing ensures proper documentation generation.


20-20: LGTM!

The DataValue import is correctly added to support type-aware meta value handling in the refactored _add_meta_values() function.

Comment thread src/pyOpenMS/pyopenms/_dataframes.py Resolved
- getMetaValue() returns native Python types (float, int, str), not DataValue
  objects, causing valueType() calls to fail and fall back to string conversion
- Now check for native Python types first before trying DataValue methods
- Also fix testMSSpectrum expected shape from (2,10) to (2,11) for ion_annotation column

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

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

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

⚠️ Outside diff range comments (2)
src/pyOpenMS/pyopenms/_dataframes.py (2)

795-799: Intensity dtype should be float, not uint64.

Chromatogram intensities are typically floating-point values. Using uint64 will truncate decimal values and could cause data loss.

-        dtypes = [('time', _np.dtype('double')), ('intensity', _np.dtype('uint64'))]
+        dtypes = [('time', _np.dtype('double')), ('intensity', _np.dtype('float32'))]

This aligns with how intensity is handled elsewhere in the codebase (e.g., MSExperiment.get_df uses float for intensity).


882-906: Bug: meta_values=None will cause TypeError.

When meta_values is None (the default), line 882 attempts to iterate over it in the list comprehension, which raises TypeError: 'NoneType' object is not iterable.

This pattern is handled correctly in _FeatureMapDF.get_df (lines 275-276). Apply the same fix:

     def get_feature_df(self, meta_values: Union[None, List[str], str] = None) -> _pd.DataFrame:
         # ... docstring ...
+        
+        # Handle None case - set to empty list
+        if meta_values is None:
+            meta_values = []
+
         def gen(features: List[_MRMFeature], fun):
             for f in features:
                 yield from fun(f)

Alternatively, guard the iteration in extract_meta_data:

         def extract_meta_data(f: _MRMFeature):
-            vals = [f.getMetaValue(m) if f.metaValueExists(m) else _np.nan for m in meta_values]
+            vals = [f.getMetaValue(m) if f.metaValueExists(m) else _np.nan for m in (meta_values or [])]
♻️ Duplicate comments (1)
src/pyOpenMS/pyopenms/_dataframes.py (1)

735-751: Inconsistent integer dtype and broad exception handling.

Two issues remain from the previous review:

  1. Dtype inconsistency: Native int uses int64 (line 721) but DataValue.INT_VALUE uses int32 (line 735). This should be consistent.

  2. Broad exception: The except Exception at line 750 catches all exceptions, making debugging difficult.

-                elif dv.valueType() == _DataValue.INT_VALUE:
-                    value = dv.toInt()
-                    dtype = "int32"
+                elif dv.valueType() == _DataValue.INT_VALUE:
+                    value = dv.toInt()
+                    dtype = "int64"
-        except Exception:
-            df[col_name] = _np.full(df.shape[0], str(dv), dtype='object')
+        except (ValueError, TypeError):
+            df[col_name] = _np.full(df.shape[0], str(dv), dtype='object')
🧹 Nitpick comments (1)
src/pyOpenMS/pyopenms/_dataframes.py (1)

843-845: Consider resetting index when concatenating chromatogram DataFrames.

Each chromatogram DataFrame starts with index 0, so concatenating without resetting indices will create duplicate index values, which can cause issues when accessing rows by label.

-        out = [ _MSChromatogramDF(c).get_df(export_meta_values=export_meta_values) for c in chroms ]
-        return _pd.concat(out)
+        out = [ _MSChromatogramDF(c).get_df(export_meta_values=export_meta_values) for c in chroms ]
+        return _pd.concat(out, ignore_index=True)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b863c20 and 42ed5a4.

📒 Files selected for processing (2)
  • src/pyOpenMS/pyopenms/_dataframes.py (2 hunks)
  • src/pyOpenMS/tests/unittests/test000.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/pyOpenMS/tests/**/*.py

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write pyOpenMS tests for new Python bindings

Files:

  • src/pyOpenMS/tests/unittests/test000.py
🪛 Ruff (0.14.7)
src/pyOpenMS/pyopenms/_dataframes.py

750-750: Do not catch blind exception: Exception

(BLE001)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (12)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-macos
  • GitHub Check: build-lnx-arm
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-macos-arm
  • GitHub Check: build-lnx
  • GitHub Check: build-win
  • GitHub Check: build-and-test (macos-15-intel, xcode, 16.0.0)
  • GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (macos-26, xcode, 26.0)
  • GitHub Check: cppcheck-test
🔇 Additional comments (2)
src/pyOpenMS/tests/unittests/test000.py (1)

3364-3374: LGTM!

The updated assertion correctly reflects the new DataFrame schema that now includes 11 columns. The individual column assertions comprehensively verify the expected values including the new ion_mobility_unit column.

src/pyOpenMS/pyopenms/_dataframes.py (1)

27-71: LGTM!

The new _MSSpectrumDF class follows the established pattern used by other wrapper classes in this file. The delegation to get_data_dict() keeps the implementation clean and the docstring comprehensively documents all DataFrame columns.

@poshul
poshul enabled auto-merge (squash) December 6, 2025 13:58
@poshul
poshul merged commit 63e530b into develop Dec 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants