Repository navigation
pyopenms: make pandas column names consistent between different data types - #8436
Conversation
…pendency-free metadata export && change np into _np
This commit fixes the implementation of get_df() and get_data_dict() methods for MSSpectrum, addressing issue #7966. Key changes: 1. MSSpectrum.pxd: Removed incorrect C++ method declarations (DataFrame get_df() and void get_data_dict()) - these methods are implemented in Python/Cython, not in C++. 2. MSSpectrum.pyx addon: - Removed incorrect 'cdef class MSSpectrum:' declaration - Fixed get_data_dict() to use Python type introspection instead of Cython cdef DataValue (which doesn't work in def methods) - Changed precursor_charge dtype to int16 (can be negative) - Improved documentation and code formatting 3. _dataframes.py: - Added _MSSpectrumDF wrapper class that provides get_df() method - get_df() calls get_data_dict() and converts to pandas DataFrame - Added MSSpectrum and PeakSpectrum aliases for the DF wrapper class - Follows same pattern as _MSChromatogramDF 4. Tests: - Comprehensive tests for get_data_dict() covering basic spectra, ion mobility, precursors, meta values, empty spectra - Tests for get_df() DataFrame export functionality - Fixed NaN comparison issues (use np.isnan instead of ==) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Resolved conflict in _dataframes.py by keeping the improved _MSSpectrumDF implementation at the top of the file (which uses get_data_dict()) and removing the duplicate class from develop. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Adds support for extracting ion annotations from StringDataArray named 'IonNames'. This feature was originally added by Axel Walter in PR #7489 for spectral library work. The ion_annotation column contains per-peak annotation strings like "y1", "b2", "y3-H2O", etc. that are populated by tools like TheoreticalSpectrumGenerator. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
- Change numpy import alias from _np to np (matching autowrap generated code) - Use len() instead of .size() for Python lists returned by autowrap - Use sda.size() for StringDataArray (has .size() method, no __len__) - Fix KDTreeFeatureNode.pxd wrap-doc annotation (add blank comment terminator) - Fix test expectation for DriftTimeUnit string (VSSC -> 1/K0) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
- 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]>
|
Warning Rate limit exceeded@timosachsenberg has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 7 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (3)
WalkthroughAdds selective column export across pyOpenMS: new get_df_columns() helpers and optional columns arguments for get_df/get_data_dict in spectrum, chromatogram, mobilogram, and DataFrame wrappers, enabling restricted exports (meta, ion‑mobility, custom arrays) while keeping previous defaults when no column list is provided. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
src/pyOpenMS/tests/unittests/test_dataframe_columns.py (1)
19-224: Good, comprehensive coverage of MSSpectrum/MSChromatogram column selection pathsThe fixtures and tests exercise default vs “all” discovery, explicit column subsets (including ion mobility, annotations, custom/non‑default columns, and meta values), as well as empty/missing‑precursor edge cases and backward compatibility for
get_df()andexport_meta_values. This is a solid test surface for the new column‑selection behavior and should catch most regressions around MSSpectrum/MSChromatogram dataframe exports.Also applies to: 229-385
src/pyOpenMS/addons/MSSpectrum.pyx (1)
7-81: Column-selection implementation for MSSpectrum looks correct and matches testsThe new
get_df_columnsand extendedget_data_dict(columns=None|list, export_meta_values=...)correctly:
- Enumerate core, precursor, ion mobility, ion annotation, meta, and custom data-array columns, with
'all'exposing non‑default/custom fields viafloat_array:/int_array:/string_array:prefixes.- Restrict computation and export of expensive/optional fields (IM, precursors, annotations, custom arrays, meta) to cases where they are either part of the default set (
columns is None) or explicitly listed incolumns.- Preserve backward compatibility for
get_df()and theexport_meta_valuesflag (as exercised bytest000.pyandTestBackwardCompatibilityintest_dataframe_columns.py), while enabling efficient subset exports for performance‑sensitive code paths.One subtle nuance:
ion_mobility_unitis omitted fromget_df_columns()in default mode but is still emitted byget_data_dict(columns=None)when IM data is present, sospectrum.get_df().columnscan be a (slightly) larger set thanspectrum.get_df_columns(). If you want stricter symmetry between discovery and default export, consider either documenting this explicitly or aligning defaultget_df()to treation_mobility_unitas non‑default as well, in a separate, compatibility‑aware change.Also applies to: 83-310
src/pyOpenMS/pyopenms/_dataframes.py (1)
36-84: MSSpectrum.get_df: column-aware wrapper and legacy fallback are reasonable; consider honoringcolumnsin the fallback pathThe new signature and the
TypeError-guarded call intoget_data_dict(columns=...)provide a clean way to enable column selection while staying compatible with older builds that don’t support thecolumnskeyword. On legacy builds, though, thecolumnsargument is currently ignored (the fallback callsget_data_dict(export_meta_values=...)and returns all columns).To keep behavior consistent even on older builds (at the cost of some extra Python-side filtering), you could filter the DataFrame after the fallback:
- try: - data_dict = self.get_data_dict(columns=columns, export_meta_values=export_meta_values) - except TypeError: - # Fallback for older Cython builds without column selection - data_dict = self.get_data_dict(export_meta_values=export_meta_values) - return _pd.DataFrame(data_dict) + try: + data_dict = self.get_data_dict(columns=columns, export_meta_values=export_meta_values) + except TypeError: + # Fallback for older Cython builds without column selection + data_dict = self.get_data_dict(export_meta_values=export_meta_values) + + df = _pd.DataFrame(data_dict) + if columns is not None: + cols = [c for c in columns if c in df.columns] + df = df[cols] + return dfThis preserves backwards compatibility while making
columnseffective everywhere.Please verify this still matches the intended behavior of the underlying
get_data_dictimplementations on both new and older builds.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/pyOpenMS/addons/MSSpectrum.pyx(2 hunks)src/pyOpenMS/pyopenms/_dataframes.py(11 hunks)src/pyOpenMS/tests/unittests/test000.py(2 hunks)src/pyOpenMS/tests/unittests/test_dataframe_columns.py(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/pyOpenMS/tests/**/*.py
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Write pyOpenMS tests for new Python bindings
Files:
src/pyOpenMS/tests/unittests/test_dataframe_columns.pysrc/pyOpenMS/tests/unittests/test000.py
🧠 Learnings (2)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/tests/**/*.py : Write pyOpenMS tests for new Python bindings
Applied to files:
src/pyOpenMS/tests/unittests/test000.py
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality
Applied to files:
src/pyOpenMS/tests/unittests/test000.py
🧬 Code graph analysis (2)
src/pyOpenMS/tests/unittests/test_dataframe_columns.py (1)
src/pyOpenMS/pyopenms/_dataframes.py (9)
get_df_columns(101-135)get_df_columns(310-343)get_df_columns(510-532)get_df_columns(951-991)get_df(36-84)get_df(241-269)get_df(363-471)get_df(534-578)get_df(993-1101)
src/pyOpenMS/tests/unittests/test000.py (2)
src/pyOpenMS/extra_includes/python_ms_data_consumer.hpp (2)
chrom(67-78)chrom(67-67)src/pyOpenMS/pyopenms/_dataframes.py (6)
get_df(36-84)get_df(241-269)get_df(363-471)get_df(534-578)get_df(993-1101)get_chromatogram_df(1149-1176)
🪛 GitHub Check: CodeFactor
src/pyOpenMS/pyopenms/_dataframes.py
[notice] 363-471: src/pyOpenMS/pyopenms/_dataframes.py#L363-L471
Complex Method
[notice] 363-471: src/pyOpenMS/pyopenms/_dataframes.py#L363-L471
Complex Method
🪛 Ruff (0.14.7)
src/pyOpenMS/pyopenms/_dataframes.py
101-101: Unused method argument: columns
(ARG002)
534-534: Do not use mutable data structures for argument defaults
Replace with None; initialize within function
(B006)
1098-1098: Do not catch blind exception: Exception
(BLE001)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (20)
- GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
- GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
- GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
- GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
- GitHub Check: build-lnx-arm
- GitHub Check: build-win
- GitHub Check: build-lnx
- GitHub Check: build-macos-arm
- GitHub Check: cppcheck-test
- GitHub Check: build-and-test (macos-15-intel, xcode, 16.0.0)
- GitHub Check: build-lnx-arm
- GitHub Check: build-lnx
- GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
- GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
- GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
- GitHub Check: build-macos
- GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
- GitHub Check: build-and-test (macos-26, xcode, 26.0)
- GitHub Check: build-macos-arm
- GitHub Check: build-win
🔇 Additional comments (1)
src/pyOpenMS/tests/unittests/test000.py (1)
3643-3738: MSChromatogram and MRMTransitionGroup dataframe tests correctly updated for non‑default chromatogram fieldsThe revised expectations for default column counts and the new explicit‑column checks for
chromatogram_typeandcommentline up with the updatedMSChromatogram.get_df/get_df_columnsbehavior (non‑default fields only when explicitly requested) and theMRMTransitionGroupCP.get_chromatogram_dfwrapper. This keeps the core smoke tests intest000.pyconsistent with the more detailed unit tests intest_dataframe_columns.pywhile preserving backward compatibility for the default column set.Also applies to: 3899-3933
|
Next items:
Key insight: MSSpectrum is the only class with get_data_dict() at the Cython level. This is actually the ideal pattern - it keeps pandas as an optional dependency and provides efficient access. Other classes should follow this pattern.
Memory copies:
Inefficient patterns in _dataframes.py: ConsensusMap.get_df() - computes everything first, then filtersdf = pd.concat([self.get_metadata_df(), self.get_intensity_df()], axis=1) Efficient pattern in MSSpectrum.pyx: Only compute requested columnsdef want(col): if want('mz'):
Correctly handled:
Issues found:
Recommendations High Priority
Medium Priority
Low Priority
● Research complete. The key findings are: Biggest wins from potential changes:
The MSSpectrum implementation you recently added is actually the model to follow - having get_data_dict() in Cython that returns numpy arrays, then get_df() as a thin Python wrapper that just calls pd.DataFrame(self.get_data_dict()). This keeps pandas optional and |
…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]>
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/pyOpenMS/pyopenms/_dataframes.py (1)
1069-1145: Fix TypeError in get_feature_df() when called without meta_values parameterThe function crashes with
TypeError: 'NoneType' object is not iterablewhen called without specifyingmeta_values, despite the docstring example showingdf = mrm.get_feature_df()as valid usage. The issue is inextract_meta_dataat line 1110, which unconditionally iteratesfor m in meta_valueseven whenmeta_valuesisNone.Normalize
meta_valuesto an empty list whenNonebefore the metadata processing block:# get all possible meta value keys in a set features = self.getFeatures() mddtypes = [('feature_id', _np.dtype('uint64')), ('rt', 'f'), ('intensity', 'f'), ('quality', 'f')] + if meta_values is None: + meta_values = [] - if meta_values is not None: + if meta_values is not None and meta_values != []: # Add all possible meta values to meta_value array if 'all' is passedThis ensures
extract_meta_datacan always safely iterate overmeta_values, while preserving existing behavior for explicit lists and'all'.
🧹 Nitpick comments (5)
src/pyOpenMS/pyopenms/_dataframes.py (5)
101-135: Consider either using or dropping thecolumnsparameter in ConsensusMap.get_df_columns
get_df_columns()currently ignores itscolumnsargument and always returns the same set of metadata+intensity columns; this is functionally fine, but it leaves an unused-argument warning and suggests a future feature that doesn’t exist yet. Either implement a real'all'mode (e.g., including meta values) or drop/undocument the parameter to avoid confusion.
362-472: Handlemeta_values=Noneand refine column filtering in FeatureMap.get_dfThe overall generator + dtype construction pattern is solid and existing meta_values handling is preserved, but two small tweaks would improve robustness and clarity:
- Normalize
meta_valuesearly (e.g.,if meta_values == 'all': ... elif not meta_values: meta_values = []) so downstream code never has to special-caseNone.- The
columnsfilter logic around thefeature_idindex is a bit indirect; explicitly treating'feature_id'as index-only makes intent clearer.A concrete cleanup could look like:
- elif not meta_values: # if None, set to empty list - meta_values = [] + elif not meta_values: # if None or empty, use no meta-value columns + meta_values = [] @@ - # Filter columns if requested - if columns is not None: - available_cols = [c for c in columns if c in df.columns or c == 'feature_id'] - # feature_id is the index, handle it specially - if 'feature_id' not in available_cols: - available_cols = [c for c in columns if c in df.columns] - df = df[[c for c in available_cols if c in df.columns]] + # Filter columns if requested (feature_id always stays as index) + if columns is not None: + available_cols = [c for c in columns if c in df.columns] + df = df[available_cols]This keeps behavior for typical usages while simplifying the special handling of the index.
510-579: MSExperiment.get_df: new column-selection is fine, but avoid mutable default and tighten docsThe updated implementation correctly supports
columns=[...]for both long and compact formats and aligns withget_df_columns(), but two minor cleanups are advisable:
- Replace the mutable default
ms_levels: List[int] = []withms_levels: Union[None, List[int]] = Noneand normalize inside the function to avoid the usual Python gotcha around shared default lists.- The docstring examples now consistently use
rtin the compact/long cases, which matches the column names returned byget_df_columns()and used in the tests.Suggested signature adjustment:
- def get_df(self, columns: Union[None, List[str]] = None, ms_levels: List[int] = [], long : bool = False): + def get_df(self, columns: Union[None, List[str]] = None, ms_levels: Union[None, List[int]] = None, long: bool = False): @@ - if not ms_levels: + if not ms_levels: ms_levels = self.getMSLevels()(Optionally also treating
ms_levels=[]passed by callers the same way.)
580-735: MassQL ion-mobility export usesion_mobilitycolumn—align docs and callersThe change to add
"ion_mobility"to the dtype map whenion_mobility=Trueand pass that through_get_ion_spec_arrayscleanly extends MassQL exports, but the docstring still refers to a column named'ion'. To avoid confusion for downstream MassQL code, it would be good to either (a) update the docs and any reference TSV headers toion_mobility, or (b) keep the external column name'ion'while usingion_mobilityonly internally.
998-1017: get_chromatogram_df_columns reuses MSChromatogram logic appropriately, but has a minor naming mismatch in examplesDelegating discovery to
_MSChromatogramDF(...).get_df_columns()ensures MRMTransitionGroupCP chromatogram column lists stay in sync with standalone MSChromatogram behavior, and the empty-group fallback columns look reasonable. The example inget_chromatogram_df()’s docstring still mentions'time', though, while the actual column is nowrt; consider updating that example to prevent user confusion.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/pyOpenMS/addons/IntegerDataArray.pyx(1 hunks)src/pyOpenMS/addons/MSChromatogram.pyx(1 hunks)src/pyOpenMS/pyopenms/_dataframes.py(13 hunks)src/pyOpenMS/tests/unittests/test000.py(4 hunks)src/pyOpenMS/tests/unittests/test_dataframe_columns.py(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/pyOpenMS/tests/**/*.py
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Write pyOpenMS tests for new Python bindings
Files:
src/pyOpenMS/tests/unittests/test_dataframe_columns.pysrc/pyOpenMS/tests/unittests/test000.py
🧠 Learnings (3)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/**/*.h : Add Doxygen comments for new public methods and classes in pyOpenMS bindings
Applied to files:
src/pyOpenMS/addons/MSChromatogram.pyx
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/tests/**/*.py : Write pyOpenMS tests for new Python bindings
Applied to files:
src/pyOpenMS/tests/unittests/test000.py
📚 Learning: 2025-04-07T21:16:06.557Z
Learnt from: jpfeuffer
Repo: OpenMS/OpenMS PR: 7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.
Applied to files:
src/pyOpenMS/pyopenms/_dataframes.py
🧬 Code graph analysis (1)
src/pyOpenMS/tests/unittests/test_dataframe_columns.py (1)
src/pyOpenMS/pyopenms/_dataframes.py (8)
get_df_columns(101-135)get_df_columns(310-343)get_df_columns(510-532)get_df(36-84)get_df(241-269)get_df(363-471)get_df(534-578)get_df(945-992)
🪛 GitHub Check: CodeFactor
src/pyOpenMS/pyopenms/_dataframes.py
[notice] 363-471: src/pyOpenMS/pyopenms/_dataframes.py#L363-L471
Complex Method
[notice] 363-471: src/pyOpenMS/pyopenms/_dataframes.py#L363-L471
Complex Method
🪛 Ruff (0.14.7)
src/pyOpenMS/pyopenms/_dataframes.py
101-101: Unused method argument: columns
(ARG002)
534-534: Do not use mutable data structures for argument defaults
Replace with None; initialize within function
(B006)
565-565: zip() without an explicit strict= parameter
Add explicit value for parameter strict=
(B905)
811-811: Consider iterable unpacking instead of concatenation
Replace with iterable unpacking
(RUF005)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
- GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
- GitHub Check: cppcheck-test
- GitHub Check: build-lnx
- GitHub Check: build-lnx-arm
- 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 (windows-2022, cl.exe, 14.36)
- GitHub Check: build-and-test (macos-26, xcode, 26.0)
- GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
- GitHub Check: build-win
🔇 Additional comments (10)
src/pyOpenMS/addons/IntegerDataArray.pyx (1)
29-61: Safe copy implementation looks good.The updated
get_data()correctly creates an independent copy of the data, and the comprehensive docstring clearly documents the safety guarantees. The loop-based copy is appropriate for Cython and ensures data independence.src/pyOpenMS/tests/unittests/test_dataframe_columns.py (1)
19-385: Thorough DF column-selection test coverage looks correctThe MSSpectrum/MSChromatogram tests exercise default vs explicit columns, meta-value toggling, non-default fields (ion_mobility_unit, chromatogram_type, comment), empty/missing-precursor cases, and backward-compatibility calls in a realistic way; they align well with the new get_df/get_df_columns/get_data_dict semantics with no obvious edge cases missing for this PR’s scope.
src/pyOpenMS/tests/unittests/test000.py (2)
3723-3738: MSChromatogram default vs explicit column behavior is well specifiedThe updated assertions and comments clearly encode the new contract that
get_df()defaults excludechromatogram_typeandcomment, while still including meta values likeFWHM, and that these non-default columns are only tested via explicitcolumns=[...], which matches the new Cython/DataFrame implementation.
3922-3985: MRMTransitionGroupCP chromatogram/feature DataFrame tests correctly track new schemaThe revised expectations for
get_chromatogram_df()(rt-based, 6 default columns, non-default chromatogram_type/comment only via explicit columns) andget_feature_df()(usingrtinstead of legacytime/RTand verifying rt values for both explicit andmeta_values='all'cases) accurately reflect the updated DataFrame export API and strengthen regression coverage without introducing fragility.src/pyOpenMS/addons/MSChromatogram.pyx (2)
7-49: MSChromatogram.get_df_columns matches documented/default column contractThe default column list, handling of the
'all'mode, and inclusion of decoded meta-value keys all align with the new MSChromatogram DataFrame API and with the tests; behavior for unknowncolumnsvalues is simply to ignore them, which is reasonable for now.
51-200: get_data_dict pre-filters columns efficiently and handles meta types robustlyThe implementation reuses the optimized
get_peaks()output, pre-filters standard vs non-default columns viawant/want_explicit, and casts meta values into appropriate NumPy dtypes with safe fallbacks, closely mirroring the proven MSSpectrum pattern and avoiding post-filtering overhead. The choice to always fill precursor/product/native_id fields when requested, even if unset (defaulting to zeros/empty), is a consistent, if slightly opinionated, behavior and fits the current tests.src/pyOpenMS/pyopenms/_dataframes.py (4)
36-84: MSSpectrum.get_df wrapper correctly negotiates new Cython signature while preserving fallbackForwarding
columnsandexport_meta_valuesintoget_data_dict, with a TypeError fallback to the legacy signature, provides column-restricted exports on new builds while remaining backward-compatible with older binaries; constructing the DataFrame directly from the returned dict keeps the wrapper thin and efficient.
241-270: ConsensusMap.get_df column filtering is straightforward and matches new discovery helperConcatenating
get_metadata_df()andget_intensity_df()and then optionally subsetting to user-specified columns (ignoring unknown names) gives the expected behavior, and the use ofrt/mzin metadata aligns with the standardized naming used elsewhere in the PR.
310-343: FeatureMap.get_df_columns provides a useful discovery surface for both core and meta columnsThe helper’s separation of
feature_id, optional peptide-identification columns, core numeric fields, and (in'all'mode) discovered meta-value names gives callers a clear way to constructcolumns=[...]selections without manually inspecting the map, and matches the behavior exercised in existing FeatureMap tests.
936-997: MSChromatogramDF wrapper is consistent with MSSpectrum and enables column-restricted exportsWrapping MSChromatogram with
_MSChromatogramDFand delegatingget_df()to the new Cythonget_data_dict(columns=..., export_meta_values=...), with a TypeError fallback, mirrors the MSSpectrum pattern and gives a uniform, efficient API for chromatogram DataFrame exports across the library.
…n 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]>
- 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]>
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/pyOpenMS/pyopenms/_dataframes.py (1)
1167-1243: MRMTransitionGroupCPDF.get_feature_df: column filtering behaves as intended; docstring naming laggingThe structured-array build, index on
feature_id, and optional meta-value typing mirror the FeatureMap pattern and look correct. The finalcolumnsfilter behaves as expected, withfeature_idremaining as the index. The docstring example still uses'RT'rather than'rt', which no longer matches the generated column names; it would be good to update that example to the new naming scheme.
🧹 Nitpick comments (6)
src/pyOpenMS/addons/Mobilogram.pyx (1)
117-157: Mobilogram len/repr look solid; consider RT handling edge caseThe size proxy and human-readable
__repr__are fine and avoid extra work when empty. The only nuance: thertfield is omitted whengetRT()returns exactly0, even though0.0can be a valid RT. If you want to show RT whenever it’s set (including 0), consider changing the condition toif rt >= 0or checking against a sentinel instead.src/pyOpenMS/pyopenms/_dataframes.py (5)
37-85: MSSpectrumDF.get_df correctly delegates to Cython get_data_dict but silently ignores columns on old buildsThe new
columnsandexport_meta_valuesparameters are wired as intended for modern Cython builds and match the MSSpectrum addon pattern. On older builds whereget_data_dictlacks acolumnsargument, theTypeErrorfallback means any user-suppliedcolumnswill be ignored while still returning a full DataFrame. If that silent degradation is undesirable, you might want to raise or log whencolumns is not Nonebut the fallback path is taken.
472-517: FeatureMapDF.get_df: column filtering logic works but could be simplifiedThe index-based construction and DataFrame build look correct, and the filtering step respects the requested column order. The special-casing of
'feature_id'(which isn’t indf.columnsbecause it’s the index) effectively results in silently ignoring it, which is fine, but the two-stepavailable_colscomputation is more complex than necessary. You could equivalently dodf = df[[c for c in columns if c in df.columns]]and document thatfeature_idis always the index.
579-624: MSExperimentDF.get_df: behavior is correct; avoid mutable default for ms_levelsThe long/compact branches, MS-level filtering, and post-hoc
columnsfiltering are all implemented correctly. However, the defaultms_levels: List[int] = []triggers Ruff’s B006 recommendation and is generally discouraged in Python, even if you don’t mutate the list. Consider changing the signature toms_levels: Optional[List[int]] = Noneand treatingNonethe same as the current empty-list behavior.
856-859: peptide_identifications_to_df: rt/mz renaming and column list are coherent; unpacking nitSwitching
clearcolsto use lowercase"rt"/"mz"aligns with the rest of the DataFrame API. If you want to satisfy Ruff’s RUF005, you could rewrite the list construction using iterable unpacking (e.g.,["id", "rt", "mz", mainscorename, "charge", *base_cols, *decodedMVs]), but that’s purely stylistic.
981-1041: MSChromatogramDF wrapper correctly reuses Cython get_data_dict with a robust fallbackThe wrapper’s
get_dfsignature and docstring are consistent with the MSSpectrum pattern, and delegating to the Cythonget_data_dict(columns=..., export_meta_values=...)keeps the Python side thin. As with MSSpectrum, on older builds whereget_data_dictdoesn’t acceptcolumns, user-suppliedcolumnswill be ignored in the fallback; that’s acceptable but worth being aware of.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/pyOpenMS/addons/Mobilogram.pyx(1 hunks)src/pyOpenMS/addons/StringDataArray.pyx(1 hunks)src/pyOpenMS/pyopenms/_dataframes.py(16 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/**/*.h : Add Doxygen comments for new public methods and classes in pyOpenMS bindings
Applied to files:
src/pyOpenMS/addons/Mobilogram.pyx
📚 Learning: 2025-04-07T21:16:06.557Z
Learnt from: jpfeuffer
Repo: OpenMS/OpenMS PR: 7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.
Applied to files:
src/pyOpenMS/pyopenms/_dataframes.py
🧬 Code graph analysis (1)
src/pyOpenMS/pyopenms/_dataframes.py (2)
src/openms/include/OpenMS/KERNEL/MSSpectrum.h (1)
updateRanges(197-367)src/openms/source/KERNEL/MSSpectrum.cpp (6)
updateRanges(530-578)updateRanges(530-530)getRT(580-583)getRT(580-580)getMSLevel(615-618)getMSLevel(615-615)
🪛 Ruff (0.14.7)
src/pyOpenMS/pyopenms/_dataframes.py
102-102: Unused method argument: columns
(ARG002)
579-579: Do not use mutable data structures for argument defaults
Replace with None; initialize within function
(B006)
610-610: zip() without an explicit strict= parameter
Add explicit value for parameter strict=
(B905)
856-856: Consider iterable unpacking instead of concatenation
Replace with iterable unpacking
(RUF005)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
- GitHub Check: build-lnx-arm
- GitHub Check: build-lnx
- GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
- GitHub Check: build-and-test (ubuntu-22.04-arm, g++, 11)
- GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
- GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
- GitHub Check: build-win
- GitHub Check: cppcheck-test
🔇 Additional comments (10)
src/pyOpenMS/addons/StringDataArray.pyx (1)
33-65: StringDataArray.get_data correctly exposes a safe Python copy of the dataImplementation mirrors
__getitem__’s casting logic, handles empty arrays, and returns a plain Python list, which is exactly what users expect for downstream use. No changes needed.src/pyOpenMS/addons/Mobilogram.pyx (1)
159-234: Mobilogram get_df_columns/get_data_dict align with the new DF export modelThe column names (
mobility,intensity,rt,drift_time_unit) match the standardized, lowercase scheme, andget_data_dict(columns=...)cleanly filters to requested columns while keeping defaults whencolumns is None. The always-onget_peaks()call is acceptable here, given Mobilogram’s limited column set, and the drift time unit handling (decode + broadcast) looks correct.src/pyOpenMS/pyopenms/_dataframes.py (8)
242-305: ConsensusMapDF.get_df column selection logic is sound and avoids unnecessary workThe new
columnshandling correctly:
- Computes metadata/intensity tables only when their columns are requested.
- Falls back to the full join when
columns is None.- Filters the final DataFrame in the order requested by the caller.
The empty-DataFrame behavior when no requested columns match is also reasonable. No functional issues from this change.
345-379: FeatureMapDF.get_df_columns provides a clear, extensible column catalogueThe core/peptide columns are well-structured, and the
'all'branch that inspects features’ meta keys to append sorted meta-value column names gives users a good discovery mechanism. This pairs cleanly with the new column-based export logic below.
398-417: FeatureMapDF.get_df: gating peptide ID export on requested columns is a good optimizationUsing
pep_id_colsandcolumnsto decide whether peptide-identification fields are actually needed avoids building those columns when the caller doesn’t request them, while preserving existing behavior whencolumns is None. This is a nice performance/complexity win without changing the public API.
555-578: MSExperimentDF.get_df_columns cleanly documents long vs compact formatsThe returned column sets (
['rt', 'mz', 'intensity', 'ms_level']for long and['rt', 'ms_level', 'mz_array', 'intensity_array']for compact) match the docstring and the actualget_dfimplementation, which should make column discovery straightforward for users.
625-635: get_ion_df: new ion_mobility column wiring is consistentAdding
"ion_mobility"to bothcolsand thedtypesmap keeps column order and types in sync with the 2D data returned byget2DPeakDataIMLong. This looks correct and matches the massql-style ion mobility semantics elsewhere.
760-777: MassQL ion_mobility dtypes update is coherent with get_ion_dfExtending
dtypeswith"ion_mobility": "float32"when ion mobility is requested keeps the MS1/MS2 DataFrames well-typed without altering existing columns. No issues here.
1044-1093: MobilogramDF wrapper matches Mobilogram.pyx semantics and column naming
_MobilogramDF.get_dfsimply wrapsget_data_dict(columns=...)and returns a DataFrame, so it stays in sync with the Mobilogram addon’s column semantics (mobility,intensity,rt,drift_time_unit) and supports column-restricted exports. The TypeError fallback keeps older builds working, with the same caveat thatcolumnswill be ignored if the underlying Cython function lacks that parameter.
1116-1137: MRMTransitionGroupCPDF.get_feature_df_columns: column discovery logic is fineCore columns (
feature_id,rt,intensity,quality) and the'all'meta-value discovery behavior are sensible and parallel the FeatureMap pattern. No functional issues here.
- 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]>
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]>
Description
This pull request introduces improvements to spectrum and chromatogram data export functionality in
pyOpenMS, focusing on flexible column selection and performance optimization. The changes add new methods to discover available columns, allow users to select specific columns for export, and update unit tests to reflect the new default and explicit column behaviors.Flexible Data Export and Column Selection
get_df_columnstoMSSpectrum.pyxthat returns all available column names for a spectrum, supporting both default and "all" modes to include custom data arrays and meta values.get_data_dictinMSSpectrum.pyxto accept acolumnsargument, enabling export of only requested columns for improved performance; now supports explicit selection of custom data arrays and meta values. [1] [2] [3]Unit Test Updates for Default and Explicit Columns
testMSChromatogramintest000.pyto assert the correct default columns (now 7 instead of 9), and added tests for explicit inclusion of non-default columns likechromatogram_typeandcomment.testMRMTransitionGroupintest000.pyto assert the new default column count (now 6 instead of 8), and added tests for explicit selection of non-default columns.Checklist
How can I get additional information on failed tests during CI
Click to expand
If your PR is failing you can check outIf you click in the column that lists the failed tests you will get detailed error messages.
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.rebuild jenkinswill retrigger Jenkins-based CI buildsSummary by CodeRabbit
New Features
Tests
✏️ Tip: You can customize this high-level summary in your review settings.