Repository navigation
feat: df wrapper for ms spectrum - #8435
Conversation
…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]>
WalkthroughAdded 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ 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
🧹 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
KDTreeFeatureNodebindings, 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 Exceptionis 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 usesgetIMData, but could be slightly more robustYou’re correctly using
containsIMData()andgetIMData()to locate the ion mobilityFloatDataArray, 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]) == cntbefore indexing up tocntto avoid potentialIndexErrorif 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 collisionsThe 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 variousMetaInfoInterfacetypes well.One behavioral nuance: meta keys are written directly into
data_dictand 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
📒 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.pyxsrc/pyOpenMS/pxds/KDTreeFeatureNode.pxdsrc/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
_MSSpectrumDFclass properly extendsMSSpectrumwith theget_df()method that delegates toget_data_dict(). The docstring is comprehensive and the alias setup for bothMSSpectrumandPeakSpectrumfollows 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_dataframefunction 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 forget_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_valuesflag 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_peaksroundtrip.src/pyOpenMS/addons/MSSpectrum.pyx (1)
1-2: NumPy cimport/import placement is consistent with typed array usage
cimport numpy as npandimport numpy as npare needed for the typednp.ndarray[...]declarations andnp.*calls later in this file; placement at the top is appropriate and matches existing patterns in this module.
- 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]>
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/pyOpenMS/addons/MSSpectrum.pyx (1)
37-44: Use dynamic string dtype fornative_idto prevent silent truncation.The fixed
dtype='U100'can silently truncatenative_idvalues longer than 100 characters. Apply the same dynamic dtype pattern used forion_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 usingget_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
📒 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 Pythoniclen()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.
…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]>
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/pyOpenMS/addons/MSSpectrum.pyx (1)
37-44: Use dynamic string dtype fornative_idto prevent silent truncation.The fixed
dtype='U100'can silently truncatenative_idvalues 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 (forion_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) usesDataValue.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
📒 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.int16for 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 requiresStringDataArray.__len__()to be implemented (added in this PR according to the AI summary).src/pyOpenMS/pyopenms/_dataframes.py (2)
27-72: LGTM!The
_MSSpectrumDFwrapper class cleanly extends_MSSpectrumwith DataFrame export capability. The implementation correctly delegates toget_data_dict()and the module/name aliasing ensures proper documentation generation.
20-20: LGTM!The
DataValueimport is correctly added to support type-aware meta value handling in the refactored_add_meta_values()function.
- 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]>
There was a problem hiding this comment.
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
uint64will 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_dfuses float for intensity).
882-906: Bug:meta_values=Nonewill cause TypeError.When
meta_valuesisNone(the default), line 882 attempts to iterate over it in the list comprehension, which raisesTypeError: '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:
Dtype inconsistency: Native
intusesint64(line 721) butDataValue.INT_VALUEusesint32(line 735). This should be consistent.Broad exception: The
except Exceptionat 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
📒 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_unitcolumn.src/pyOpenMS/pyopenms/_dataframes.py (1)
27-71: LGTM!The new
_MSSpectrumDFclass follows the established pattern used by other wrapper classes in this file. The delegation toget_data_dict()keeps the implementation clean and the docstring comprehensively documents all DataFrame columns.
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_dictmethod forMSSpectrumto 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
get_data_dicttoMSSpectrum, 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.to_dataframeinpandas_utils.pyand exposed it in the package API for easy conversion of OpenMS data dictionaries to pandas DataFrames, with import error handling. [1] [2]_add_meta_valuesfunction to ensure meta values are exported with correct types (string, int, float, etc.) using theDataValueAPI, enhancing DataFrame compatibility.Class Enhancements for DataFrame Support
_MSSpectrumDFclass, extendingMSSpectrumwith aget_df()method for direct DataFrame export; set this as the newMSSpectrumandPeakSpectrumclass to unify usage and documentation.Convenience Improvements
__len__methods forFloatDataArray,IntegerDataArray, andStringDataArrayto 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
Tests
✏️ Tip: You can customize this high-level summary in your review settings.