Skip to content

(feat,pyopenms): add XIMParquetFile pyopenms bindings - #8894

Merged
timosachsenberg merged 7 commits into
OpenMS:developfrom
singjc:feature/xim_pyopenms_only
Mar 13, 2026
Merged

timosachsenberg merged 7 commits into
OpenMS:developfrom
singjc:feature/xim_pyopenms_only

Conversation

@singjc

@singjc singjc commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Description

Added python bindings fir the extracted ion mobilogram parquet files introduced in PR #8871. The bindings are pretty much the same as the XIC parquet fles python bindings.

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

Summary by CodeRabbit

  • New Features

    • Added XIMParquetFile for reading and analyzing ion-mobility Parquet data.
    • Chainable query builder for flexible mobilogram filtering.
    • Export mobilogram data to pandas DataFrame and PyArrow table.
    • Direct access to run and analyte metadata and rich mobilogram structures.
  • Tests

    • Added unit tests covering schema, queries, DataFrame/arrow exports, and metadata access.

@coderabbitai

coderabbitai Bot commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds Python bindings and a high-level addon for OpenMS::XIMParquetFile: C++ bindings exposing file/column/run/analyte/mobilogram access and a Python addon with DataFrame/Arrow/dict conversions, a chainable mobilogram query builder, and unit tests.

Changes

Cohort / File(s) Summary
C++ Bindings
src/pyOpenMS/bindings/bind_format.cpp
Added XIMParquetFile Python binding under WITH_PARQUET: constructors, copy/deepcopy, __repr__/__str__, getFilename(s), getColumns, getRuns, getAnalytes, and getMobilograms with appropriate policies.
Python addon & query
src/pyOpenMS/pyopenms/addons/ximparquetfile.py
New addon implementing _MobilogramQuery (chainable filters) and public methods: __len__, df_columns, get_data_dict, get_run_dict, get_run_df, get_analyte_dict, get_analyte_df, to_df, to_arrow, and query_mobilograms. Adds pandas/pyarrow import checks and explode handling.
Tests
src/pyOpenMS/tests/unittests/test_XIMParquetFile.py
New unit tests covering schema columns, run/analyte dicts (including column-filtering and errors), DataFrame/expanded conversions, and _MobilogramQuery filtering behaviors; tests skip when parquet support missing.
Changelog
CHANGELOG
Recorded addition of XIMParquetFile Python bindings entry.

Sequence Diagram

sequenceDiagram
    actor User
    participant PyAddon as XIMParquetFile<br/>(Python addon)
    participant CppBind as XIMParquetFile<br/>(C++ binding)
    participant Parquet as Parquet Data<br/>Layer
    participant Output as Formatter<br/>(DF/Dict/Arrow)

    User->>PyAddon: query_mobilograms() / build filters
    activate PyAddon
    PyAddon-->>CppBind: getMobilograms(filters..., explode)
    activate CppBind
    CppBind->>Parquet: read/scan Parquet files
    activate Parquet
    Parquet-->>CppBind: mobilogram records (dict)
    deactivate Parquet
    CppBind-->>PyAddon: mobilogram dict/result
    deactivate CppBind
    PyAddon->>Output: convert to DataFrame/Arrow/dict
    activate Output
    Output-->>PyAddon: formatted result
    deactivate Output
    PyAddon-->>User: return result
    deactivate PyAddon
Loading

Possibly Related PRs

Poem

🐇 In a parquet burrow data hums and hops,
Mobilograms lined in tidy little drops,
I filter and nest with a twitch of my nose,
To DataFrames and Arrows the pathway glows,
A rabbit's small dance where ion-story crops.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately describes the main change: adding Python bindings for XIMParquetFile.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@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: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/pyOpenMS/bindings/bind_format.cpp`:
- Around line 2181-2201: The loop currently iterates using c.mobility.size() but
then accesses c.intensity[j], risking OOB if the vectors differ; change the
iteration to use a safe size (e.g., size_t n = std::min(c.mobility.size(),
c.intensity.size())) and loop j from 0 to n, or explicitly check that
c.mobility.size() == c.intensity.size() before the loop and handle the mismatch
(skip, truncate, or log/error) so accesses to c.mobility[j] and c.intensity[j]
are always in-bounds; update the loop around the block that appends into
run_id_list, mobility_list, intensity_list accordingly (referencing c.mobility,
c.intensity and the for loop using j).

In `@src/pyOpenMS/pyopenms/addons/ximparquetfile.py`:
- Around line 20-25: The _add_filter function currently builds IN-list filters
by joining raw str(v) which breaks for string elements and doesn't escape
quotes; update _add_filter to detect string elements and wrap them in quoted,
escaped form (e.g., replace any internal quote characters or use a safe quoting
routine) before joining so the produced "column IN ('a','b')" is valid; apply
the same quoting/escaping logic to the other filter-construction code referenced
around the same region (the similar filter-building block at lines 46-59) so all
list/tuple values are consistently quoted and escaped.
- Around line 81-84: The __len__ implementation currently swallows all
exceptions by using a bare "except Exception:" around self.getFilenames(), which
hides real errors; update the __len__ method in ximparquetfile.py (and mirror
change in xicparquetfile.py) to either remove the try/except so exceptions
propagate, or catch only the expected exceptions (e.g., AttributeError,
TypeError, or the library-specific exception raised by getFilenames()) and
re-raise or return 0 only for those specific cases; ensure you reference the
method name __len__ and the call self.getFilenames() when making the change so
the behavior is explicit and unexpected errors are not silently swallowed.
- Around line 101-103: The parameter name "filter" in get_data_dict shadows a
Python builtin; rename it to "filter_expr" in the function signature of
get_data_dict, update every reference inside the function body (including any
use in conditionals or variable access), update the docstring parameter
description to use "filter_expr", and update any calls to get_data_dict within
this module that pass the old "filter" keyword to use "filter_expr" instead so
all references to the old name are replaced consistently.

In `@src/pyOpenMS/tests/unittests/test_XIMParquetFile.py`:
- Around line 93-109: The test assumes the first precursor_id from
xim.get_analyte_dict(columns=["PRECURSOR_ID"], nest_transitions=False) is
non-null; change the test_xim_query_builder (and the earlier test usage) to
select the first non-null precursor_id instead of blindly using
analytes["precursor_id"][0] so the test isn't flaky. Locate usages of
get_analyte_dict and replace the direct index access with logic that filters out
None/NaN values (e.g., iterate or use a comprehension to find the first valid
value) before passing it into xim.query_mobilograms().filter_precursor_id(...).
Ensure the same change is applied in both the initial assertions block and
test_xim_query_builder referencing precursor_id.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: baa1c58d-949e-44c6-95dc-489552631f60

📥 Commits

Reviewing files that changed from the base of the PR and between 88f2819 and 3beb0ee.

📒 Files selected for processing (3)
  • src/pyOpenMS/bindings/bind_format.cpp
  • src/pyOpenMS/pyopenms/addons/ximparquetfile.py
  • src/pyOpenMS/tests/unittests/test_XIMParquetFile.py

Comment thread src/pyOpenMS/bindings/bind_format.cpp 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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/pyOpenMS/pyopenms/addons/ximparquetfile.py`:
- Around line 117-171: The get_data_dict function accepts **kwargs but silently
ignores them; update get_data_dict to handle legacy/alias kwargs (e.g.,
'filter') or fail loudly: check if 'filter' is present in kwargs and, if so, pop
it and assign to filter_expr before calling self.getMobilograms; after handling
known aliases, if kwargs is not empty raise a TypeError listing unexpected
kwargs so callers are not silently ignored. Ensure you reference get_data_dict,
the filter_expr variable, and the call to
self.getMobilograms(filter=filter_expr, ...) when making the change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2ad38fed-acc1-442c-937b-91ba1a35178e

📥 Commits

Reviewing files that changed from the base of the PR and between 3beb0ee and e6dd253.

📒 Files selected for processing (4)
  • CHANGELOG
  • src/pyOpenMS/bindings/bind_format.cpp
  • src/pyOpenMS/pyopenms/addons/ximparquetfile.py
  • src/pyOpenMS/tests/unittests/test_XIMParquetFile.py
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG

Comment on lines +117 to +171
filter_expr="",
**kwargs,
):
"""
Return mobilogram data as a dict.

If explode=True, returns long format with mobility/intensity rows.
Otherwise, mobility and intensity are stored as lists.

Parameters
----------
explode : bool
If True, return long format with one row per mobility/intensity.
precursor_id : int
Optional precursor id (-1 to ignore).
transition_id : int
Optional transition id (-1 to ignore).
modified_sequence : str
Optional modified sequence filter (empty to ignore).
precursor_charge : int
Optional precursor charge filter (-1 to ignore).
product_charge : int
Optional product charge filter (-1 to ignore).
ms_level : int
Optional MS level filter (-1 to ignore).
run_id : int
Optional run id filter (-1 to ignore).
mobilogram_type : str
Optional mobilogram type filter (empty to ignore).
feature_id : int
Optional feature id filter (-1 to ignore).
feature_rt : float
Optional feature RT filter (<0 to ignore).
filter_expr : str
Optional filter expression string.

Returns
-------
dict
Dict of lists keyed by column name.
"""
return self.getMobilograms(
precursor_id=precursor_id,
transition_id=transition_id,
modified_sequence=modified_sequence,
precursor_charge=precursor_charge,
product_charge=product_charge,
ms_level=ms_level,
run_id=run_id,
mobilogram_type=mobilogram_type,
feature_id=feature_id,
feature_rt=feature_rt,
filter=filter_expr,
explode=explode,
)

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.

⚠️ Potential issue | 🟠 Major

Handle legacy/unknown kwargs explicitly in get_data_dict.

At Line 118, **kwargs is accepted but never used. Calls like get_data_dict(filter="...") will silently drop the filter and return unfiltered results.

🔧 Proposed fix
 def get_data_dict(
@@
     feature_rt=-1.0,
     filter_expr="",
     **kwargs,
 ):
@@
+    # Backward compatibility with older keyword name used in related APIs.
+    if "filter" in kwargs:
+        if filter_expr:
+            raise TypeError("Use only one of 'filter_expr' or 'filter'.")
+        filter_expr = kwargs.pop("filter")
+
+    if kwargs:
+        unexpected = ", ".join(sorted(kwargs.keys()))
+        raise TypeError(f"Unexpected keyword argument(s): {unexpected}")
+
     return self.getMobilograms(
@@
         filter=filter_expr,
         explode=explode,
     )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/pyOpenMS/pyopenms/addons/ximparquetfile.py` around lines 117 - 171, The
get_data_dict function accepts **kwargs but silently ignores them; update
get_data_dict to handle legacy/alias kwargs (e.g., 'filter') or fail loudly:
check if 'filter' is present in kwargs and, if so, pop it and assign to
filter_expr before calling self.getMobilograms; after handling known aliases, if
kwargs is not empty raise a TypeError listing unexpected kwargs so callers are
not silently ignored. Ensure you reference get_data_dict, the filter_expr
variable, and the call to self.getMobilograms(filter=filter_expr, ...) when
making the change.

@timosachsenberg
timosachsenberg merged commit 4c934ac into OpenMS:develop Mar 13, 2026
17 of 19 checks passed
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.

2 participants