Repository navigation
MSSpectrum: Add DataFrame export via get_df() - #7970
ChandraDevs1 wants to merge 23 commits into
Conversation
WalkthroughThe changes introduce several new methods to the Changes
Sequence Diagram(s)sequenceDiagram
participant U as User
participant M as MSSpectrum
participant P as Pandas DataFrame
U->>M: Call get_df()
M->>P: Build DataFrame with spectrum data
P-->>M: Return constructed DataFrame
M-->>U: Return DataFrame
Assessment against linked issues
Poem
Tip ⚡💬 Agentic Chat (Pro Plan, General Availability)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/pyOpenMS/pxds/MSSpectrum.pxd (1)
77-77: Add documentation for the new get_df methodThe new method declaration looks good, but it's missing a documentation string like other methods in this file. Consider adding a
wrap-doccomment to describe what the method does and how to use it.- DataFrame get_df() except + + DataFrame get_df() except + # wrap-doc:Returns a pandas DataFrame representation of the spectrum with mz, intensity and metadatasrc/pyOpenMS/pyopenms/_dataframes.py (1)
711-761: Enhance documentation for the get_df methodThe current implementation is comprehensive and handles various data types and edge cases correctly. However, the docstring could be improved to better explain the columns in the resulting DataFrame, similar to the docstring in the first implementation (which should be removed).
def get_df(self, export_meta_values: bool = True) -> _pd.DataFrame: """ Returns a DataFrame representation of the MSSpectrum. Args: export_meta_values (bool): Whether to export meta values. Returns: - pd.DataFrame: DataFrame representation of the MSSpectrum. + pd.DataFrame: DataFrame with columns: + - mz: Mass-to-charge ratio values + - intensity: Intensity values for each peak + - ion_mobility: Ion mobility values (if available) + - ion_mobility_unit: Unit of ion mobility measurements + - ms_level: MS level of the spectrum + - precursor_mz: Precursor mass-to-charge ratio + - precursor_charge: Precursor charge + - native_id: Native ID of the spectrum + - sequence: Peptide sequence (if identified) + - ion_annotation: Ion annotations (if available) """🧰 Tools
🪛 Ruff (0.8.2)
711-711: Redefinition of unused
get_dffrom line 675(F811)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/pyOpenMS/pxds/MSSpectrum.pxd(1 hunks)src/pyOpenMS/pyopenms/_dataframes.py(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
- GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
- GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
- GitHub Check: build-and-test (macos-13, xcode, 14.2)
- GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
🔇 Additional comments (1)
src/pyOpenMS/pxds/MSSpectrum.pxd (1)
78-79: Good performance optimization with nogilAdding the
nogilkeyword to the constructors is a useful optimization that will allow these operations to execute in parallel with other Python code by releasing the Global Interpreter Lock (GIL).
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
src/pyOpenMS/pyopenms/_dataframes.py (3)
700-706: Consider checking for valid ion mobility array indexThe current implementation assumes that the first float data array is always the ion mobility data when
containsIMData()returns true. For greater stability, consider retrieving the specific ion mobility array index instead.- df['ion_mobility'] = self.getFloatDataArrays()[0] + im_array_idx, im_unit = self.getIMData() + df['ion_mobility'] = self.getFloatDataArrays()[im_array_idx]
721-726: Improve handling of ion annotationsThe code creates a default array of empty strings with length of only 1 character, which could truncate any ion annotations longer than that. Also, it's better to initialize the array after determining the actual content length.
- ion_annotations = _np.full(cnt, '', dtype='U1') + ion_annotations = [] for sda in self.getStringDataArrays(): if sda.getName() in ['IonNames', 'IonName']: - ion_annotations = [ion.decode() for ion in sda] + ion_annotations = [ion.decode() if isinstance(ion, bytes) else ion for ion in sda] break + if not ion_annotations: + ion_annotations = _np.full(cnt, '', dtype='U1')
717-718: Handle potential empty sequenceThe code creates a numpy array with a potentially empty sequence string, which could result in a dtype of 'U0'. This might cause issues in edge cases.
- df['sequence'] = _np.full(cnt, seq, dtype=f'U{len(seq)}') + df['sequence'] = _np.full(cnt, seq, dtype=f'U{max(1, len(seq))}')
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/pyOpenMS/pyopenms/_dataframes.py(1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
src/pyOpenMS/pyopenms/_dataframes.py (2)
src/openms/include/OpenMS/KERNEL/MSSpectrum.h (10)
getRT(192-192)getMSLevel(230-230)containsIMData(546-546)getFloatDataArrays(257-257)getFloatDataArrays(260-263)getFloatDataArrays(260-260)getDriftTimeUnitAsString(218-218)getStringDataArrays(269-269)getStringDataArrays(272-272)getName(236-236)src/openms/source/KERNEL/MSSpectrum.cpp (16)
getRT(553-556)getRT(553-553)getMSLevel(588-591)getMSLevel(588-588)containsIMData(750-755)containsIMData(750-750)getFloatDataArrays(608-611)getFloatDataArrays(608-608)getDriftTimeUnitAsString(568-571)getDriftTimeUnitAsString(568-568)getStringDataArrays(618-621)getStringDataArrays(618-618)getStringDataArrays(628-631)getStringDataArrays(628-628)getName(598-601)getName(598-598)
⏰ 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 (ubuntu-22.04, clang++, 15)
- GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
- GitHub Check: build-and-test (macos-13, xcode, 14.2)
- GitHub Check: build-and-test (windows-2022, cl.exe, default)
🔇 Additional comments (2)
src/pyOpenMS/pyopenms/_dataframes.py (2)
674-732: Solid implementation of the get_df() methodThe implementation effectively converts MSSpectrum data into a pandas DataFrame with comprehensive metadata handling. I particularly like how it handles special cases such as ion mobility data, precursors, and peptide sequences.
708-710: 🛠️ Refactor suggestionAdd bounds checking before accessing precursors
The code assumes that the first precursor exists when
precsis not empty. It would be better to explicitly check if the list contains elements.- df['precursor_mz'] = _np.full(cnt, precs[0].getMZ() if precs else 0.0, dtype='double') - df['precursor_charge'] = _np.full(cnt, precs[0].getCharge() if precs else 0, dtype='uint16') + df['precursor_mz'] = _np.full(cnt, precs[0].getMZ() if precs and len(precs) > 0 else 0.0, dtype='double') + df['precursor_charge'] = _np.full(cnt, precs[0].getCharge() if precs and len(precs) > 0 else 0, dtype='uint16')Likely an incorrect or invalid review comment.
|
I think you forgot the test. Does this even work? Did you compile pyopenms and test it? |
|
Nope. This is not how cython works. |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (8)
src/pyOpenMS/pyopenms/_dataframes.py (1)
655-661: Consider renaming the “object” parameter and verify proper usage of decoded keys
Using the variable nameobjecthere shadows the built-in Python type. It’s clearer to rename it (e.g.,obj) to avoid confusion. Also ensure that each decoded key (k.decode()) properly matches existing meta values.-def _add_meta_values(df: _pd.DataFrame, object: any) -> _pd.DataFrame: +def _add_meta_values(df: _pd.DataFrame, obj: any) -> _pd.DataFrame: ...src/pyOpenMS/pxds/MSSpectrum.pxd (1)
138-152: Validate new method signatures and imports for metadata & raw data retrieval
Each newly introduced method is useful for spectrum data extraction. Ensure you properly include the necessary C++ headers or forward declarations (e.g., forDataValue), and confirm that concurrency aspects (nogil) are safe for all methods that might access shared state.src/pyOpenMS/addons/MSSpectrum.pyx (6)
5-6: Enhance the docstring with more details about parameters and outputThe current docstring is brief and doesn't provide information about the
export_meta_valuesparameter or what specific metadata fields are included in the returned DataFrame.- def get_df(self, export_meta_values=True): - """Returns a pandas DataFrame with m/z, intensities, and properly typed metadata.""" + def get_df(self, export_meta_values=True): + """Returns a pandas DataFrame with m/z, intensities, and properly typed metadata. + + Parameters + ---------- + export_meta_values : bool, optional + Whether to include metadata values in the DataFrame (default: True) + + Returns + ------- + pandas.DataFrame + DataFrame containing columns for m/z, intensity, retention time, MS level, + native ID, ion mobility, precursor information, peptide sequence, and ion annotations. + If export_meta_values is True, additional metadata fields are included as columns. + """
21-21: Consider using flexible string type for native_idThe fixed-length 'U100' might not be sufficient for all native IDs, potentially truncating long identifiers.
- df['native_id'] = np.full(cnt, self.getNativeID().decode(), dtype='U100') + native_id = self.getNativeID().decode() + df['native_id'] = np.full(cnt, native_id, dtype=f'U{max(len(native_id), 1)}')
34-38: Handle multiple precursors appropriatelyThe current implementation only uses the first precursor. If there are multiple precursors, this could lead to information loss.
precursors = self.getPrecursors() if precursors.size() > 0: precursor = precursors[0] df['precursor_mz'] = np.full(cnt, precursor.getMZ(), dtype=np.float64) df['precursor_charge'] = np.full(cnt, precursor.getCharge(), dtype=np.uint16) + # Optionally add information about multiple precursors if present + if precursors.size() > 1: + df['multi_precursor'] = True + # Store additional precursor information as list or string if needed + precursor_mzs = [precursors[i].getMZ() for i in range(precursors.size())] + df['all_precursor_mzs'] = str(precursor_mzs)
53-62: Optimize ion annotation extractionThe current implementation decodes all strings before determining the maximum length, which is inefficient for large datasets.
- ion_annotations = np.full(cnt, '', dtype='U1') + ion_annotations = np.full(cnt, '', dtype='U1') # Default to empty strings str_arrays = self.getStringDataArrays() for sda in str_arrays: if sda.getName().decode() in ['IonNames', 'IonName']: - decoded = [sda[i].decode() for i in range(sda.size())] - if len(decoded) == cnt: - max_len = max(len(s) for s in decoded) if decoded else 1 - ion_annotations = np.array(decoded, dtype=f"U{max_len}") + if sda.size() == cnt: + # Find max length in one pass to avoid decoding twice + max_len = 1 + decoded = [] + for i in range(sda.size()): + s = sda[i].decode() + decoded.append(s) + max_len = max(max_len, len(s)) + ion_annotations = np.array(decoded, dtype=f"U{max_len}") break
95-97: Add logging for exception handlingThe current exception handling catches all exceptions but doesn't log the error, which could make debugging difficult.
except Exception as e: # Fallback to string representation + import warnings + warnings.warn(f"Error processing meta value '{k_str}': {e}") df[k_str] = np.full(cnt, str(dv.toString().decode()), dtype='object')
43-50: Improve peptide sequence handlingThe current implementation only extracts the sequence from the first hit of the first peptide identification, potentially missing relevant information.
# ====== Peptide Sequence ====== seq = '' pep_ids = self.getPeptideIdentifications() if pep_ids.size() > 0: hits = pep_ids[0].getHits() if hits.size() > 0: seq = hits[0].getSequence().toString().decode() + # Add confidence score if available + if hits[0].metaValueExists(b'score'): + df['sequence_score'] = np.full(cnt, hits[0].getMetaValue(b'score').value(), dtype=np.float64) + # Note if multiple hits are available + if hits.size() > 1: + df['multiple_sequence_hits'] = True df['sequence'] = np.full(cnt, seq, dtype=f"U{len(seq)}" if seq else 'U1')
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/pyOpenMS/addons/MSSpectrum.pyx(1 hunks)src/pyOpenMS/pxds/MSSpectrum.pxd(2 hunks)src/pyOpenMS/pyopenms/_dataframes.py(1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/pyOpenMS/pyopenms/_dataframes.py
663-663: Undefined name DataValue
(F821)
677-677: Undefined name np
(F821)
678-678: Local variable e is assigned to but never used
Remove assignment to unused variable e
(F841)
679-679: Undefined name np
(F821)
⏰ Context from checks skipped due to timeout of 90000ms (5)
- GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
- GitHub Check: build-and-test (windows-2022, cl.exe, default)
- 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 (ubuntu-22.04, clang++, 15)
🔇 Additional comments (1)
src/pyOpenMS/pxds/MSSpectrum.pxd (1)
77-79:Details
✅ Verification successful
Confirm GIL release safety for newly declared methods
Marking the default constructor and copy constructor asnogilcan expose concurrency risks if the constructor interacts with Python objects. Verify that no Python-level functions (e.g., logging, raising Python exceptions) are invoked inside these constructors to ensure thread-safety.
🏁 Script executed:
#!/bin/bash # This script searches for usages of these constructors to confirm they don’t # call Python APIs that might break nogil constraints rg --color=never -A 5 "MSSpectrum()" | grep -i "Py_" rg --color=never -A 5 "MSSpectrum(MSSpectrum &)" | grep -i "Py_"Length of output: 868
GIL safety verified for MSSpectrum constructors
Based on the grep results:
- The default constructor (
MSSpectrum()) shows usage in related.pyxfiles (e.g., viaMSSpectrum.__new__(MSSpectrum)) but no direct Python C API (e.g.,Py_…) calls are detected.- The copy constructor (
MSSpectrum(MSSpectrum &)) produced no output indicating any invocations of Python-level functions.These findings suggest that marking these constructors as
nogildoes not introduce thread-safety risks with respect to Python API usage. Please continue to monitor any future changes that might inadvertently introduce Python-level interactions.
|
Pandas imports missing. Pandas needs to be added to required libraries at build time in cmake. In general I have to say I still do not like the idea of requiring pandas so deep as dependency just for beginners not being able to call pd.DataFrame(dict_of_np_cols) on their own. But fine.. not worse than before. Are there tests from the old python module already? If not they should be added now at least. |
@jpfeuffer |
…pendency-free metadata export && change np into _np
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
src/pyOpenMS/addons/MSSpectrum.pyx (2)
38-47:⚠️ Potential issueUse signed integer for precursor charge
Precursor charges can be negative in mass spectrometry, so you should use a signed integer type instead of an unsigned one.
- data_dict['precursor_charge'] = _np.full(cnt, precursor.getCharge(), dtype=_np.uint16) + data_dict['precursor_charge'] = _np.full(cnt, precursor.getCharge(), dtype=_np.int16)- data_dict['precursor_charge'] = _np.full(cnt, 0, dtype=_np.uint16) + data_dict['precursor_charge'] = _np.full(cnt, 0, dtype=_np.int16)
21-37: 🛠️ Refactor suggestionUse getIMData() for ion mobility identification
Your current approach searches for ion mobility by name, which is fragile. Use the existing
getIMData()method which returns the exact index of ion mobility data.- # Ion Mobility - if self.containsIMData(): - im_arrays = self.getFloatDataArrays() - im_index = -1 - for i in range(im_arrays.size()): - name = im_arrays[i].getName().decode().lower() - if name in ['ion_mobility', 'drift_time', 'mobility']: - im_index = i - break - - if im_index >= 0 and im_arrays[im_index].size() == cnt: - data_dict['ion_mobility'] = _np.array([im_arrays[im_index][i] for i in range(cnt)]) - data_dict['ion_mobility_unit'] = _np.full(cnt, self.getDriftTimeUnitAsString().decode(), dtype='U50') - else: - data_dict['ion_mobility'] = _np.full(cnt, _np.nan, dtype=_np.float64) - data_dict['ion_mobility_unit'] = _np.full(cnt, '', dtype='U1') + # Ion Mobility + if self.containsIMData(): + im_arrays = self.getFloatDataArrays() + im_index, im_unit = self.getIMData() # Get the correct index of IM data + if im_index < im_arrays.size() and im_arrays[im_index].size() == cnt: + data_dict['ion_mobility'] = _np.array([im_arrays[im_index][i] for i in range(cnt)]) + data_dict['ion_mobility_unit'] = _np.full(cnt, self.getDriftTimeUnitAsString().decode(), dtype='U50') + else: + data_dict['ion_mobility'] = _np.full(cnt, _np.nan, dtype=_np.float64) + data_dict['ion_mobility_unit'] = _np.full(cnt, '', dtype='U1')
🧹 Nitpick comments (2)
src/pyOpenMS/addons/MSSpectrum.pyx (2)
5-6: Function docstring needs improvementThe docstring is too brief and missing important details like parameter descriptions and return type information.
- def get_data_dict(self, export_meta_values=True): - """Returns a dictionary of NumPy arrays with m/z, intensities, and metadata""" + def get_data_dict(self, export_meta_values=True): + """ + Returns a dictionary of NumPy arrays with m/z, intensities, and metadata. + + Args: + export_meta_values (bool): Include meta values if True (default). + + Returns: + dict: Dictionary with keys including 'mz', 'intensity', 'rt', 'ms_level', + 'native_id', and potentially 'ion_mobility', 'precursor_mz', etc. + """
57-78: Improve exception handlingThe current exception handler catches all exceptions without distinguishing between different error types, which could mask real issues.
- except: + except Exception as e: + # Log or handle specific exceptions more gracefully data_dict[k_str] = _np.full(cnt, str(dv.toString().decode()), dtype='object')
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/pyOpenMS/addons/MSSpectrum.pyx(6 hunks)src/pyOpenMS/pxds/MSSpectrum.pxd(2 hunks)src/pyOpenMS/pyopenms/_dataframes.py(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/pyOpenMS/pxds/MSSpectrum.pxd
⏰ 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 (windows-2022, cl.exe, default)
- 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)
🔇 Additional comments (8)
src/pyOpenMS/addons/MSSpectrum.pyx (6)
1-3: Good addition of explicit importsThe imports of DataValue and numpy as _np are clear and follow the project's naming conventions.
7-19: Well-structured core data handlingThe core spectrum data handling is clean and well-implemented, using NumPy's efficient array operations.
48-56: Nicely handled peptide sequence extractionThe peptide sequence extraction logic is robust and correctly handles empty sequences.
82-155: Good namespace consistency updatesThe changes to use
_npinstead ofnpimprove consistency across the codebase.
156-270: No issues in the remaining implementationThe remaining changes in the file are consistent with the namespace updates and maintain the existing functionality.
271-279: Well-implemented getIMData methodThis existing method correctly returns ion mobility data position and unit, and should be used in your ion mobility handling code as suggested earlier.
src/pyOpenMS/pyopenms/_dataframes.py (2)
19-19: Good addition of DataValue importThe explicit import of DataValue is appropriate for the enhancements to metadata handling.
657-680: Improved metadata handlingThe updated _add_meta_values function now properly handles different data types using DataValue's valueType method, making the code more robust.
The implementation correctly:
- Retrieves metadata values with getMetaValue
- Checks the value type
- Applies appropriate conversions based on the value type
- Handles exceptions gracefully
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py (1)
9-10: Remove unused variable and unnecessary whitespace.The
dirnamevariable is assigned but never used in the code. This was also flagged by the static analysis tool.- dirname = os.path.dirname(os.path.abspath(__file__)) -🧰 Tools
🪛 Ruff (0.8.2)
9-9: Local variable
dirnameis assigned to but never usedRemove assignment to unused variable
dirname(F841)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py(1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py
9-9: Local variable dirname is assigned to but never used
Remove assignment to unused variable dirname
(F841)
⏰ Context from checks skipped due to timeout of 90000ms (5)
- GitHub Check: build-and-test (windows-2022, cl.exe, default)
- GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
- GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
- GitHub Check: build-and-test (macos-13, xcode, 14.2)
- GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
🔇 Additional comments (7)
src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py (7)
4-5: LGTM: Appropriate imports added for the new test methods.The imports for
Precursor,PeptideIdentification,PeptideHit,AASequencefrompyopenmsandnumpyare correctly added to support the new test methods.
11-25: LGTM: Well-structured test for ion mobility functionality.The test correctly verifies that ion mobility data is properly handled by the
get_data_dict()method. The test creates a float data array for ion mobility, sets the drift time unit, and then verifies both the value and unit are correctly retrieved.
26-36: LGTM: Comprehensive test for precursor information.The test effectively verifies that precursor m/z and charge values are correctly exposed in the dictionary returned by
get_data_dict().
37-47: LGTM: Good test coverage for peptide identifications.The test properly verifies that peptide sequence information from peptide identifications is correctly included in the data dictionary.
48-60: LGTM: Thorough metadata handling test.The test effectively verifies that different types of metadata (integer, float, string, boolean) are correctly stored and retrieved.
61-66: LGTM: Edge case testing for empty spectrum.Good practice to test edge cases like empty spectra. The test verifies both empty m/z array and NaN precursor m/z for an empty spectrum.
67-71: LGTM: Test for optional parameter functionality.The test correctly verifies that the
export_meta_valuesparameter works as expected when set toFalse.
@jcharkow @singjc would this change cause issues to the way we currently generate dataframes for pyopenms-viz? BTW if possible I would like to see the pandas dependency go in favor of the dictionary. |
For pyopenms_viz, this would not break the core packages but it would break our tutorials and our claims that pandas dataframes can be directly fetched from pyopenms. If it is not too much of a burden to incorporate pandas dataframes into the build I would favour that as I believe a few other data structures also have conversion to pandas and I envision more data structures in the future supporting this. Possibly we can copy what pyarrow does? For pyarrow, pandas is not a dependency however it does have a |
There was a problem hiding this comment.
Changes look reasonable to me however I have not tested it locally. @ChandraDevs1 would be good to look at test datasets (e.g. from the pyopenms_viz tutorials, pyopenms tutorials) and ensure that the new functions work as the old functions did. Adding screenshots of the output here from your tests would be an asset.
From my end it would be good to have pandas integration as I mentioned above, even if it is not a dependency.
|
This definitely needs to be tested. |
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
src/pyOpenMS/addons/MSSpectrum.pyx (2)
39-48: Use signed integer for precursor chargePrecursor charges can be negative in some mass spectrometry experiments, so
np.uint16might not be appropriate.- data_dict['precursor_charge'] = _np.full(cnt, precursor.getCharge(), dtype=_np.uint16) + data_dict['precursor_charge'] = _np.full(cnt, precursor.getCharge(), dtype=_np.int16)
5-72: Add unit tests for get_data_dict methodNo unit tests were found for this new method. Please add comprehensive tests to validate functionality with various input scenarios.
🧹 Nitpick comments (5)
src/pyOpenMS/pyopenms/_dataframes.py (1)
684-690: Usefrom ewhen re-raising ImportError.Modify the exception handling to include the original exception when re-raising the ImportError, following Python best practices.
try: import pandas as pd except ImportError: - raise ImportError("The 'pandas' package is required to use this function.") + raise ImportError("The 'pandas' package is required to use this function.") from None🧰 Tools
🪛 Ruff (0.8.2)
689-689: Within an
exceptclause, raise exceptions withraise ... from errorraise ... from Noneto distinguish them from errors in exception handling(B904)
src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py (2)
4-5: Remove unused imports.Several imports are added but never used in the code. Clean up the imports to include only what's needed.
-from pyopenms import Precursor, PeptideIdentification, PeptideHit, AASequence , DriftTimeUnit +from pyopenms import Precursor, DriftTimeUnit import numpy as np🧰 Tools
🪛 Ruff (0.8.2)
4-4:
pyopenms.PeptideIdentificationimported but unusedRemove unused import
(F401)
4-4:
pyopenms.PeptideHitimported but unusedRemove unused import
(F401)
4-4:
pyopenms.AASequenceimported but unusedRemove unused import
(F401)
9-10: Remove unused variable.The
dirnamevariable is assigned but never used. Remove it if it's not needed.def setUp(self): - dirname = os.path.dirname(os.path.abspath(__file__)) + pass🧰 Tools
🪛 Ruff (0.8.2)
10-10: Local variable
dirnameis assigned to but never usedRemove assignment to unused variable
dirname(F841)
src/pyOpenMS/addons/MSSpectrum.pyx (2)
21-38: Fix indentation in ion mobility array constructionThe ion mobility array code has inconsistent indentation at lines 27-28, which should be fixed for readability and to avoid potential errors.
if im_index >= 0 and im_index < im_arrays.size(): - data_dict['ion_mobility'] = _np.array( - [im_arrays[im_index][i] for i in range(cnt)] - ) + data_dict['ion_mobility'] = _np.array( + [im_arrays[im_index][i] for i in range(cnt)] + )
49-70: Improve exception handling in metadata processingThe current implementation uses a broad try-except block without specifying which exceptions to catch. This can hide unexpected errors and make debugging difficult.
try: if dv.valueType() == DataValue.INT_VALUE: data_dict[k_str] = _np.full(cnt, dv.value(), dtype=_np.int32) elif dv.valueType() == DataValue.DOUBLE_VALUE: data_dict[k_str] = _np.full(cnt, dv.value(), dtype=_np.float64) elif dv.valueType() == DataValue.STRING_VALUE: s = dv.value() data_dict[k_str] = _np.full(cnt, s, dtype=f"U{len(s)}") elif dv.valueType() == DataValue.BOOL_VALUE: data_dict[k_str] = _np.full(cnt, dv.value(), dtype=bool) - except: + except Exception as e: + # Fall back to string representation when value conversion fails data_dict[k_str] = _np.full(cnt, str(dv.toString().decode()), dtype='object')
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
src/pyOpenMS/addons/MSSpectrum.pyx(6 hunks)src/pyOpenMS/converters/__init__.py(1 hunks)src/pyOpenMS/converters/pandas_utils.py(1 hunks)src/pyOpenMS/pxds/MSSpectrum.pxd(2 hunks)src/pyOpenMS/pyopenms/_dataframes.py(2 hunks)src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/pyOpenMS/pxds/MSSpectrum.pxd
🧰 Additional context used
🧠 Learnings (1)
src/pyOpenMS/addons/MSSpectrum.pyx (1)
Learnt from: jpfeuffer
PR: OpenMS/OpenMS#7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:38-38
Timestamp: 2025-04-07T21:15:07.674Z
Learning: In mass spectrometry data, precursor charges can be negative, so signed integer types (like np.int16) should be used instead of unsigned integers (like np.uint16) when storing charge values.
🧬 Code Graph Analysis (1)
src/pyOpenMS/converters/__init__.py (1)
src/pyOpenMS/converters/pandas_utils.py (1)
to_dataframe(1-21)
🪛 Ruff (0.8.2)
src/pyOpenMS/pyopenms/_dataframes.py
689-689: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py
4-4: pyopenms.PeptideIdentification imported but unused
Remove unused import
(F401)
4-4: pyopenms.PeptideHit imported but unused
Remove unused import
(F401)
4-4: pyopenms.AASequence imported but unused
Remove unused import
(F401)
10-10: Local variable dirname is assigned to but never used
Remove assignment to unused variable dirname
(F841)
⏰ 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, default)
🔇 Additional comments (13)
src/pyOpenMS/converters/__init__.py (1)
3-5: Good addition to the public API.The changes correctly expose the
to_dataframefunction in the public API through the__all__list. This enables users to easily import and use this functionality.src/pyOpenMS/converters/pandas_utils.py (1)
1-21: Well-implemented converter with proper error handling.The function is clean, focused, and handles the case where pandas is not installed with an appropriate error message and installation instructions. The docstring is informative and includes parameter types, return types, and exception information.
src/pyOpenMS/pyopenms/_dataframes.py (2)
19-19: Good addition of DataValue import.This import enables more sophisticated type checking in the
_add_meta_valuesfunction.
657-681: Improved metadata type handling.The updated implementation properly handles different types of metadata values using the
DataValueclass, with appropriate fallbacks for exceptional cases. This is more robust than the previous direct conversion approach.src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py (1)
21-21:Details
✅ Verification successful
Verify enum usage.
The DriftTimeUnit.VSSC might not exist according to a previous comment. Please confirm this is the correct enum value.
🏁 Script executed:
#!/bin/bash # Check available DriftTimeUnit values rg -A 10 "DriftTimeUnit" --glob "src/pyOpenMS/pxds/*.pxd"Length of output: 2679
Enum value confirmed: DriftTimeUnit.VSSC exists
Based on the output from the verification script, the enum defined in
src/pyOpenMS/pxds/IMTypes.pxdclearly includesVSSCas a valid member. The usage in the test file (spec.setDriftTimeUnit(DriftTimeUnit.VSSC)) is therefore correct and requires no modification.src/pyOpenMS/addons/MSSpectrum.pyx (8)
1-3: Code imports NumPy with '_np' aliasThe code imports NumPy with the alias
_npinstead of the more commonnp. This is a good practice in Cython modules to avoid potential namespace conflicts.
5-19: LGTM: Well-structured dictionary initialization with proper typingThe new
get_data_dictmethod efficiently retrieves peak data and initializes a dictionary with appropriate NumPy data types for each field, maintaining type consistency across mass spectrometry data.
5-72: Add get_df() method to convert dictionary to DataFrameThe PR objectives mention adding a
get_df()method to convert mass spectrometry data to a pandas DataFrame, but this method is missing from the implementation.Please add the
get_df()method that uses the newget_data_dict()method to create a pandas DataFrame:def get_df(self, export_meta_values=True): """Returns a pandas DataFrame with m/z, intensities, and properly typed metadata.""" import pandas as pd return pd.DataFrame(self.get_data_dict(export_meta_values))This would fulfill the main objective of the PR: "Add DataFrame export via get_df()".
85-86: Namespace change from 'np' to '_np'Updated NumPy namespace from
npto_npfor consistency with the import statement.
109-110: Namespace change from 'np' to '_np'Updated NumPy namespace from
npto_npfor consistency with the import statement.
132-135: Namespace change from 'np' to '_np'Updated NumPy namespace from
npto_npfor consistency with the import statement.
163-169: Namespace change from 'np' to '_np'Updated NumPy namespace from
npto_npfor consistency with the import statement.
176-198: Method signature updated to use '_np'Method signature updated to use the
_npnamespace for NumPy array declarations, maintaining consistency with the import statement.
| def test_ion_mobility(self): | ||
| spec = pyopenms.MSSpectrum() | ||
| spec.set_peaks(([100.0], [10.0])) | ||
|
|
||
| # Add ion mobility array | ||
| fda = pyopenms.FloatDataArray() | ||
| fda.setName("Ion Mobility") | ||
| fda.push_back(0.5) | ||
| spec.setFloatDataArrays([fda]) | ||
| spec.setDriftTimeUnit(DriftTimeUnit.VSSC) | ||
|
|
||
| data = spec.get_data_dict() | ||
| self.assertTrue(np.array_equal(data["ion_mobility"], [0.5])) | ||
| self.assertEqual(data["ion_mobility_unit"][0], "VSSC") | ||
|
|
||
| def test_precursors(self): | ||
| spec = pyopenms.MSSpectrum() | ||
| p = Precursor() | ||
| p.setMZ(300.0) | ||
| p.setCharge(2) | ||
| spec.setPrecursors([p]) | ||
|
|
||
| data = spec.get_data_dict() | ||
| self.assertEqual(data["precursor_mz"][0], 300.0) | ||
| self.assertEqual(data["precursor_charge"][0], 2) | ||
|
|
||
| def test_metadata_handling(self): | ||
| spec = pyopenms.MSSpectrum() | ||
| spec.setMetaValue("int_val", 5) | ||
| spec.setMetaValue("float_val", 3.14) | ||
| spec.setMetaValue("str_val", "test") | ||
| spec.setMetaValue("bool_val", True) | ||
|
|
||
| data = spec.get_data_dict() | ||
| self.assertEqual(data["int_val"][0], 5) | ||
| self.assertEqual(data["float_val"][0], 3.14) | ||
| self.assertEqual(data["str_val"][0], "test") | ||
| self.assertEqual(data["bool_val"][0], True) | ||
|
|
||
| def test_empty_spectrum(self): | ||
| spec = pyopenms.MSSpectrum() | ||
| data = spec.get_data_dict() | ||
| self.assertEqual(len(data["mz"]), 0) | ||
| self.assertEqual(data["precursor_mz"][0], np.nan) | ||
|
|
||
| def test_export_meta_values_flag(self): | ||
| spec = pyopenms.MSSpectrum() | ||
| spec.setMetaValue(b"test", 42) | ||
| data = spec.get_data_dict(export_meta_values=False) | ||
| self.assertNotIn("test", data) |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Add tests for the get_df() method.
While you've thoroughly tested the get_data_dict() method, there are no tests for the related get_df() functionality mentioned in the PR description. Consider adding tests that verify the proper conversion from the dictionary to a pandas DataFrame.
🏁 Script executed:
#!/bin/bash
# Check implementation of get_df for MSSpectrum
# Find where get_df might be implemented
echo "Checking for get_df() method in MSSpectrum:"
rg -A 2 "def get_df" --glob "src/pyOpenMS/**/*.pyx" --glob "src/pyOpenMS/**/*.py"
# Look for import of to_dataframe
echo "Checking for to_dataframe imports:"
rg "from.*to_dataframe" --glob "src/pyOpenMS/**/*.pyx" --glob "src/pyOpenMS/**/*.py"Length of output: 1509
Action Required: Add Tests for the get_df() Method
While the get_data_dict() functionality is well-covered, the get_df() method—which converts spectrum data into a pandas DataFrame—is not yet exercised by any unit tests. Since the method is implemented (see its presence in src/pyOpenMS/pyopenms/_dataframes.py), please add tests in src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py (or an appropriate test file) that verify:
- The DataFrame object is correctly created from an MSSpectrum instance.
- All expected columns are present and correctly reflect the spectrum's peaks, meta values, and other associated data.
- The conversion handles various spectrum states (e.g., empty spectrum, spectrum with meta values) similarly to what is expected from
get_data_dict().
This will ensure that the get_df() functionality remains robust against future changes.
This commit fixes the implementation of get_df() and get_data_dict() methods for MSSpectrum, addressing issue OpenMS#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 OpenMS#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]>
- 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]>
…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]>
- 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]>
- Add get_df_columns() method to discover available columns - Add columns parameter to get_df() for selective export - Support custom data arrays via prefixed names: - float_array:<name>, int_array:<name>, string_array:<name> - Keep ion_mobility and ion_annotation as aliases for default arrays - Add comprehensive tests for column selection feature 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
…atogram - Standardize column naming to lowercase snake_case across all DataFrame exports: - RT → rt, time → rt, inty → intensity - mzarray → mz_array, intarray → intensity_array - IM → ion_mobility, RTstart/RTend → rt_start/rt_end - MZstart/MZend → mz_start/mz_end - Add Cython-level get_data_dict() and get_df_columns() to MSChromatogram following MSSpectrum pattern for pandas-optional access with column selection - Add get_data_mv() to IntegerDataArray for zero-copy memory view access (consistency with FloatDataArray API) - Update tests for new column names 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
|
Merged via other PR |

Description
Added
get_df()method toMSSpectrumclass to enable direct conversion of mass spectrometry data to pandas DataFrames. This implementation:Resolves #7966
Checklist
MSSpectrum.pxdand corresponding wrappersrc/tests/class_tests/spectrum_test.pySummary by CodeRabbit
New Features
Bug Fixes