Skip to content

[Feature] Export ion annotations for MSSpectrum DataFrame - #7489

Merged
timosachsenberg merged 5 commits into
OpenMS:developfrom
axelwalter:spectrum-df-ion-annotations
Jun 17, 2024
Merged

timosachsenberg merged 5 commits into
OpenMS:developfrom
axelwalter:spectrum-df-ion-annotations

Conversation

@axelwalter

@axelwalter axelwalter commented May 13, 2024 •

Copy link
Copy Markdown
Collaborator

User description

Description

Export ion annotations for MSSpectrum DataFrame. This information is required for plotting of mirror spectra.

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

How can I get additional information on failed tests during CI

Click to expand If your PR is failing you can check out

Advanced commands (admins / reviewer only)

Click to expand
  • /reformat (experimental) applies the clang-format style changes as additional commit. Note: your branch must have a different name (e.g., yourrepo:feature/XYZ) than the receiving branch (e.g., OpenMS:develop). Otherwise, reformat fails to push.
  • setting the label "NoJenkins" will skip tests for this PR on jenkins (saves resources e.g., on edits that do not affect tests)
  • commenting with rebuild jenkins will retrigger Jenkins-based CI builds

⚠️ Note: Once you opened a PR try to minimize the number of pushes to it as every push will trigger CI (automated builds and test) and is rather heavy on our infrastructure (e.g., if several pushes per day are performed).


PR Type

Enhancement, Tests


Description

  • Enhanced the _MSSpectrumDF class to export ion annotations in the DataFrame.
  • Removed export_ion_mobility and export_peptide_identifications arguments from the get_df method.
  • Updated the DataFrame to include a new column ion_annotation for ion annotations.
  • Added unit tests to verify the inclusion of ion annotations in the DataFrame.

Changes walkthrough 📝

Relevant files
Enhancement
_dataframes.py
Enhance MSSpectrum DataFrame export with ion annotations 

src/pyOpenMS/pyopenms/_dataframes.py

  • Added export of ion annotations to DataFrame.
  • Removed export_ion_mobility and export_peptide_identifications
    arguments.
  • Updated DataFrame columns to include ion_annotation.
  • +20/-24 
    Tests
    test000.py
    Add unit tests for ion annotations in DataFrame                   

    src/pyOpenMS/tests/unittests/test000.py

  • Added unit tests for ion annotations in DataFrame.
  • Updated expected DataFrame shape and content.
  • +10/-1   

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    Comment thread src/pyOpenMS/pyopenms/_dataframes.py Resolved
    Comment thread src/pyOpenMS/tests/unittests/test000.py Resolved
    Comment thread src/pyOpenMS/tests/unittests/test000.py Resolved
    @timosachsenberg

    Copy link
    Copy Markdown
    Contributor

    looks good!
    what would be really cool (right @Arslan-Siraj and @matteopilz ?) if we could also plot spectra with peak annotations in PeptideHits:
    https://github.com/OpenMS/OpenMS/blob/develop/src/pyOpenMS/pxds/PeptideHit.pxd#L42
    which gives you https://github.com/OpenMS/OpenMS/blob/develop/src/pyOpenMS/pxds/PeptideHit.pxd#L63

    I think we don't have a function annotate_spectrum_with_peak_annotations or similar name, yet. It could take a MSSpectrum and a vector of PeakAnnotations and fill the string data array ?@matteopilz or @Arslan-Siraj

    Or how do we currently plot this e.g., in NuXL web app?

    @timosachsenberg

    Copy link
    Copy Markdown
    Contributor

    example from Wout
    image

    @qodo-code-review

    Copy link
    Copy Markdown
    Contributor

    PR-Agent was enabled for this repository. To continue using it, please link your git user with your CodiumAI identity here.

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review [1-5] 3
    🧪 Relevant tests Yes
    🔒 Security concerns No
    ⚡ Key issues to review Possible Bug:
    The dtype for 'ion_annotation' in the DataFrame is initialized with 'U1', which might not be sufficient for longer ion names. Consider initializing it with a larger size or dynamically determining the size based on the maximum length of the ion names.
    Data Consistency:
    The removal of parameters such as 'export_ion_mobility' and 'export_peptide_identifications' from the 'get_df' method simplifies the function but reduces the flexibility of the method. Ensure that this change aligns with the intended use cases and that all necessary data is still being exported.
    Performance Concern:
    The loop through 'self.getStringDataArrays()' and the conditional check for 'IonNames' could be inefficient if there are many data arrays. Consider optimizing this section if performance issues arise.

    @qodo-code-review

    Copy link
    Copy Markdown
    Contributor

    PR-Agent was enabled for this repository. To continue using it, please link your git user with your CodiumAI identity here.

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Possible bug
    Handle cases where self.getStringDataArrays() returns an empty list to avoid potential index errors

    The get_df method should handle cases where self.getStringDataArrays() returns an empty
    list to avoid potential index errors.

    src/pyOpenMS/pyopenms/_dataframes.py [704]

    -for sda in self.getStringDataArrays():
    +string_data_arrays = self.getStringDataArrays()
    +if string_data_arrays:
    +    for sda in string_data_arrays:
     
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    Why: This suggestion addresses a potential bug that could lead to index errors, making it a crucial improvement for error handling and robustness.

    9
    Possible issue
    Dynamically set the dtype for the ion_annotations array based on the maximum length of the ion names

    The dtype for the ion_annotations array is set to 'U1', which may not be sufficient for
    longer ion names. It would be better to dynamically determine the maximum length of the
    ion names and set the dtype accordingly.

    src/pyOpenMS/pyopenms/_dataframes.py [703]

    -ion_annotations = _np.full(cnt, '', dtype=_np.dtype('U1'))
    +ion_annotations = _np.full(cnt, '', dtype=_np.dtype(f'U{max(len(ion) for ion in sda)}'))
     
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: The suggestion correctly identifies a potential issue with the dtype size for ion_annotations and proposes a dynamic solution that prevents data truncation.

    8
    Set a default dtype length for the sequence array to handle cases where no peptide sequences are found

    The dtype for the sequence array is set based on the length of the first peptide sequence
    found. If no peptide sequences are found, this will result in an empty dtype. Consider
    setting a default dtype length to handle cases where no sequences are found.

    src/pyOpenMS/pyopenms/_dataframes.py [700]

    -df['sequence'] = _np.full(cnt, seq, dtype=_np.dtype(f'U{len(seq)}'))
    +df['sequence'] = _np.full(cnt, seq, dtype=_np.dtype(f'U{max(len(seq), 1)}'))
     
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: This is a valid improvement to handle cases where no sequences are found, ensuring that the dtype does not become invalid.

    7
    Test enhancement
    Add a test case to verify the shape of the DataFrame when export_meta_values is set to False

    The test case for get_df should also verify the shape of the DataFrame when
    export_meta_values is set to False to ensure that the function behaves correctly under
    different conditions.

    src/pyOpenMS/tests/unittests/test000.py [2885]

    -df = spec.get_df()
    +df = spec.get_df(export_meta_values=False)
    +assert df.shape == (2, 10)
    +df = spec.get_df(export_meta_values=True)
     
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Adding this test case would improve the robustness of the testing by checking the function's behavior under different parameter settings.

    6

    @timosachsenberg
    timosachsenberg merged commit 5cdd58c into OpenMS:develop Jun 17, 2024
    timosachsenberg added a commit that referenced this pull request Dec 5, 2025
    Adds support for extracting ion annotations from StringDataArray named
    'IonNames'. This feature was originally added by Axel Walter in PR #7489
    for spectral library work.
    
    The ion_annotation column contains per-peak annotation strings like
    "y1", "b2", "y3-H2O", etc. that are populated by tools like
    TheoreticalSpectrumGenerator.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude <[email protected]>
    poshul pushed a commit that referenced this pull request Dec 6, 2025
    * Added get_df() Dataframe
    
    * expose the get_df()
    
    * Remove duplicate get_df implementation
    
    * Add metadata method declarations and docstrings
    
    * Fix metadata handling with type-safe DataValue unwrapping
    
    * Remove redundant MSSpectrumDF subclass after Cython integration
    
    * removed getpeaks()
    
    * fixes the issue as suggested by CodeRabbit
    
    * refactor(MSSpectrum): Replace pandas DataFrame with NumPy dict for dependency-free metadata export && change np into _np
    
    * added unit test
    
    * Updated the Code and also added tests
    
    * Fix MSSpectrum.get_df() implementation for pyOpenMS
    
    This commit fixes the implementation of get_df() and get_data_dict() methods
    for MSSpectrum, addressing issue #7966.
    
    Key changes:
    
    1. MSSpectrum.pxd: Removed incorrect C++ method declarations (DataFrame get_df()
       and void get_data_dict()) - these methods are implemented in Python/Cython,
       not in C++.
    
    2. MSSpectrum.pyx addon:
       - Removed incorrect 'cdef class MSSpectrum:' declaration
       - Fixed get_data_dict() to use Python type introspection instead of
         Cython cdef DataValue (which doesn't work in def methods)
       - Changed precursor_charge dtype to int16 (can be negative)
       - Improved documentation and code formatting
    
    3. _dataframes.py:
       - Added _MSSpectrumDF wrapper class that provides get_df() method
       - get_df() calls get_data_dict() and converts to pandas DataFrame
       - Added MSSpectrum and PeakSpectrum aliases for the DF wrapper class
       - Follows same pattern as _MSChromatogramDF
    
    4. Tests:
       - Comprehensive tests for get_data_dict() covering basic spectra,
         ion mobility, precursors, meta values, empty spectra
       - Tests for get_df() DataFrame export functionality
       - Fixed NaN comparison issues (use np.isnan instead of ==)
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude <[email protected]>
    
    * Add ion_annotation column to MSSpectrum.get_data_dict()
    
    Adds support for extracting ion annotations from StringDataArray named
    'IonNames'. This feature was originally added by Axel Walter in PR #7489
    for spectral library work.
    
    The ion_annotation column contains per-peak annotation strings like
    "y1", "b2", "y3-H2O", etc. that are populated by tools like
    TheoreticalSpectrumGenerator.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude <[email protected]>
    
    * Fix MSSpectrum.get_data_dict() Cython issues and tests
    
    - 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__ to data array classes for Pythonic API
    
    - 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]>
    
    * Remove redundant to_dataframe/to_pandas helper functions
    
    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]>
    
    * Fix _add_meta_values to handle native Python types from getMetaValue()
    
    - 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]>
    
    ---------
    
    Co-authored-by: ChandraDevs1 <[email protected]>
    Co-authored-by: Claude <[email protected]>
    timosachsenberg added a commit that referenced this pull request Dec 7, 2025
    …types (#8436)
    
    * Added get_df() Dataframe
    
    * expose the get_df()
    
    * Remove duplicate get_df implementation
    
    * Add metadata method declarations and docstrings
    
    * Fix metadata handling with type-safe DataValue unwrapping
    
    * Remove redundant MSSpectrumDF subclass after Cython integration
    
    * removed getpeaks()
    
    * fixes the issue as suggested by CodeRabbit
    
    * refactor(MSSpectrum): Replace pandas DataFrame with NumPy dict for dependency-free metadata export && change np into _np
    
    * added unit test
    
    * Updated the Code and also added tests
    
    * Fix MSSpectrum.get_df() implementation for pyOpenMS
    
    This commit fixes the implementation of get_df() and get_data_dict() methods
    for MSSpectrum, addressing issue #7966.
    
    Key changes:
    
    1. MSSpectrum.pxd: Removed incorrect C++ method declarations (DataFrame get_df()
       and void get_data_dict()) - these methods are implemented in Python/Cython,
       not in C++.
    
    2. MSSpectrum.pyx addon:
       - Removed incorrect 'cdef class MSSpectrum:' declaration
       - Fixed get_data_dict() to use Python type introspection instead of
         Cython cdef DataValue (which doesn't work in def methods)
       - Changed precursor_charge dtype to int16 (can be negative)
       - Improved documentation and code formatting
    
    3. _dataframes.py:
       - Added _MSSpectrumDF wrapper class that provides get_df() method
       - get_df() calls get_data_dict() and converts to pandas DataFrame
       - Added MSSpectrum and PeakSpectrum aliases for the DF wrapper class
       - Follows same pattern as _MSChromatogramDF
    
    4. Tests:
       - Comprehensive tests for get_data_dict() covering basic spectra,
         ion mobility, precursors, meta values, empty spectra
       - Tests for get_df() DataFrame export functionality
       - Fixed NaN comparison issues (use np.isnan instead of ==)
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude <[email protected]>
    
    * Add ion_annotation column to MSSpectrum.get_data_dict()
    
    Adds support for extracting ion annotations from StringDataArray named
    'IonNames'. This feature was originally added by Axel Walter in PR #7489
    for spectral library work.
    
    The ion_annotation column contains per-peak annotation strings like
    "y1", "b2", "y3-H2O", etc. that are populated by tools like
    TheoreticalSpectrumGenerator.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude <[email protected]>
    
    * Fix MSSpectrum.get_data_dict() Cython issues and tests
    
    - 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__ to data array classes for Pythonic API
    
    - 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]>
    
    * Remove redundant to_dataframe/to_pandas helper functions
    
    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]>
    
    * Fix _add_meta_values to handle native Python types from getMetaValue()
    
    - 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 column selection for MSSpectrum/MSChromatogram get_df()
    
    - 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]>
    
    * Standardize DataFrame column names and add get_data_dict() to MSChromatogram
    
    - 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]>
    
    * Add Pythonic methods to Mobilogram and StringDataArray, improve column selection
    
    - Mobilogram: Add __len__, __str__, __repr__, get_df_columns(), get_data_dict()
    - StringDataArray: Add get_data() returning list of Python strings
    - ConsensusMap/FeatureMap: Improve column selection efficiency by pre-filtering
      (skip computation of unused data sources)
    - _dataframes.py: Add Mobilogram DataFrame wrapper class
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude Opus 4.5 <[email protected]>
    
    * Add development patterns documentation to pyOpenMS README
    
    - Document snake_case naming convention for Python-facing names
    - Explain get_data_dict() → get_df() layering pattern for optional pandas
    - Add examples for addon and wrapper implementation
    - Document common Pythonic methods (__len__, __repr__, etc.)
    - Include rebuild instructions for addon changes
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude Opus 4.5 <[email protected]>
    
    * Fix docstring column names and add breaking change to CHANGELOG
    
    - Update get_metadata_df() docstring to show actual lowercase column names
      (rt, mz, quality instead of RT/mz)
    - Add BREAKING change note to CHANGELOG documenting snake_case column rename
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude Opus 4.5 <[email protected]>
    
    * Fix incorrect column name in get_chromatogram_df() example
    
    Change example from columns=['time', 'intensity'] to columns=['rt', 'intensity']
    to match actual column names.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude Opus 4.5 <[email protected]>
    
    ---------
    
    Co-authored-by: ChandraDevs1 <[email protected]>
    Co-authored-by: Claude <[email protected]>
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    2 participants